I'm using ajax successives requests and I need do a callback when all the successives requests are done
function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
},
error:function (xhr, status, error) {
//Do something
}
});
},
error:function (xhr, status, error) {
//Do something
}
});
}
$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2){
//Need do something when both second ajax requests (example2.php) are finished
}
With this code, the done function is call before my calls to "exemple2.php" are succeeded.
How can I wait for that?
Thanks for answering!
function doAjaxRequest(data, id) {
// Get payment Token
return new Promise(function(resolve,reject){
$.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
resolve();
},
error:function (xhr, status, error) {
//Do something
reject();
}
});
},
error:function (xhr, status, error) {
//Do something
reject();
}
});
});
}
Promise.all([
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")])
.then(function(values){
//Need do something when both second ajax requests (example2.php) are finished
}
Your sub ajax request is independant of the first ajax result, then the call to example2 is completely separated from the $.when() promise.abort
Just try to use the fact that jquery $.ajax return promise like object
Here my code from plnkr
// Code goes here
function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "GET",
url: 'example1.json',
data: data
}).then(function(msg, status, jqXhr) {
return $.ajax({
type: "GET",
url: 'example2.json',
data: msg
});
}).done(function(msgr) {
console.log(msgr);
return msgr;
});
}
var data = {foo:'bar'};
var otherData = {foo2:'bar2'};
$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2) {
console.log(a1, a2);
//Need do something when both second ajax requests (example2.php) are finished
});
Attention, I replace POST by GET and use exampleX.json files for my tests on plnkr
You can test it here : https://plnkr.co/edit/5TcPMUhWJqFkxbZNCboz
Return a custom deferred object, e.g:
function doAjaxRequest(data, id) {
var d = new $.Deferred();
// Get payment Token
$.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
d.resolveWith(null, [msgr]); // or maybe d.resolveWith(null, [msg]);
},
error:function (xhr, status, error) {
//Do something
d.reject();
}
});
},
error:function (xhr, status, error) {
//Do something
d.reject();
}
});
return d;
}
Now, i'm not sure what is your expected datas passed to $.when().done() callback.
Related
I made ajax call with jquery to get some information from database with php,but the problem is that when i am using $.ajax it is not working,it doesn't show any errors,it doesn't console.log('success') and i can't figure out why,while when i do the same thing with $.post it works.Any idea what is happening here?
function get_all_chats()
{
$.ajax({
url: "get_previous_chats.php",
type: "POST",
succes: function(data){
console.log(data);
console.log("succes");
},
error: function(xhr, status, error) {
console.log(error);
}
})
$.post("get_previous_chats.php", {}, function(data){
console.log(data);
})
}
You are using ajax properly but there are properties that needs to be checked and apply. First is your 'success' where yours is 'succes' with a single S in the end. Next is you must throw request using 'data' property. So this is how it looks.
function get_all_chats()
{
$.ajax({
url: "get_previous_chats.php",
type: "POST",
data: { data: YOUR_DATA },
success: function(data){
console.log(data);
console.log("succes");
},
error: function(xhr, status, error) {
console.log(error);
}
})
}
I'm trying to get my server-side code to play nicely with some page templates we got from a design agency. All is good except that I'm struggling to implement the correct behaviour with the results of the form submission.
What should happen is, if the form submits successfully, some JQuery is triggered to animate into a success message. If not, the user should be redirected to an error page.
Here's the form submit script:
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});
And here's the controller action that it posts to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(User userObject)
{
bool userExists;
try
{
if (ModelState.IsValid)
{
userExists = InsertUser(userObject); //calls a sproc
}
else
{
return CollectValidationErrors(); // collects all validation errors into a string
}
}
catch(Exception ex)
{
ViewBag.ErrorMessage = "Sorry! There has been an error " + ex.Message;
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}
if(userExists)
{
ViewBag.ErrorMessage = "This user already exists";
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
What happens is that the form submission is received and the code inside executed successfully. But if an error state is returned, there's no redirect.
What am I doing wrong?
Try to use error property of ajax call:
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
//Do Something
},
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});
You do not send an error.
You can throw an Exception (forces HTTP Status 500 Internal Server Error) in the Controller Action. It will result that the success is not invoked, but the error function of ajax.
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
},
error: function(function (xhr, status, errorThrown)){
// Do Redirect
}
});
I have a Post call. After the result I want to do another get CALL to check the status. But only if the status is FINISHED.
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
.. now I want to do the polling on the status
jQuery.ajax({
type: "GET",
dataType: "json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
// to continue only if status if Finished
},
error: function() {
}
});
}
});
$.ajax returns a deferred object.
You can do something like below. More info here
var doSomething = $.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
function doneCallback(){
// Handle exit condition here.
doSomething();
}
function failCallback(){
// Handle failure scenario here.
}
doSomething.then(doneCallback, failCallback)
Just set your code in a function:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
doPoll();
}
});
var doPoll = function() {
jQuery.ajax({
type: "GET",
contentType: "application/json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
//do stuff
doPoll();
},
error: function() {
//handle error
}
});
}
You can try to export the ajax call to a function and use recursion to pool.
Note: You should have a max counter so that you do not flood server with infinite calls.
var max_count = 20;
var counter = 0;
function getStatus() {
jQuery.ajax({
type: "GET ",
contentType: "application / json ",
url: " / getStatusUrl,
success: function(data, textStatus, response) {
// to continue only if status if Finished
if (textStatus != "status" && ++counter < max_count) {
getStatus();
}
},
error: function() {}
});
}
I have one html element (elem1) and 2 JS functions (func1, func2) that hides and shows elem1 respectively. These JS functions make individual ajax calls and func2 is calling func1 internally.
Problem: I need to call func2, which internally calls func1. Calling func1 hides elem1. After calling func1, I want to show elem1. But this show is not working.
JSFiddle: https://jsfiddle.net/46o93od2/21/
HTML:
<div id="elem">
Save ME
</div>
<br/>
<button onclick="func1()" id="func1">Try Func1</button>
<button onclick="func2()" id="func2">Try Func2</button>
JS:
function func1() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
$('#elem').hide();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
func1();
$('#elem').show();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
Make func1 take a callback function that tells it what to do after it gets the response. func2 can pass a function that shows the element.
function func1(callback) {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
if (callback) {
callback();
} else {
$('#elem').hide();
}
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
func1(function() {
$('#elem').show();
});
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
DEMO
I can't return the value of an ajax request in Jquery. Here's my code:
function ajaxUniversal(datos, url) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
return data; //This does not returns the data
},
error: function (errorThrown) {
return false;
}
});
}
And if I add the return statement to the final:
function ajaxUniversal(datos, url) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
return data;
},
error: function (errorThrown) {
return false;
}
});
return data;//This is the statement but not works
}
And I get this error:
Uncaught ReferenceError: data is not defined
How can I return the data? Thank you. And sorry for my bad english but I speak spanish.
Ajax calls are asynchronous so you can not return value immediately from them. Instead they return a promise to return a value so what you can do is:
function ajaxUniversal(datos, url, callback) {
return $.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html"
});
}
And call it like this:
ajaxUniversal( datos, url, callback ).then( function(data){
//manipulate data here
});
Ajax calls are asynchronous, therefore you cannot return data with them. If you want to use that data, you need to use a callback function instead.
function ajaxUniversal(datos, url, callback) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
callback(data);
},
error: function (errorThrown) {
callback(errorThrown);
}
});
}
Elsewhere...
ajaxUniversal(someData, someUrl, function(data){
// Do work with data here
console.log(data);
});
As the others have said, this is failing due to the request being asynchronous. You could either fix your code as they suggest, by handling it asynchronously, OR you can set your request to be synchronous using async: false.
function ajaxUniversal(datos, url) {
var data;
$.ajax({
url: url,
async: false, // <---- this will cause the function to wait for a response
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
data = data;
}
});
return data;
}
You can't return the item cause it no longer exists. try to define it first, like this:
function ajaxUniversal(datos, url) {
var returlVal;
$.ajax({
url: url,
async: false,
data: {valores: datos},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
returlVal = data;
},
error: function (errorThrown) {
returlVal = false;
}
});
return returlVal;
}