Set javascript variables from ajax request to mysql database - javascript

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

Related

Push/Add multiple JSON objects one by one to the API using ajax and for loop

I'm working on a code where I can push a JSON objects one by one inside an array going to the API using AJAX and for loop. The code here is just a rough sample of what I have been working on. I can't seem to make it work on in pushing the objects to the API JSON array
var lms_json = <?php echo json_encode($json_data); ?>;
var jobjects = JSON.parse(lms_json);
var data = jobjects[0];
for ( i = 0; i < jobjects.length; i++ ) {
var data = jobjects[i];
$.ajax({
type : 'POST',
url : url,
data : data,
dataType : 'json',
success : function() {
console.log(success);
},
error : function(error) {
console.log('Error')
}
})
}
You need to use JSON.stringify to serialize your JSON object. Also, specify the content-type to make the server expect JSON data. This might work:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
I think that your problem is that AJAX is asynchronous process so you can do the following to do it correctly:
var lms_json = <?php echo json_encode($json_data); ?>;
var jobjects = JSON.parse(lms_json);
var i=0;
function makeAjax(url, objs){
var data = objs[i];
i++;
$.ajax({
type : 'POST',
url : url,
data : data,
dataType : 'json',
success : function() {
console.log(success);
makeAjax();
},
error : function(error) {
console.log('Error')
}
})
}
makeAjax(url,jobjects);
So After every success callback run it will run the next. so it will be synchronous process.
I hope it helps.

Send php array to jquery ajax and make a each loop from that array

hi actually i read many topic about array and jquery and they all show example using jquery inside the hmtl script tag but what i try to learn is how to read an array sent by php throught ajax inside a js file
here is my php example
$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);
then here is my ajax
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
// here i want to read the array and make a loop for each element
},
});
thanks if you can help me
try basic for loop with count using length This .. this should help surely.
function ajax_test()
{
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i]);
}
}
});
}
Try a for loop to loop the records
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
var record;
for(record in response)
{
console.log(response[record]);
});
},
});
Please use below code :
$(response).each(function(key,value){
console.log(value);
});
Here each loop of response array and value get ('jazz',rock,...etc).
try see this, clear solution for your question
https://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery
$.each : A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. Reference documentation
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
//Check if the response is in expected JSON format.
var flag = isJSON(response);
if(flag === true)
{ response = JSON.parse(response); }
//Iterate the Array using for each loop of jquery
$.each(response, function( index, value ) {
console.log( "Index : " + index + "Value : " + value );
});
} // End of success function
}); //End of Ajax
//JSON format check
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
You can get array indexes and values by using .each in jQuery as:
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
$.each(response, function(index,value)
{
console.log(index); // print all indexes
console.log(value); // print all values
});
},
});
<div id="dat" name="dat"></div>
<script type="text/javascript">
$.ajax({ url: "music_list.php",
dataType: 'json',
cache: false,
success:function(response) {
for( res in response) {
document.getElementById('dat').innerHTML+=response[res]+"<br/>";
}
}
});
</script>

jQuery .ajax Call Returns JSON ParseError Even Thought JSON Appears to be Correct?

I'm getting a ParseError even though my JSON validates on jsonlint.com.
Here is the jQuery code:
$.ajax({
url: path,
type: 'GET',
data: {},
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var a = 'breakpoint here doesn't activate';
},
error: function (x, y, z) {
var b = 'code execution stops at a breakpoint here.';
}
});
Here is the PHP code that is being called:
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
$encodedData = json_encode($testData);
echo $encodedData;
return;
}
This comes back to a breakpoint set in the error: function of my .ajax call. Parameter Y is set to "parseerror", and x.responseText =
["testing123"]
I've been looking into this for hours so far. I've looked at many relevant StackOverflow posts, but none have solutions that work in this case.
How can I get a success response from this .ajax call?
Thanks very much in advance to all for any info.
There's nothing visibly wrong with your code, and it works fine when I try it on my local machine. However, your comment above is a big clue:
I just looked at the z param in the Safari console, and found this:"undefined is not a function (evaluating 'JSON.parse(a+"")')" How could that be happening?
It could happen if some code somewhere uses "JSON" as a global variable name, hiding the built-in window.JSON object.
Check for Notice or Warning in your php code, if their is any then remove that and then try. Hop this will help you.
JavaScript allows either single or double quotes for strings, but JSON only allows double quotes. See http://www.json.org/
See also jQuery.parseJSON single quote vs double quote
Just Use
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
echo json_encode($testData);
}
Then in your AJAX you can do
$.ajax({
url: path,
type: 'GET',
dataType: 'json'
success: function(data){
for (var i = 0; i < data.length; i++) {
//DO YOUR STUFF
}
}
});
Please use
$.ajax({
url: path,
type: 'GET',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var a = 'breakpoint here doesn\'t activate';
},
error: function (x, y, z) {
var b = 'code execution stops at a breakpoint here.';
}
});
and in your PHP CODE Paste this code.
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
$encodedData = $testData;
echo json_encode($encodedData);
exit;
}
May be after digging more in your code I assume that in your PHP code you were not passing data properly. Please use exit or die method to pass data back to ajax. Please check.
Try with the below code,
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
echo json_encode($testData);
die();
}
$.ajax({
url: path,
type: 'GET',
dataType: 'json'
success: function(data){
console.log(data);
var result = JSON.parse(data);
console.log(result);
}
});

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.

error looping through Ajax (JSON) response

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;

Categories