Multiple ajax calls in event function full calendar - javascript

I am using fullcalendar jQuery plugin in our page for create/view meeting invitation.
And my new requirement is to show meetings created in outlook for that particular user in our page . My webservice(used to pull meetings from outlook) took min of 45 secs to send the reponse . I don't want the user to wait completely for 45 secs .(Performance Issue) So I just want to load events from db first and then i want to append events coming back as webservice response . Hence user couldn't feel that much delay.
So I just made two ajax calls to pull required details. One ajax call is to pull events from local database(SUCCESS) and another one is to call the webservice to pull events created in Outlook.
events: function(start, end, timezone,callback) {
$.ajax({
url: // url hits db and gets meeting details in db
dataType: 'json',
success: function(response) {
var events = [];
if(response != null){
alert("Success");
$.map(response ,function ( r ){
alert(r.title + " " + r.start + " " + r.end);
events.push({
title : r.title,
start : r.start,
end : r.end
});
});
}
callback(events);
}
$.ajax({
url: // url calls webservice and gets meetings in Outlook
dataType: 'json',
success: function(response) {
var events = [];
if(response != null){
alert("Success");
$.map(response ,function ( r ){
alert(r.title + " " + r.start + " " + r.end);
events.push({
title : r.title,
start : r.start,
end : r.end
});
});
}
alert("External Events "+ events.length); //EXECUTED
callback(events); //NOT EXECUTED
}
});
}
And now the problem is ,
1 . First ajax call is working fine .
2 . Am getting proper response from Webservice but the response wasn't attached to calendar .
And my queries are ,
Can't we use callback(events) twice ?
Or else please suggest me the alternative solution for this ?
If am using two event function separately,only second event function will gets executed . Why first event function is not getting executed ?

A little old, but a way around for reference. In your first ajax call, instead of the callback, put in the second ajax call
$.ajax({
url: // url hits db and gets meeting details in db
dataType: 'json',
success: function(response) {
var events = [];
if(response != null){
alert("Success");
$.map(response ,function ( r ){
alert(r.title + " " + r.start + " " + r.end);
events.push({
title : r.title,
start : r.start,
end : r.end
});
});
}
//second call
$.ajax({
url: // url calls webservice and gets meetings in Outlook
dataType: 'json',
success: function(response) {
var events = [];
if(response != null){
alert("Success");
$.map(response ,function ( r ){
alert(r.title + " " + r.start + " " + r.end);
events.push({
title : r.title,
start : r.start,
end : r.end
});
});
}
alert("External Events "+ events.length);
callback(events); // return all results
}
});
}

Nothing is wrong with your code. Ensure the responses you're getting from your server is what you expect (response != null for instance).
https://jsfiddle.net/5ds8z06p/
var foo = function(callback) {
$.ajax({
url: '/echo/json',
success: function() {
callback('first');
}
});
$.ajax({
url: '/echo/json',
success: function() {
callback('second');
}
});
};
foo(function(bar) {
console.log(bar);
});

Related

Identifying AJAX request

I am triggering multiple AJAX requests in a loop. They run in parallel and it is not clear which one will respond first.
If the response is successful, I can identify the request by analyzing the response.
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
success: function (results) {
if (results.status == 'success'){
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log(error);
}
});
}
However, once in a while, the request fails and an error is triggered.
For a proper error handling, I would like to know to which of the (previously triggered) requests the error belongs.
Is there a clean method how a specific AJAX request can be identified?
I would recommend to pass in a identifier via context to the AJAX call which you can use inside the success or error methods:
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
// data inside "context" will be available as part of "this" in the success/error case.
context: {
"kk": kk
},
success: function (results) {
if (results.status == 'success'){
console.log("Element " + this.kk + " finished successfully.");
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log("Element " + this.kk + "failed.");
console.log(error);
}
});
}
More information regarding context can be found in the jQuery documentation.
Regarding your comment about checking how many calls failed / succeeded: here is a JsFiddle demonstrating how to keep track of the call statistics.

ajax data isn't the same in chrome vs firefox

