I am trying to make an ajax request to a mysql database and need to loop through the results and either set them as javascript variables or use them in functions within the loop.
mysql query where id is not unique and will return an array of results:
$id =$_REQUEST['id'];
$sth = $conn->prepare("SELECT * FROM quote where id = :id");
$sth->bindParam(':id', $id);
$sth->execute();
$result = $sth->fetchAll();
echo json_encode($result);
Ajax request using post and log results:
$.ajax({
type: "POST",
data: "id="+id,
url: "get-quote-data.php",
cache: false,
success: function (result) {
console.log(result);
}
});
logs 2 objects in an array as there are currently 2 results:
[{"id":"6776t2dhc3aq","0":"6776t2dhc3aq","Wid":"6776t2dhc3aqnew0.5981985541579144","1":"6776t2dhc3aqnew0.5981985541579144","room":"Plot 1 Bedroom","2":"Plot 1 Bedroom","style":"S150","3":"S150","type":"upvc","4":"upvc","colour":"0","5":"0","RAL":"","6":"","cill":"2","7":"2","width":"1023.0000","8":"1023.0000","height":"1585.0000","9":"1585.0000","fitting":"1","10":"1","comments":"","11":"","spacercol":"1","12":"1","glassstyle":"0","13":"0","handles":"0","14":"0","hinges":"0","15":"0","trickle":"0","16":"0","sash":"0","17":"0","fanlight":"0","18":"0","total":"0.0000","19":"0.0000","g1":"6","20":"6","g2":"6","21":"6","g3":"0","22":"0","g4":"0","23":"0","g5":"0","24":"0","g6":"0","25":"0","g7":"0","26":"0","g8":"0","27":"0","m1":"1023.0000","28":"1023.0000","m2":"1023.0000","29":"1023.0000","m3":"0.0000","30":"0.0000","m4":"0.0000","31":"0.0000","m5":"0.0000","32":"0.0000","m6":"0.0000","33":"0.0000","m7":"0.0000","34":"0.0000","m8":"0.0000","35":"0.0000","t1":"777.5000","36":"777.5000","t2":"777.5000","37":"777.5000","t3":"0.0000","38":"0.0000","t4":"0.0000","39":"0.0000","t5":"0.0000","40":"0.0000","t6":"0.0000","41":"0.0000","t7":"0.0000","42":"0.0000","t8":"0.0000","43":"0.0000","ICwinBor":"0","44":"0","LOF":"0","45":"0","LOH":"0","46":"0","intFinish":"0","47":"0","fEx":"0","48":"0","fExt":"0","49":"0","fExl":"0","50":"0","fExr":"0","51":"0","cler":"0","52":"0","fMul":"0","53":"0","commission":"666.999666","54":"666.999666","survey":"666.999666","55":"666.999666","NumItem":"1","56":"1","slideType":"","57":"","horns":"0","58":"0","vsLS":"0","59":"0","vsArched":"0","60":"0","vsFixed":"0","61":"0","vsSecure":"0","62":"0","vsPolished":"0","63":"0","vsJointed":"0","64":"0","vsBay":"0","65":"0","UPVCfStyle":"1","66":"1","UPVCbStyle":"1","67":"1","ALUfStyle":"1","68":"1","ALUbStyle":"1","69":"1","drain":"1","70":"1","ventPos":"1","71":"1","ALUProfile":"Alitherm 600","72":"Alitherm 600"},
{"id":"6776t2dhc3aq","0":"6776t2dhc3aq","Wid":"6776t2dhc3aqnew0.8957906831392683","1":"6776t2dhc3aqnew0.8957906831392683","room":"Plot 2 Bedroom","2":"Plot 2 Bedroom","style":"S150","3":"S150","type":"upvc","4":"upvc","colour":"0","5":"0","RAL":"","6":"","cill":"2","7":"2","width":"1023.0000","8":"1023.0000","height":"1585.0000","9":"1585.0000","fitting":"1","10":"1","comments":"","11":"","spacercol":"1","12":"1","glassstyle":"0","13":"0","handles":"0","14":"0","hinges":"0","15":"0","trickle":"0","16":"0","sash":"0","17":"0","fanlight":"0","18":"0","total":"0.0000","19":"0.0000","g1":"6","20":"6","g2":"6","21":"6","g3":"0","22":"0","g4":"0","23":"0","g5":"0","24":"0","g6":"0","25":"0","g7":"0","26":"0","g8":"0","27":"0","m1":"1023.0000","28":"1023.0000","m2":"1023.0000","29":"1023.0000","m3":"0.0000","30":"0.0000","m4":"0.0000","31":"0.0000","m5":"0.0000","32":"0.0000","m6":"0.0000","33":"0.0000","m7":"0.0000","34":"0.0000","m8":"0.0000","35":"0.0000","t1":"777.5000","36":"777.5000","t2":"777.5000","37":"777.5000","t3":"0.0000","38":"0.0000","t4":"0.0000","39":"0.0000","t5":"0.0000","40":"0.0000","t6":"0.0000","41":"0.0000","t7":"0.0000","42":"0.0000","t8":"0.0000","43":"0.0000","ICwinBor":"0","44":"0","LOF":"0","45":"0","LOH":"0","46":"0","intFinish":"0","47":"0","fEx":"0","48":"0","fExt":"0","49":"0","fExl":"0","50":"0","fExr":"0","51":"0","cler":"0","52":"0","fMul":"0","53":"0","commission":"666.999666","54":"666.999666","survey":"666.999666","55":"666.999666","NumItem":"1","56":"1","slideType":"","57":"","horns":"0","58":"0","vsLS":"0","59":"0","vsArched":"0","60":"0","vsFixed":"0","61":"0","vsSecure":"0","62":"0","vsPolished":"0","63":"0","vsJointed":"0","64":"0","vsBay":"0","65":"0","UPVCfStyle":"1","66":"1","UPVCbStyle":"1","67":"1","ALUfStyle":"1","68":"1","ALUbStyle":"1","69":"1","drain":"1","70":"1","ventPos":"1","71":"1","ALUProfile":"Alitherm 600","72":"Alitherm 600"}]
Within my success function I need to be able to loop through all of the results in each object and use them as I require.
I have tried many of the answers posted on here with no luck, such as:
for (var j = 0; j < result.length; j++){
var windowid = result[j].Wid);
console.log(windowid );
}
logs undefined.
I have also tried many for in and foreach loop examples with no luck.
Thanks in advance for any help.
Parse the result as JSON before the for loop.
Add line result = JSON.parse(result) . As content-type header is not set to application/json your result will be a string which should be parsed as json.
First, you're returning in JSON format, so set that in the ajax request...
$.ajax({
type: "POST",
data: "id="+id,
url: "get-quote-data.php",
dataType: 'json',
cache: false,
success: function (result) {
console.log(result);
}
});
Inside the success function, you can use $.each function to loop through your response...
$.each(result,function(id,value) {
value['id']...
value['Wid']...
etc...
});
So, putting all together...
$.ajax({
type: "POST",
data: "id="+id,
url: "get-quote-data.php",
dataType: 'json',
cache: false,
success: function (result) {
$.each(result,function(id,value) {
var windowid = value['Wid'];
console.log(windowid);
});
}
});
I hope it helps
I am fairly new to JS and AJAX, and for some reason I can not send my dynamically generated and read data via AJAX. How do I properly send an array via AJAX to PHP script?
I have tried following the instructions but I can not get the AJAX to send the data. The first try was a complete bust, the second gets error:
Uncaught TypeError: Illegal invocation
but it seems to originate from the JS-library instead of my code (though the code is most probably the reason for it!) and I do not know what to do with it.
//first thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
console.log(cu[j].value);
i++;
}
var dynamic_account_value = JSON.stringify(cu);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:dynamic_account_value
}
});
//2nd thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
cu2.push(JSON.parse(cu[j].value));
i++;
}
var tilinrot_lisa = JSON.stringify(cu2);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:tilinrot_lisa
}
});
First, give them something that makes selection easier, like a common class. Second, use jquery serialize
$.ajax({
url : "foo",
data : $(".bar").serialize(),
success : function(response) {}
})
Try this code snippet, Try to send just one variable then go for another & use content type.
u can use //console.log(JSON.stringify(cu)); to view what's inside.
jQuery.ajax({
type: 'post',
dataType: 'json',
data: {your_var:JSON.stringify(cu)},
contentType: "application/json"
});
I'm just testing a local application and wanted to make something like this:
Click button, that's easy.
Perform AJAX request and create a database table.
Once the table is created, perform another series of AJAX requests and populate the table according to some parameters gotten from a series of select boxes.
"Animate" the whole thing using a progress bar.
Surprisingly, everything is working fine (apart the last point), but I'm getting some troubles.
The table gets created and populated but, for some reasons, the very last AJAX requests doesn't fire correctly, since it's not passing a parameter correctly.
My ajax requests are ALL asyncronous, if I set them syncronous the whole thing will freeze, but all the requests are executed correctly, even the very last one.
For instance, let's say that I don't want to use asyncronous requests in order to DON'T freeze the page and be able to show a progress bar.
The questions are the following:
Is it possible to call the same script twice?
Is there an efficient way to avoid ajax requests executing before other ajax requests?
After reading a whole bunch of topics here in stackoverflow, I edited my code and tried to:
use jQuery.AJAX prototype instead of jQuery.POST
Set everything asyncronously, in order to don't freeze the page and be able to handle a progress bar
perform the very next AJAX request into the "success" callback of the parent AJAX request.
At this point, I still have another question:
By stacking AJAX requests, is it actually TRUE that everything executed into the "success" callback will be executed AFTER the ajax requests has completed?
This is what I'm performing:
$.ajax({
type: "POST",
url: '../libs/php libraries/agenda.php',
data: {'action':'create>agenda', 'sqlname': createInfo},
processData: true,
dataType: "json",
timeout: 60000,
async: true,
success: function(res) {
$('#popup_content').append(res.log);
var dateList = new Array();
var dateObj = new Date();
var m = dateObj.getMonth();
var Y = dateObj.getFullYear();
for (var i = 1; i <= 31; i++) {
dateList.push(i+"/"+m+"/"+Y);
}
for (var i = 0; i < dateList.length; i++) {
var rs = false;
$.ajax({
type: 'POST',
url: '../libs/php libraries/agenda.php',
data: {'action':'validate>date', 'date': dateList[i]},
processData: true,
timeout: 60000,
async: true,
dataType: "json",
success: function(x) {
$('#popup_content').append(x.log);
if (x.res == 'true') {
rs = dateList[i];
}
if (rs != false) {
$.ajax({
type: 'POST',
url: '../libs/php libraries/agenda.php',
data: {'action':'create>day', 'date': rs, 'sqltable': createInfo},
processData: true,
timeout: 60000,
async: true,
dataType: "json",
success: function(newResult) {
console.log(newResult.res);
$('#popup_content').append(newResult.log);
}
});
}
}
});
}
}
});
the first AJAX request executes correctly, the second one does too, but in the third one (the one with data: {'action':'create>day', 'date': rs, 'sqltable': createInfo}) is getting fired but is missing the parameter rs defined above.
Also, to be clearer, rs is a temporary variable I've defined when I was trying to make the requests outside the "success" callback and when using $.when and $.done, in this case the variable rs is useless, but It won't change anything.
Again, as said above, the whole thing works using a syncronous request, but doesn't by using an asyncronous one.
Moreover, I'm just going to use this script locally, so delays or every problematic related to delays caused by servers and client are not important.
Is there any reason for the last request to don't work with an asyncronous request? if so is there a valuable solution for this case? I've also checked the topics about the queue, but it didn't solve my problem either. For some reasons, asyncronously, the last AJAX requests get just partially fired, since the variable rs is not getting passed correctly.
One solution is to use queue() function. This way you can execute as many functions as you want
var ajaxQueue = $({});
$.ajaxQueue = function(date, ajaxOpts) {
// queue the method. a second call wont execute until this dequeues
ajaxQueue.queue(function(next) {
// for this example I serialize params, but you can save them in several variables
// and concat into ajaxOpts.data
var params = method_that_get_params_and_serialize_them();
ajaxOpts.data = params;
ajaxOpts.complete = function() {
next();
};
$.ajax(ajaxOpts);
});
};
Then your functions have no need of shared vars, with the concurrency conflicts that it causes.
It should be like this:
$.ajax({
type: "POST",
url: '../libs/php libraries/agenda.php',
data: {'action':'create>agenda', 'sqlname': createInfo},
processData: true,
dataType: "json",
timeout: 60000,
async: true,
success: function(res) {
$('#popup_content').append(res.log);
var dateList = new Array();
var dateObj = new Date();
var m = dateObj.getMonth();
var Y = dateObj.getFullYear();
for (var i = 1; i <= 31; i++) {
dateList.push(i+"/"+m+"/"+Y);
}
for (var i = 0; i < dateList.length; i++) {
processDate(dateList[i]);
}
}
});
function processDate(date){
$.ajaxQueue({
type: 'POST',
url: '../libs/php libraries/agenda.php',
data: {'action':'validate>date', 'date': date},
processData: true,
timeout: 60000,
async: true,
dataType: "json",
success: function(x) {
$('#popup_content').append(x.log);
if (x.res == 'true') {
$.ajax({
type: 'POST',
url: '../libs/php libraries/agenda.php',
data: {'action':'create>day', 'date': date, 'sqltable': createInfo},
processData: true,
timeout: 60000,
async: true,
dataType: "json",
success: function(newResult) {
console.log(newResult.res);
$('#popup_content').append(newResult.log);
}
});
}
}
});
};
}
Here is what bothering me. My code is running on document.ready. I need the request to be asynchronous, meaning async: true
for (var i = 0; i < totalGraphs; i++) {
var kpiId = kpiIds[i];
jQuery.ajax({
type: 'POST',
url: graphUrl,
data: "kpiId="+kpiId+"&divId="+(i+1),
async: true, //if false things are working fine
cache:false,
success: function(response){
document.getDocumentById("graph" + (i + 1)).innerHTML("hello");
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
This request does not put hello in my graphX divs, but whenever i put async: false things are working fine. I really need the request to be asynchronous.
Thanks in advance for any help.
Try this...
for (var i = 0; i < totalGraphs; i++){
(function ajaxCall(index) {
var kpiId = kpiIds[index];
jQuery.ajax({
type: "POST",
url: graphUrl,
data: {
kpiId : kpiId,
divId : index + 1
},
async: true, //if false things are working fine
cache: false,
success: function(response) {
document.getDocumentById("graph" + (index + 1)).innerHTML("hello");
},
error: function(XMLHttpRequest,textStatus,errorThrown) {}
});
})(i);
}
I've wrapped the ajax call in an anonymous function so that the value of i will never change, relative to the ajax call.
I'm guessing the i count is getting mixed up in your loop when success is returned. success will return after the loop has run through and thus this will give an unexpected result.
Can you return the i value that went sent in data in your response then use this in your getDocumentById method? I'm guessing this would fix your issue.
New code to try:
for(var i=0;i<totalGraphs;i++){
jQuery.ajax({
type: 'POST',
url: graphUrl,
data: { kpiId: kpiIds[i], divId: (i+1) },
async: true, //if false things are working fine
cache:false,
success: function(response){
document.getDocumentById("graph" + response.count).innerHTML("hello");
},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
}
First of all, you are running an ajax call inside a loop. This will be okay if you've turned off the async. But since you've turned on the async, the loop doesn't wait for the ajax to finish its work.
The best thing to do would be to get the values to a global variable using the inner loop ajax and then use the variable to draw the graph later.