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 trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array