Some reason I can return data fine from a POST in Chrome. The data returned looks like this when using Chrome:
{"email":"account#bytestand.com","customer_id":20413,"credit_amount":50.0,"currency_symbol":"$"}
But then when the same POST is completed on FireFox I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Somehow the data isn't being handled the same and I don't know why.
Here is the code that generates the ajax request
function getCustomerAndCredit() {
console.log("getCustomerAndCredit");
$(function() {
$("form[action='" + shopAddress + "/account/login']").submit(function(event){
console.log("this is past the submit event in Firefox");
var custEmail = $("form[action='" + shopAddress + "/account/login'] input[type=email]").val();
var pass = $("form[action='" + shopAddress + "/account/login'] input[type=password]").val();
sessionStorage.setItem('custEmail', custEmail);
sessionStorage.setItem('pass', pass);
sessionStorage.setItem('loggedIn', true);
debugger;
$.ajax({
url: "/apps/proxy/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "js",
complete: function(data) {
debugger;
if(noCustomerInDB(data)){
if(data.responseJSON == undefined){
sessionStorage.setItem('customer_id', JSON.parse(data.responseText).customer_id);
sessionStorage.setItem('creditAmount', JSON.parse(data.responseText).credit_amount);
sessionStorage.setItem('currency', JSON.parse(data.responseText).currency_symbol);
}
else {
sessionStorage.setItem('customer_id', data.responseJSON.customer_id);
sessionStorage.setItem('creditAmount', data.responseJSON.credit_amount);
sessionStorage.setItem('currency', data.responseJSON.currency_symbol);
}
}
// console.log("What is the credit_amount here in getCustomerAndCredit " + sessionStorage.getItem('creditAmount'));
},
});
});
});
}
And then this is where the data is going:
function noCustomerInDB(data){
console.log("this is the todd variable " + data);
console.log("stringify data " + JSON.stringify(data));
console.log("what about just data?? " + JSON.parse(data));
console.log("this is the response down here in the no customer function" + data.responseText);
if(data.responseText == ""){
return false;
}
else{
if (JSON.parse(data.responseText).customer_id == "no_customer"){
sessionStorage.setItem('creditAmount', "null");
return false;
}
else{
return true;
}
}
}
I did some more digging and now its looking like the ajax isn't being called on FireFox. Because the data returned from the POST looks like this:
{"readyState":0,"status":0,"statusText":"error"}
This cannot be - dataType: "js"
Use dataType: "json" instead. Also make sure that "/apps/proxy/return_customer" has the proper header configured to deploy JSON:
"Content-Type: application/json"

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

exec function before every ajax success callback

I have a website where I rely on a lot of custom API call. My API return always an XML.
Currently, at the start of each and every $.get or $.post I call, I have this snippet :
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
However, I feel this code to be much redundant on one of my page, it's used 15 times.
I tried to use the $(document).ajaxSuccess() but the event.stopPropagation don't seem to work here
Is there a way to "intercept" each and every ajax call responses, do some stuff and possibly prevent the call to other defined success functions ?
I assume that you have something like this in many places in your code
$.ajax({
method: "GET",
url: "someurl.html",
dataType: "xml",
success : function() {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
// ...
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
});
you could create a generic custom ajax function tha you can re-use
function baseAjaxCall(option, sCb) {
var ajaxOptions = {
method: option.method || "GET",
url: option.url,
dataType: option.dataType || "xml",
success : function(data) {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
else {
sCb(root);
}
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
};
//you can check for optional settings
if(option.contentType !== undefined){
ajaxOptions.contentType = option.contentType;
}
$.ajax(ajaxOptions);
}
everywhere in your code you can re-use the baseAjaxCall function
baseAjaxCall({ url: "someurl.html" }, function(root){
// no need to chek for errors here!
});
Hope it's helps!

jquery dialog pause a script like alert()

I have next javascript code:
function getLetterOfResponsibilityNote(dialogNoteLink, visitCountryName) {
$.ajax({
type: "GET",
url: "/Admin/Applications/GetLetterOfResponsibilityNote/?selectedCountryName=" + visitCountryName,
cache: false,
success: function(data) {
if (data != "") {
dialogNoteLink.dialog();
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
}
}
});
}
I want to call it, for example, 5 times and get data from server, then I will display it in dialog. But I get one Jquery UI Dialog with message. Problem is that script doesn't pause while dialog is open.
If I write instead of it:
dialogNoteLink.dialog();
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
with alert() - it works fine!
How I can resolve this problem?
That is how JavaScript alert works. If you want to make the calls wait for the dialog to close, then you will have to make the subsequent calls in a callback after the dialog is closed. You should do something like this -
var arrayofNotesAndCountryNames = [{
"dialogNoteLink" : link1,
"visitCountryName" : "country1"
},{
"dialogNoteLink" : link2,
"visitCountryName" : "country2"
},{
"dialogNoteLink" : link3,
"visitCountryName" : "country3"
}];
var currentIndex = 0;
function getLetterOfResponsibilityNote() {
var dialogNoteLink = arrayofNotesAndCountryNames[currentIndex].dialogNoteLink;
var visitCountryName = arrayofNotesAndCountryNames[currentIndex].visitCountryName;
$.ajax({
type: "GET",
url: "/Admin/Applications/GetLetterOfResponsibilityNote/?selectedCountryName=" + visitCountryName,
cache: false,
success: function(data) {
if (data != "") {
dialogNoteLink.dialog({close : function(){
currentIndex++;
if (currentIndex < arrayofNotesAndCountryNames.length){
getLetterOfResponsibilityNote();
}
}
});
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
}
}
});
}
getLetterOfResponsibilityNote();
The dialog should be shown from the callback of the query to the server.
There are no blocking function or dialogs on JQuery.

Categories