Below, am making an AJAX call. First it has to hit the dofirstthing.do. On success of it, it has to make a call with "param1" as the query parameter.
My question - I need to make another call with "param2" as the query parameter after above call. Not sure how to?
$.ajax({
url: "dofirstthing.do",
jsonp: false,
type: "GET",
dataType: "JSON",
statusCode: {
200: function () {
global.location.search = param1;
}
}
});
You can chain the ajax calls like this
$.ajax({..}).then(function(data1){
return $.ajax({..});
}).then(function(data2){
return $.ajax({..});
})
You can execute a function on success or fail as this:
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
reference:
http://api.jquery.com/jquery.ajax/
jQuery offers a $.get() function that returns a promise.
You can chain your requests.
see https://api.jquery.com/deferred.then/ for more info
Try using jQuery deferred.then() , defining an error function
var err = function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
}
$.ajax({
url: "dofirstthing.do",
jsonp: false,
type: "GET",
dataType: "JSON",
statusCode: {
200: function() {
global.location.search = param1;
$.get("/url?" + "param1=" + global.location.search)
.then(function() {
$.get("/url?" + "param2=" + param2).then(null, err)
}, err)
}
}
});
You can do it with a chain of callbacks ---
function sendAjax(target,callback)
{
$.ajax({
url: target,
jsonp: false,
type: "GET",
dataType: "JSON",
statusCode: {
200: callback
}
});
}
Now call Your function as -
sendAjax("dofirstthing.do",function(data){
sendAjax("dofirstthing.do?param1="+data,function(data){
sendAjax("dofirstthing.do?param2="+data,function(data){
return ;
});
});
});
Related
I think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?
You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am new to AJAX and I need to find a way to return an AJAX JSON response back to the calling function. Is there any way to achieve this.
My code snippet:
function requestAjaxWebService(webServiceName, method, jsonData) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
return returnData;
}
jQuery.ajax() performs asynchronous HTTP request. Hence, you can't return its response synchronously (which your code is trying to do).
If the request succeeds, the success(data, textStatus, jqXHR) handler will get called at some point (you don't know when).
Here is one way you could modify your code:
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data, textStatus, jqXHR) {
callback(true, data); // some method that knows what to do with the data
},
error: function(jqXHR, textStatus, errorThrown){
callback(false, errorThrown);
}
});
}
callback should be a reference to a method like:
function onData(isSuccess, dataOrError)
{
if (isSuccess) {
// do something with data
} else {
console.error(dataOrError);
}
}
Update If the settings object is needed in the callback for some reason:
function onData(isSuccess, settings, jqXHR, errorThrown)
{
if (isSuccess) {
// do something with the data:
// jqXHR.responseText or jqXHR.responseXML
} else {
// do something with error data:
// errorThrown, jqXHR.status, jqXHR.statusText, jqXHR.statusCode()
}
}
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
var settings = {
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
};
settings.success = function(data, textStatus, jqXHR){
callback(true, settings, jqXHR);
};
settings.error = function(jqXHR, textStatus, errorThrown){
callback(false, settings, jqXHR, errorThrown);
};
$.ajax(settings);
}
requestAjaxWebService("name", "POST", "json", onData);
You can also use .done() and .fail() callbacks of jqxhr object instead of callbacks in settings object, as obiTheOne's answer suggests. It may look neater, but is not actually important here.
jQuery.ajax is an asynchronous function, so normally it doesn't return anything.
You can anyway return a value to the original function by setting the async option to false, but is not recommended, because a synchronous request will block the rest execution of the rest of your code until a response will be returned.
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
async: false,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
}
take a look at this example: jsbin sync ajax example
You should instead use a callback (the standard way) to handle the response
function onSuccess (data) {
console.log(data);
}
function onFail (error) {
console.log('something went wrong');
}
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: onSuccess,
error: onError
});
}
Or you can return a Promise (a sort of async object) that will change value as soon as the request will be fullfilled
function requestPromise (webServiceName, method) {
return $.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
});
}
requestPromise('...', 'GET').done(function (data) {
console.log(data);
});
refs:
jquery.ajax params
I'm trying to make global ajax handler. so first let me show you the function
var data = {
test : 1
}
$.when( $.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
})
).then(function( data, textStatus, jqXHR ) {
console.log('then me')
});
this way it works.
and outputs
first me
then me
But I want this ajax to be a function
So this is how I'm trying to make it.
var data = {
test : 1
}
$.when(globalAjax(data)).then(function( data, textStatus, jqXHR ) {
console.log('then me')
});
function globalAjax(data) {
$.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
})
}
this way console outputs then me and then first me.
How to ask to wait ajax inside a function?
You need to return a promise in globalAjax:
function globalAjax(data) {
return $.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
});
}
And you don't need to use the $.when function:
globalAjax(data).then(function(data, ...) { ... });
$.when is, mainly, to wait for the completion of two or more deferreds or promises.
function globalAjax(data) {
return $.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
});
}
you need to return a promise from your function.
$.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
}).then(function( data, textStatus, jqXHR ) {
console.log('then me')
});
You dont need when $.ajax already returns a promise.
You need to return the ajax promise from globalAjax so that it can be passed to $.when
function globalAjax(data) {
return $.ajax({
type: 'POST',
url: ajaxurl,
data: data,
dataType: "json",
success: function (data) {
console.log('first me')
}
})
}
Demo: Problem, Solution
$.when()
If a single argument is passed to jQuery.when and it is not a Deferred
or a Promise, it will be treated as a resolved Deferred and any
doneCallbacks attached will be executed immediately.
In your case since there is no return from the method, it will pass undefined to $.when which is causing the behavior
since a promise is returned there is no need to use $.when()
globalAjax(data).then(function (data, textStatus, jqXHR) {
console.log('then me')
});
Demo: Fiddle
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
function Run(someJsonObject) {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
}
var result = Run({dummy:'dummy'});
If I'm not mistaken, the above function will not return true or false, but rather it will be undefined. I want to return the result of the AJAX call, I'd prefer to make it synchronous (I realize I'm using AJAX). How would I accomplish this?
You are backwards, let your ajax run first.
$(function () {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
DoStuffWithResult(data.d);
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
});
function DoStuffWithResult(result){
//time to rock, i have my result
}
If you add the async option to your jquery call, it stops being asynchronous.
That being said, this is usually a bad idea and can probably be handled a better way. Usually, this is done by doing your ajax call first and working with your data in your success function.
If you are really adamant about doing it this way, though, this is what you want:
function Run(someJsonObject) {
var result;
$.ajax({
async: false,
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
result = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
result = false;
}
});
return result;
}
var result = Run({dummy:'dummy'});
If you want to make an ajax request in jquery synchronous and have it be the return value of Run:
function Run(someJsonObject) {
var returnValue;
$.ajax({
type: "post",
async: false,
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
returnValue = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
returnValue = false;
}
});
return returnValue;
}
I added async: false to the ajax options and used a local variable (accessible to the success and error handlers) as the return value.
You can't just return $.ajax(/* snip */) because that returns a promise object.
You can simplify
$.post('/MyWebService', JSON.stringify(someJsonObject), function(r) {
if(r.success) {
// do something (1)
} else {
// do else something (2)
}
},'json').error(function() {
alert('comunication error');
});
If you get any response like this
{ "success": true, data: "my_data" }
execute something (1)
else (2)
If not a valid json or timeout trigger .error()
I'm currently getting a json response which is:
[{"id":1,"title":"Test 1 "},{"id":2,"title":"Test 2"}]
and I want to convert it to a javascript array called 'events' like below so I can return it: e.g:
return {
events : [
{
"id":1,
"title":"Test 1"
},
{
"id":2,
"title":"Test 2"
}
]
};
I'm getting the response from a jquery ajax call:
jQuery.ajax({
type: "POST",
url: "calendar.aspx/get_all_events",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
document.write(msg.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error getting events from database.');
}
});
Anyone know how I can convert the msg or msg.d into what is needed?
Thanks,
You can use:
return {events: JSON.parse(msg.d)};
or, for better compatibility:
eval("var result = "+msg.d);
return {events: result};
or jQuery solution
return {events: $.parseJSON(msg.d)};
if msd.d is
[{"id":1,"title":"Test 1 "},{"id":2,"title":"Test 2"}]
then you could return it like this:
return {
events : msg.d
};
But you would have to do a callback in order to return it. Because ajax is asynchronous. I added the return because that is what you wanted. The alternative would be to make the ajax call synchronous.
I think you just need this:
success: function (msg) {
// The event object is what you require
var eventObj = {events:msg.d};
document.write(eventObj);
},
function doXHR( callback ) {
jQuery.ajax( {
type: "POST",
url: "calendar.aspx/get_all_events",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function ( event ) {
callback && callback( event );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error getting events from database.');
}
});
}
doXHR( function( event ) {
var data = { events: event.d };
// Do other stuff with data here (processing, displaying, etc.).
// You can call other functions here and feed them with data.
} );
Note that XHR requests are asynchronous. You cannot simply return XHR request data. You have to put all your further code into callback function so it can process your array when it's available.