How to send ember js header request without ember data - wordpress

I'm trying to make a call to the wp-api.org plugin for Wordpress. I want to show all users, and I want to use cookie authentication. Therefore I need to send a header request as explained on the website like this:
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
if (beforeSend) {
return beforeSend.apply(this, arguments);
}
};
The following code I am using in my model:
App.UsersRoute = Ember.Route.extend({
model: function() {
return Ember.$.ajax({
url: "http://myurl.com/wp-json/users/",
type: "GET",
dataType: "json",
data: JSON.stringify({}),
beforeSend: xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
});
}
});
At the moment the site returns this message because the authentication failed, but I am logged in and cookies are set:
[{"code":"json_user_cannot_list","message":"Sorry, you are not allowed to list users."}]

This should work:
App.UsersRoute = Ember.Route.extend({
model: function() {
return Ember.$.ajax({
url: "http://myurl.com/wp-json/users/",
type: "GET",
dataType: "json",
data: JSON.stringify({}),
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
}
});
}
});

the beforeSend property needs to be a function that is passed xhr, like in your first example, in your second code snippet xhr will be undefined.

Related

Ajax data not passing to controller

I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}

Fullcalendar jquery plugin loading times after selecting and inserting new events

I am using fullcalendar plugin for our users to set their available times. Now everything works fine when reloading the page and when user adds one event, but when they add another event or start selecting, the page almost frozes. I tried all the solutions I found out on Stack but nothing.
I tried calendar.fullCalendar('addEventSource', response.new_events); to add only the new events returned, but lag persist. Tried removing all the eventRender functions, but still the same result. Only thing that seems to work is when I reload the page after each event insert.
IS there any way to decrease the lag while adding new eventSource after select?
These are the parts of my calendar js code
eventSources: [{
url: '/nanny/calendar/availability/all',
type: 'GET',
success: function (response) {
},
error: function (jqXhr, textStatus, errorThrown, data) {
$(".loading-icon").hide();
console.log(jqXhr, textStatus, errorThrown, data);
},
}],
eventRender: function (event, element) {
var delete_icon = '<i style="float: right; cursor: pointer;" class="' + event.icon + '"></i>';
if (event.icon) {
element.find("div.fc-time").append(delete_icon);
}
},
eventAfterRender: function (event, $el, view) {
$(".loading-icon").hide();
var formattedTime = $.fullCalendar.formatRange(event.start, event.end, "HH:mm");
// if event has fc-short class, data-start value will be displayed
// remove fc-short class and update fc-time span text
if ($el.is('.fc-short')) {
$el.find(".fc-time span").text(formattedTime + " - " + event.title);
$el.removeClass('fc-short');
$el.find('.fc-title').remove();
}
},
select: function (start, end) {
//in the past so give error
if (start.isBefore(moment())) {
$('#calendar').fullCalendar('unselect');
return false;
}
//get the event data
eventData = {
start: moment(start).format('YYYY-MM-DD HH:mm:ss'),
end: moment(end).format('YYYY-MM-DD HH:mm:ss')
};
if (eventData) {
if (eventData) {
$.ajax({
type: "POST",
url: "/nanny/calendar/store",
data: eventData,
dataType: "JSON",
success: function (response) {
console.log(response);
swal({
title: "Yay",
text: response.msg,
type: "success",
showCancelButton: false,
confirmButtonColor: "#e36159",
confirmButtonText: "CLose",
closeOnConfirm: false
});
calendar.fullCalendar('addEventSource', response.new_events);
},
error: function (jqXhr, textStatus, errorThrown, data) {
console.log(jqXhr, textStatus, errorThrown, data);
}
});
}
}
},
EDIT
Here's the video.
Lag example
A single event should be added using the renderEvent method. Create the event struct using the appropriate input and pass it to the renderEvent method.
$.ajax({
type: "POST",
url: "/nanny/calendar/store",
data: eventData,
dataType: "JSON",
success: function (response) {
var myEvent =
{
id: response.ID,
title: response.TITLE,
start: eventData.start,
end: eventData.end,
};
$( "#calendar" ).fullCalendar( "renderEvent", myEvent );
}
});
According to the documentation (https://fullcalendar.io/docs/event_data/Event_Object/) the start, end, and title attributes are required. If you are not collecting a title you can hardcode it to something such as "Event".
If you are updating your events in a db and want to allow your users to modify an event (ie. drag and drop, resize, etc.) without refreshing/reloading the calendar you must also provide the id attribute. This can be the unique key assigned to the meeting when stored in the database. You will want to pass this value back in the ajax response. If this functionality is not necessary, then you can ignore the id attribute.
**refetchEvents recall the function CalendarApp.prototype.init and refresh the calendar **
$.ajax({
url: "BASE_URL",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json"
},
type: "POST",
data: JSON.stringify(dataEvent),
dataType: "json",
contentType: "application/json",
success: function(data) {
window.swal({
title: "Checking...",
text: "Please wait",
buttons: false,
timer: 2000
});
$("#calendar").fullCalendar("refetchEvents",dataEvent);
}
});

