JQuery mutiple post in the same time - javascript

I have three functions ,and every function post to special php page to get data..
and every function need some time because every php script need some time ..
function nb1() {
$.post("p1.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
function nb2() {
$.post("n2.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
function nb3() {
$.post("c3.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
$(window).load(function() {
nb1();
nb2();
nb3();
});
how can i threading all posts to work in the same time ?

You can use the jQuery when function (https://api.jquery.com/jquery.when/) to wait for all three promises to resolve.
You only need to make sure you also return the promise in your nb1, nb2, nb3 functions.
function nb1() {
return $.post("p1.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
function nb2() {
return $.post("n2.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
function nb3() {
return $.post("c3.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
$(window).load(function() {
$.when(nb1(), nb2(), nb3()).then(function(){
///
});
});
Do you really need to wait for window.load? Otherwise I would use document.ready beacuse it executes sooner.

You can use jQuery.when to call all ajax requests at once. And the success or failure events can be handled collectively.
Eg.
jQuery.when(
jQuery.post("p1.php", {
action: 1
}),
jQuery.post("n2.php", {
action: 1
}),
jQuery.post("c3.php", {
action: 1
})
).done(function(a1, a2, a3){
// handle success
var p1_responseTxt = a1;
var n2_responseTxt = a2;
var c3_responseTxt = a3;
}).fail(function (jqXHR, textStatus, errorThrown) {
// handle error
});
Here, the done function's params a1, a2, a3 correspond to the success data of p1, n2, c3 respectively.

Related

Problem: pass some parameters in ajax call (post)

I have 2 functions: one to add and another to delete. I would like to reuse the same ajax call to send the parameters that are added or deleted. How can I optimize my function?
Here is my code at the moment
jQuery(document).ready(function () {
function ajaxCall(action, callback) {
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
},
success: function (response) {
if (response.error == true) {
alert(response.errors.join('\n'));
}
else if (response.status == "DONE") {
callback(false);
}
},
error: function (xhr) {
console.log("Error: ", JSON.stringify(xhr));
callback(true);
}
});
}
jQuery('#ajax_add').click(function (event) {
event.stopPropagation();
var id = jQuery('#id').val();
var price = jQuery('#price').val();
//I want to send two variables: id, price
ajaxCall("addData", function (error) {
if (error) {
alert("Error!.");
}
else {
alert("It's OK!");
}
});
});
});
The function to delete is similar to "addData" function, it also calls "ajaxCall" and will send parameters to remove.
I'm blocked and I do not know how to solve it, I hope you can give me some help, thanks
You could add a new argument to the ajaxCall function and send the parameters as an object them merge them with the data you've in the function like :
function ajaxCall(action, params, callback) {
Then in the ajax call :
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: $.extend(params, {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
}),
...
The call inside the event will be like :
ajaxCall("addData", {id: id, price: price}, function (error) {

JQuery/Ajax: How to combine several ajaxes into one async ajax with response?

Is it possible to use $.when asynchronously:
init: function() {
console.log('begin');
$.when(
{async: true},
this.ajax1(),
this.ajax2(),
this.ajax3()
).done(function() {
console.log('success');
}, function () {
console.log('error');
});
console.log('end');
}
each ajax1, ajax2 or ajax3 can be either sync or async
For not it's not working then I expect, I want to see the next order in console output:
begin
end
success (or error)
But actual output is always:
begin
success (or error)
end
you should never use synchronous ajax. – adeneo
The problem was that some of my ajaxes were synchronous because their results are depended.
can't you call ajax2 when ajax1 is completed. for e.g. $ajax() {
....., complete: function() { ajax2 call} – user3509208
So I made them asynchronous and made inner ajaxes on completed for those who data are depended:
init: function() {
console.log('begin');
$.when(
{async: true},
this.ajax1(),
this.ajax2()
).done(function() {
console.log('success');
}, function () {
console.log('error');
});
console.log('end');
}
ajax1: function() {
return $.ajax('url', {
async: true,
success: ... ,
error: ...)
);
}
ajax2: function() {
return $.ajax('url', {
async: true,
success: ajax3(),
error: ...)
);
}
ajax3: function() {
return $.ajax('url', {
async: true,
success: ... ,
error: ...)
);
}
And now it's working!

Issue parsing json from jquery

I'm new to jquery I have a php that returns a json, so I can get it from jquery, but there is a problem getting the result.
Here's my code:
calculate: function(me, answer, res_id, soulmates) {
console.log('CALCULATE: ');
var deferred = $.Deferred();
data = {
'me': me,
'answer': answer,
'resid': res_id,
};
$.ajax({
url: appConfig.calculate_url,
type: 'post',
beforeSend: function() {
console.log('BEFORE');
Site.switch_calculation_animations();
console.log('AFTER');
console.log(appConfig.calculate_url);
},
data: JSON.stringify(data),
timeout: 15000
}).done(function(ans) {
console.log(ans);
console.log(ans.ok);
console.log(ans.combi_id);
console.log(ans.slug);
if (ans.ok == 'yes') {
console.log('YES');
deferred.resolve(ans);
}
}).fail(function(jqXHR, textStatus, error) {
console.log('ERROR');
Site.handle_exception('calculate', {
'textStatus': textStatus,
'error': error
});
deferred.reject();
});
console.log('END CALCULATE');
return deferred.promise();
},
The console log I get is:
CALCULATE:
app.js?v=35:242 BEFORE
app.js?v=35:244 AFTER
app.js?v=35:245 /es/test_calculate/4170/waiting/
app.js?v=35:266 END CALCULATE
app.js?v=35:250 {"ok":"yes","combi_id":6059244666,"slug":"true"}
app.js?v=35:251 undefined
app.js?v=35:252 undefined
app.js?v=35:253 undefined
So although the ok value is "yes", do not enter into the if command. Why? What I'm missing?
Thanks
Try this:
}).done(function(ans) {
var data = $.parseJSON(ans)
console.log(data);
console.log(data.ok);
console.log(data.combi_id);
console.log(data.slug);
if (data.ok == 'yes') {
console.log('YES');
deferred.resolve(data);
}

Load data to highchart using ajax

I'm loading a highchart graph using following function.
function reloadSubGraph(data){
$(function () {
$('#SubPatternContainer').highcharts({
plotOptions: {
events: {
update: function (event) {
}
}
},
title: {
text: 'Selected Pattern'
},
series:[{data:[[1,200],[2,200],[3,200]]}]
});
});
}
It works fine, but when using ajax call to load data as follows for same data string [{data:[[1,200],[2,200],[3,200]]}] as follows it doesn't show on graph.
function getSubPatternData(patternId,patternName){
$.ajax({
url: "/arcane/patternData1?patternId="+patternId+"&patternName="+patternName,
type: "get",
cache: false,
success: function(data) {
var tempdata=String(data);
reloadSubGraph(tempdata);
},
error:function(xhr, status, error){
alert(xhr.responseText);
}
});
}
Can anyone point me where i'm doing wrong here. when I see the returned results of ajax using alert(data) it shows the same string that i used in reloadSubGraph() function ([{data:[[1,200],[2,200],[3,200]]}])
when using with ajax i changed reloadSubGraph() funcion as follows.
function reloadSubGraph(data){
alert(data);
$(function () {<!--from w w w .j ava 2 s . c o m-->
$('#SubPatternContainer').highcharts({
plotOptions: {
events: {
update: function (event) {
}
}
},
title: {
text: 'Selected Pattern'
},
series:data
});
});
}

getJSON: how to try to get some url until success in every 0.5 second?

So currently I use simple try once:
$.getJSON("server.json", function(data) {
servicesList.render(data);
});
I wonder how to try until success each 0.5 seconds?
function getFromServer(){
$.getJSON("server.json", function(data) {
// Verify your data, if it's not you want run error function
if(!data){ onerror(); return; }
servicesList.render(data);
}).error(function() { onerror(); });
}
// if error ,run it again.
function onerror(){
setTimeout(function(){getFromServer();},500);
}
you can find the $.getJSON API help with this link:
http://api.jquery.com/jQuery.getJSON/
Try this logic:
function update_it() {
$.ajax({
url: 'server.json',
dataType: 'json',
success: function(data) {
servicesList.render(data);
},
error: function() {
setTimeout('update_it', 500);
}
});
}
If fail, it waits 500 ms then recalls the function.

Categories

Resources