javascript callback is not called when using ajax post - javascript

i have ajax call inside my function make it reusable, when my ajax success i want to callback a function,
var ajaxPostCall = function(data , url ,callback){
// Return the $.ajax promise
$.ajax({
data: data,
dataType: 'json',
url: url,
method: 'POST',
beforeSend: function() {
onStartAjaxRequest();
},
success:function(data){
if(typeof callback == "function"){
callback();
}else{
console.log('not callback');
}
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjaxRequest();
}
});
}
var ajaxGetCall = function(data , url ,callback){
// Return the $.ajax promise
$.ajax({
url: url,
dataType: 'json',
method: 'GET',
beforeSend: function() {
onStartAjaxRequest();
},
success:function(data){
//console.log('test');
if(typeof callback == "function"){
callback();
}else{
console.log('not callback');
}
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjaxRequest();
}
});
}
function onStartAjaxRequest(){
$('#spinner').hide();
}
function onEndAjaxRequest(){
$('#spinner').show();
}
$(document).ready(function(){
data = {'name' : 'john'};
function callbackSuccess(){
console.log('success');
}
ajaxPostCall(data , '/proccess.php' , function(){
console.log('success 1');
});
ajaxGetCall(data , '/proccessGet.php?id=12' , function(){
console.log('success 2');
});
})
when i run this code, both of ajax post and get can work.but why only my ajaxget can call the callback 'success2' , the ajaxpost doesnt show 'success1' .. any idea?
image

well, i just find out myself and i know the problem...my proccess.php on ajaxpost is not returning json object properly , meanwhile i put dataType: 'json' in my ajaxpost, thats why my ajaxpost is not going to success callback
but i still wonder on my ajaxget still going to success callback even my /proccessGet.php?id=12 does not return json object , is ajax with GETmethod ignoring datatype:json?

Related

Handing value into Success function from AJAX Call

G'day all,
I'm trying to pass a value through to a Success var from the original AJAX call.
Here's some code :
function isJobComplete(jobGUID) {
var data = { "pJobGUID": jobGUID };
var url = '/DataService.asmx/isJobComplete';
var success = function (response, jobGUID) {
if (response.d) {
//The job is complete. Update to complete
setJobComplete(jobGUID);
}
};
var error = function (response) {
jAlert('isJobComplete failed.\n' + response.d);
};
sendAjax(data, url, success, error);
}
function sendAjax(data, url, success, error) {
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: success,
error: error || function (response) {
jAlert(response.d);
}
});
}
When the isJobComplete function runs, it has the correct value for jobGUID on the first pass through, but on the return to Success after the AJAX call, jobGUID changes to the word "success", with the double quotes.
How can I pass through that jobGUID to the Success function so I can use it to do more work depending on the AJAX response?
Thanks in advance....

jQuery AJAX stop request after another response

