error looping through Ajax (JSON) response - javascript

I'm trying to loop through an array that gets returned from a php file.
If I run this:
$.ajax({
type: "POST",
url: "lib/search/search.standards_one.php",
async: "false",
dataType: "json",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
$.each(response[0], function(){
console.log(this['code'], this['standard_id']);
});
}
});
everything works perfectly.
but, I need to loop through this response using an array (grades) as parameters.
like this:
$.ajax({
type: "POST",
url: "lib/search/search.standards_one.php",
async: "false",
dataType: "json",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
var len = grades.length;
var param = "";
for(var x=0; x < len; x++){
param = grades[x];
$.each(response[param], function(){
console.log(this['code'], this['standard_id']);
});
}
}
});
however, when I run this I get the "Cannot read property 'length' of undefined" error.
I've tried a number of different solutions, but I still arrive at this result.
////
this is where the JSON object gets created:
private function retrieve_standards_one(){
$dbh = $this->connect();
$stmt = $dbh->prepare("SELECT code, standard_one_id
FROM standard_one
WHERE grade_id = :grade_id
ORDER BY standard_one_id");
$stnd = array();
for($x = 0; $x < (count($this->grades)); $x++){
$stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
$stmt->execute();
$stnd[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$json = json_encode($stnd);
return $json;
}

grades is out of scope of your success function, that is why it is undefined. The ajax is asynchronous, so the call is fired off, and your success function is only executed when the response is received (and it was successful).
A quick fix would be to put the vars you need in the global scope, or get them from response if they are in there.
var len = response.length;

Related

Update front after ajax request in for function

I have a project where I sent an array to a foreach in PHP and it worked, the question is that it took a long time and it showed timeout, I try to do that for from js and ajax so that it sends the request to PHP and returns, update the value of the registry and return to PHP, this to avoid this timeout error, but when doing the synchronous for, the PHP function works ok and return data, but does not update the front with the information.
I have tried with success and with .done and it doesn't work as I want.
for(var i = 0 ;i < ids.length; i++){
console.log(i+' '+ids[i]);
var parametros = {'val1' : ids[i]}
$.ajax({
data: parametros,
url: "{{path('enviar_fac')}}",
type: 'post',
async: false,
success: function(data){
alert("success: "+i);
document.getElementById("loading").style.display = "block";
document.getElementById("resultados").innerHTML = "id: "+i+" data: "+data;
}
});
}
thanks

Passing an array of strings from JS to PHP

I have an array of strings in JS, and I want to send it to php (to be able to add it to db). This is my current code -> showing success message, but not showing the $_POST['array'] variable.
Keep in mind that that array I want to send has string values only and is called times
JS
function fetchDates(){
times = [];
var table = document.getElementById("timeScheduleBody");
var tableRows = table.getElementsByTagName("tr");
for(var j=0;j<tableRows.length;j++){
var tableCells = tableRows[j].getElementsByTagName("td");
for(var i = 0;i<tableCells.length;i++){
if(tableCells[i].getAttribute('class').includes("success")){
var arr = tableCells[i].getAttribute('value').split("-");
var date, hour, mins;
date = arr[0];
hour = arr[1];
mins = arr[2];
times.push(date);
times.push(hour);
times.push(mins);
}
}
}
window.alert(times);
//send array to PHP from jQuery
jQuery.ajax({
type: "post",
url: window.location.href,
data: {array:times},
success: function(){
alert("done");
}
});
}
PHP
<?php
if(isset($_POST['array'])){
$array = $_POST['array'];
echo $array[0];//just testing -> output: nothing
foreach($array as $d){
print '<script>window.alert($d);</script>';//also just to test -> output: nothing
}
}
?>
But you're not getting and showing the response of the ajax call, to see the response you have to get the response in the success function...
PHP (test.php - Create this file and put it in the same directory):
<?php
if(isset($_POST['array']))
print_r($_POST['array']);
?>
JQUERY:
$.ajax({
type: 'POST',
url: 'test.php',
data: { array: times },
success: function(response) {
alert(response);
}
});
You'll see the array content. You're sending the javascript array correctly, but if you want to see the response of the ajax call you have to get it in the success function and do something with it (alert it, add it to the DOM, etc.)

Set javascript variables from ajax request to mysql database

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

Best practice when changing PHP Data to JS Data via AJAX (especially arrays)

(Secondary title): ajax array recieved as json encoded PHP array not behaving as javascript array
For some reason, my PHP array gets sent over to JavaScript just fine, but when I try to access an individual key of the array, it doesn't return anything, or it returns some other value which doesn't correspond. I am of course using json_encode() in the corresponding PHP file (echoClientData.php):
$id = $_GET['selected_id'];
$id = str_replace("clientSel","",$id);
$getclientinfo = "SELECT * FROM `clients` WHERE `ClientID` = $id";
if ($result = $Database->query($getclientinfo))
{
$row = $result->fetch_row();
$output = $row;
}
echo json_encode($output);
This code works fine:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data;
$('#client-detail-box').html(test);
}
});
And returns an array into the #client-detail-box div, e.g.
["1566","","Adrian","Tiggert","","","","","","","","","","","","0000-00-00","0000-00-00","0.00","","0","","","102","Dimitri Papazov","2006-02-24","102","Dimitri Papazov","2006-02-24","1","0","0"]
However, when I do
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
}
It returns
5
You may need to do one of two things when returning JSON from PHP.
Either set your content type in PHP before echoing your output so that jQuery automatically parses it to a javascript object or array:
header('Content-type: application/json');
or specify that jQuery should treat the returned data as json:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
dataType: 'json',
success: function(data)
{
var test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
Be aware, that in your current PHP script, in the event that your query fails, you will be json_encodeing an undefined variable.
Also, your PHP code is entirely open to SQL injection. Make sure you sanitize your $id, either by casting it to (int) or by escaping it before sending it through in your query.
Have you tried using JSON.parse on the value you are getting back from PHP?
e.g.
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = JSON.parse(data); // should be "Tiggert"
$('#client-detail-box').html(test[3]);
}
});
That seems like it would be a fix.