Asynchronous ajax call causing issue in KnockOutjs

I have a button on click of that i am calling something like :
ViewModel:
self.MyArray = ko.observableArray();
self.remove = function(c) {
ko.utils.arrayForEach(c.sData(), function(ser) {
if (ser.Check() == true) {
self.MyArray.push(service);
count++;
}
});
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function(data) {
ko.utils.arrayForEach(self.MyArray(), function(removedata) {
c.sData.remove(removedata);
});
}
});
self.MyArray([]);
}
};
If i include async:false in my ajax call i get everything fine but if i didn't include async (its default property is true) i dont know somehow in my success function of ajax call self.MyArray() remains Empty but its not the case if i keep it false (Awkward).
Sometimes i fear like if i have series of ajax calls with async:true while loading into a observable array(OnLoad) there may be a slight chance of misplacement of data .
Help me understand .
The reason your observable array MyArray is empty sometimes is because this line of code self.MyArray([]); executing before the ajax call is done. How about this instead -
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function (data) {
ko.utils.arrayForEach(self.MyArray(), function (removedata) {
c.sData.remove(removedata);
});
},
complete: function() { // complete fires after success and error callbacks
self.MyArray([]); // empty the array no matter what happens (error or success)
}
});
}

X-editable with .Net and c# web methods

I am using X-Editable Plugin in Asp.net.
I have tried this: Usage with .Net and C# Webmethods
But it gives me error. It is not calling the WebMethod as it should be.
How to solve this problem?
Please help.
Javascript:
$('#username').editable({
url: function (params) {
return $.ajax({
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
HTML:
superuser
WebMethod in Default.aspx:
[System.Web.Services.WebMethod]
public static String TestMethod(String params)
{
//access params here
}
If you want to call a page method, first of all you need to make a request of type POST (also having content-type set will not do any harm):
$('#username').editable({
url: function (params) {
return $.ajax({
type: 'POST',
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
Also the JSON will be auto deserialized on server side, so you should expect the name, pk and value parameters on server side (this is what plugin is sending according to docs)
[System.Web.Services.WebMethod]
public static String TestMethod(string name, string pk, string value)
{
//access params here
}
In your case the pk will be null as you haven't set one.

jquery Post does not work in asp.net mvc 3?

I just copied some code from an asp.net mvc 2 app which works. Now i am trying it in asp.net mvc 3 and it does not call the save method on the controller?
controller:
[HttpPost]
public JsonResult save(string inputdata)
{
return Json(new { Result = string.Format("From the controller - you have clicked the GO-button ! ") }, JsonRequestBehavior.AllowGet);
}
view:
<button id="but">go</button>
<div id=result></div>
<script type="text/javascript">
$(document).ready(
$("#but").click(
function () {
$.ajax({
url: "/Home/save",
dataType: "json",
type: 'POST',
data: "test",
success: function (result) {
$("#result").html(result.Result);
}
});
}
)
);
</script>
You are not passing the data correctly. The action argument is called inputdata. So you should use this same name in the data hash of the AJAX request:
$.ajax({
url: '/Home/save',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Also never hardcode urls in your javascript, always use url helpers or your application will simply stop working when you deploy due to the possibility of having a virtual directory name:
$.ajax({
url: '#Url.Action("save", "home")',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Another issue that you have with your code is that you are not canceling the default action of the button meaning that if this is an action link or a submit button the AJAX request might never have the time to execute before the browser redirects.
Also you don't need to specify the dataType to JSON as jQuery is intelligent enough to deduce this from the Content-Type response header sent from the server.
So the final version should look something along the lines of:
<script type="text/javascript">
$(function() {
$('#but').click(function () {
$.ajax({
url: '#Url.Action("save", "home")',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
return false;
});
});
</script>

Resources