i have an issue and i need an idea for solve :)
I have 2 call to $.ajax
First, is asynch, and during a lot of time (1 minutes for example)
Second, is sync (in ajax async: false) and it response fast (5 sec for example)
Second call is in a loop (requests->response->print data, request->response->print data).
I need when first finish (success or error), stop second call.
I attach an example code:
var success = false;
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
},
success: processOK,
error: processError
});
do {
$.ajax({
type: "POST",
url: urlData,
data: {
data: dataSend
},
async: false,
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(data, textStatus, jqXHR){
console.log("Error");
}
});
} while (!success);
I hope it's clear :)
I corrected an issue that would cause some errors, try this out.
let printData = function( input ){
let config = {
urlRest: '',
data: { data: {} },
loop: false,
callback: false
}
$.each(config,function(k,v){ config[k] = input[k] });
config.loop = false;
$.ajax({
type: 'POST',
url: config.urlRest,
data: config.data,
success: function( data ){
// Based on the response if you need to run again change config.loop to true and it will run again
// you can also alter anything your sending through
if( config.loop ) printData( config );
else if( typeof config.callback === 'function' ) callback();
},
error: function(){
// Based on the response if you need to run again change config.loop to true and it will run again
// you can also alter anything your sending through
if( config.loop ) printData( config );
else if( typeof config.callback === 'function' ) callback();
}
});
}
printData({
urlRest: '', // URL Here
data: data, // Data Object
loop: true, // Set this to true if you want it to loop
callback: function(){
console.log( 'Job Complete' );
}
})
You can run async calls in synchronous manner using SynJS:
function ajaxWrapper(ctx, url, data){
var res={done:false};
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){
res.data=result;
},
error: function(){
res.error=true;
},
}).always(function(){
res.done = true;
SynJS.resume(ctx); // <-- tell caller that callback is finished
});
return res; // <-- return object that will hold the results
}
// function that is executed in synchronous manner
function myFunc(modules, urlRest, urlData) {
var success = false;
var res1 = modules.ajaxWrapper(_synjsContext, urlRest, urlData);
SynJS.wait(res1.done); // <-- wait for result from callback
do {
var res2 = modules.ajaxWrapper(_synjsContext, urlRest, urlData);
SynJS.wait(res2.done); // <-- wait for result from 2nd callback
} while (!success);
}
var modules = {ajaxWrapper: ajaxWrapper};
SynJS.run(myFunc,null, modules, "/", {}, function () {
console.log('done');
});
You can change the success value like this
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
}
}).always(function() {success=true;});
Or you can create a self call function (after the second ajax finish, calls it again) but before the call its checks the success variable like #mplungjan did.
It is never a good idea to loop Ajax. You need to allow the call to return.
Here is an example that is NOT using async false
var firstDone = false,tId;
// call long ajax
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
}
}).done(processOK);
}).fail(processError)
}).always(function() {firstDone=true; clearTimeout(tId);}); // stops the other loop
// setup function that can be looped
function callAjax() {
if (firstDone) return;
$.ajax({
type: "POST",
url: urlData,
data: {
data: dataSend
}
}).done(function(data, textStatus, jqXHR) {
console.log(data);
}).fail(function(data, textStatus, jqXHR) {
console.log("Error");
}).always(function() {
tId=setTimeout(callAjax,1000); // give the server time to recover
});
}
callAjax();

Calling PHP functions through AJAX using jQuery callback parameters

I have problems with AJAX results using jQuery.
I have defined these functions:
<script>
function hello(callback, funct, val) {
var ret = 0;
console.log(val);
$.ajax({
type: 'GET',
dataType: 'json',
url: 'SGWEB/header.php',
data: {
'funct': funct,
'val': val
}
}).done(function (data) {
// you may safely use results here
console.log(data);
callback(data);
});
};
function change() {
hello(function (ret) {
console.log(ret);
$("#b1").text(ret);
}, "hello", 1);
};
change();
</script>
SGWEB/header.php:
extract($_GET);
$validFunctions = array("readPin","hello");
if(in_array($funct, $validFunctions)) $funct();
// functions
// ....
function hello($val) {
if ($val == 1) {
echo "1";
} else
echo "2";
}
The problem I have is that the AJAX passes only the first parameter in data {'funct': funct} and it's working, but val is completely ignored (it always echoes "2").
How can I solve this? Thanks
You are forgetting to pass the $val parameter to your function in PHP
Change this:
if (in_array($funct, $validFunctions)) $funct();
to this:
if (in_array($funct, $validFunctions)) $funct($val);
Another problem is that your AJAX is expecting JSON as you are defining it here dataType:'json' but you are not sending that. I would redo your ajax call like this so that you can see other errors as well:
$.ajax({
type: 'GET',
url: 'SGWEB/header.php',
data: {
'funct': funct,
'val': val
},
success: function (result) {
console.log(result);
callback(result);
},
error: function (xhr, textStatus, error) {
console.log(xhr);
console.log(textStatus);
console.log(error);
}
});

Callback Issue in JavaScript