JavaScript(jquery) function does not finish its excution

I have a php file which returns a large json string (~2000 elements , each have 14 child element).
I use jquery ajax to fetch the json and put them in to id-identified table.
but it stops filling in mid-way(~1100).Here's the code:
var max = <?php echo $max; ?>; //max is the total number of elements in the database called by php.
$.ajax({
url: "all_arr.php",
type: 'POST',
dataType: "json",
success: function(data) {
for (var i = 0; i < max; i++) {
$("#name_" + i).html(data[i].eng);
$("#slot_" + i).html(data[i].slot);
}
}
});
UPDATE:The code works fine in Safari,but not in chrome.
Uncaught TypeError: Cannot read property 'eng' of undefined
How you get count of values in data table?:
var max = <?php echo $max; ?>; //max is the total number of elements in the database called by php.
It is wrong. You pass data parameter in your success function. Loop through it and receive all data this way.
Your final code will be (if data is array):
$.ajax({
url: "all_arr.php",
type: 'POST',
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
$("#name_" + i).html(data[i].eng);
$("#slot_" + i).html(data[i].slot);
}
}
});
Also, you can use this:
$.ajax({
url: "all_arr.php",
type: 'POST',
dataType: "json",
success: function(data) {
var i;
for (i in data) {
$("#name_" + i).html(data[i].eng);
$("#slot_" + i).html(data[i].slot);
}
}
});
Both approaches based on length of received object in success function, but not on length you specified. Possibly, you set wrong length of data array, which you want to receive in this code: var max = <?php echo $max; ?>;.
Tell me about result.
Please post the code for all_arr.php because the problem could be there.
try the error paramenter if there is any errors:
try the max=2200 see if that works. max maybe set to wrong number in php.
.
var max = <?php echo $max; ?>;
$.ajax({
url: "all_arr.php",
type: 'POST',
dataType: "json",
timeout: 10000, //add this if there a timeout
success: function(data) {
for (var i = 0; i < max; i++) {
if(data[i] != undefined){
$("#name_" + i).html(data[i].eng);
$("#slot_" + i).html(data[i].slot);
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
Timeout Error:
Your error event handler takes the three arguments (xmlhttprequest, textstatus, message) when a timeout happens, the status arg will be timeout. Then add:
timeout: 10000, //10seconds
Regarding your error: Uncaught TypeError: Cannot read property 'eng' of undefined
This is cleary an error in the .php file and what it returns.
if(data[i] != undefined){ // if nothing is returned, print nothing.

Categories