I am trying to execute a WCF service call, from function one(). Only once this is complete I want function two() to be executed. The issue I have is that function two() is invoked before function one() completes execution and the WCF service returns the result. How can I solve this please? I am using callback function, so I can't figure out why, given that the response does not exceed 3 seconds.
<script type="text/javascript">
var jsonGetFileResult = "";
function one(callback) {
setTimeout(function() {
//var jsonGetFileResult = "";
console.log('01: into one');
$.ajax({
type: 'GET',
url: ‘http: //wcf.google.com’, //this is the wcf call
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {},
timeout: 10000,
success: function(data) {
jsonGetFileResult = stringifyNewsletter(data);
console.log('03: ' + jsonGetFileResult);
},
error: function(data) {
alert(error);
}
});
callback();
}, 3000);
}
function stringifyNewsletter(data) {
var removeHeader = JSON.stringify(data);
var file = removeHeader.split('"');
console.log('02: ' + file[3]);
return file[3];
}
function two(linkToNewsletter) {
window.open(linkToNewsletter, '_blank', 'location=yes');
return false;
}
/* now we make use of the callback */
one(function() {
alert(jsonGetFileResult);
// "one" triggers "two" as soon as it is done, note how "two" is a parameter
two(jsonGetFileResult);
});
</script>
You're invoking the callback outside of the ajax "success" function. The $.ajax() call is asynchronous — the call will return to your code essentially immediately, after launching the HTTP request and without waiting for it to finish.
If you move the line
callback();
to inside the "success" handler, then that will run after the HTTP request completes.
You need to put callback inside success function like that:
function one(callback) {
setTimeout(function() {
//var jsonGetFileResult = "";
console.log('01: into one');
$.ajax({
type: 'GET',
url: ‘http: //wcf.google.com’, //this is the wcf call
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {},
timeout: 10000,
success: function(data) {
jsonGetFileResult = stringifyNewsletter(data);
console.log('03: ' + jsonGetFileResult);
callback();
},
error: function(data) {
alert(error);
}
});
}, 3000);
}

Two Ajax onclick events

So I have had to modify some old existing code and add another ajax event to onclick
so that it has onclick="function1(); function2();"
This was working fine on our testing environment as it is a slow VM but on our live environment it causes some issues as function1() has to finished updating some records before function2() gets called.
Is there a good way to solve this without modifying the js for function2() as this the existing code which is called by other events.
Thanks
Call function2 upon returning from function1:
function function1() {
$.ajax({
type: "POST",
url: "urlGoesHere",
data: " ",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//call function2
},
error:
});
}
Or wrap them in a function that calls both 1 and 2.
You need to use always callback of ajax method, check out always callback of $.ajax() method http://api.jquery.com/jquery.ajax/.
The callback given to opiton is executed when the ajax request finishes. Here is a suggestion :
function function1() {
var jqxhr = $.ajax({
type: "POST",
url: "/some/page",
data: " ",
dataType: "dataType",
}).always(function (jqXHR, textStatus) {
if (textStatus == 'success') {
function2();
} else {
errorCallback(jqXHR);
}
});
}
I'm assuming you use Prototype JS and AJAX because of your tags. You should use a callback function:
function function1(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function function2(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function both() {
function1(function() {
function2();
});
}
Then use onclick="both();" on your html element.
Example: http://jsfiddle.net/EzU4p/
Ajax has async property which can be set false. This way, you can wait for that function to complete it's call and set some value. It actually defeats the purpose of AJAX but it may save your day.
I recently had similar issues and somehow calling function2 after completing function1 worked perfectly. My initial efforts to call function2 on function1 success didn't work.
$.ajax({
type: "POST",
url: "default.aspx/function1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // to make function Sync
success: function (msg) {
var $data = msg.d;
if ($data == 1)
{
isSuccess = 'yes'
}
},
error: function () {
alert('Error in function1');
}
});
// END OF AJAX
if (isSuccess == 'yes') {
// Call function 2
}

Categories