I make an Ajax call that needs to return (after success:...) a multidimensional array representing an SQL query :
$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
data: {action: this.title},
type: 'post',
success: function(data) {
//I need to use the data array here.
});
Here is the method that is called :
<?php
$bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');
$req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");
$data = ... //Here I need to transform the previous request into a multidimensional array.
//For exemple data[3][2] will contain the value within the third row of the second column
echo $data; //returning the array
}
Thanks
Problem
You are trying to return am array. But as AJAX calls works on HTTP protocol, you can transfer only text, normally. So your ajaxmethod.php will print the array and the rendered page i.e. the text will be returned as it is displayed, not an array.
Solution
Convert the array into a JSON object using json_encode() (PHP) andreturn that. Then decode it on the page that made the ajax call, using JSON.parse() (JavaScript). This will give an array.
Code
$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
data: {action: this.title},
type: 'post',
success: function(data) {
//I need to use the data array here.
var array = JSON.parse(data); //This is the array you want
});
...
<?php
$bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');
$req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");
$data = ... //Here I need to transform the previous request into a multidimensional array.
//For exemple data[3][2] will contain the value within the third row of the second column
echo json_encode($data) //returning the array
}
You cant just echo an array (you can't, it an array not a simple value).
Luckily, there is a thing called JSON. In PHP you store all the information you want (in this case, your rows from the DB) in a large array and then you do echo json_encode($array);.
At the Javascript side you change the $.ajax to $.getJSON so that jQuery also understands that we're talking about JSON, et voila, you have a nice javascript version of your PHP array.
// I am not familiar with PDO, but something along these lines:
$allData = $req->fetchAll();
echo json_encode($allData); // Now you output a JSON version of the array
And then javascript
$.getJSON(
'http://localhost/Project/ajaxmethod.php',
{action: this.title},
function(response) {
// And in 'response' you now have a ready to use JS object)
console.log(response);
});
*You can also use $.ajax() if you really want to, just add a dataType: 'json
Related
I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.
I have posted a question about How to alert a php array in ajax success function in this post: How to alert a php array in ajax success function
I got the answer to use alert(JSON.stringify(result[0])); but this will give me access to the first row of the array while i need to have access to each element of each row. imagine that my array is like this now
[0]1>>>>2>>>>>3>>>>>5>>>>>6
[1]1>>>>2>>>>>3>>>>>5>>>>>6
[2]1>>>>2>>>>>3>>>>>5>>>>>6
[3]1>>>>2>>>>>3>>>>>5>>>>>6
[4]1>>>>2>>>>>3>>>>>5>>>>>6
[5]1>>>>2>>>>>3>>>>>5>>>>>6
alert(JSON.stringify(result[0])) will give me only [0]1>>>>2>>>>>3>>>>>5>>>>>6 but I want to alert 5 only, I have tried alert(JSON.stringify(result[0][3])) but no luck.
Could you tell me how to have access to 2d array elements using JSON.stringify? Or is there any other way than JSON.stringify(result[0]
Here is the ajax function :
$.ajax({
type: 'POST',
url: "profile/ajax/getorder.php",
data: {id:gotid},
dataType: 'json',
cache: false,
success: function(result) {
alert(JSON.stringify(result[0]))
},
});
here is the php
$ent = $_POST['id'];
$column = array();
$gtord = mysql_query("SELECT * FROM order WHERE oId = '$ent' ");
while($rowmnu2=mysql_fetch_array($gtord))
{
$column[] = $rowmnu2;
}
echo json_encode($column);
Appreciated.
The json.stringify method simply gets the array in a text format that can be sent to alert. If you are only looking at a single value that isn't an array, you don't need it. Just alert(result[0][3]).
After getting more info:
To access a whole row, use JSON.stringify(result[0]), to look at a specific element use result[0]['user_id']. If you want to use numbers to look at the specific elements, use mysql_fetch_row instead of mysql_fetch_assoc. Hope that helps.
So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.
I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.
I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.
jQuery code to call AJAX:
var element= $('select[name=elementName]');
var data = 'inData=' + element.val();
// Call AJAX to get the info we need to fill the drop downs by passing in the new ID
$.ajax(
{
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
success:
function(outData)
{
// WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
},
error:
function()
{
}
});
PHP code:
$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'");
$outData = array();
// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));
// echo the data to return it for use in the jQuery file
echo $outData;
The code posted is working fine - I just don't know how to read 'outData' in jQuery.
Thanks in advance for any help!!
Have you looked at json_encode?
echo json_encode($outData);
This will convert it into a json object that can be read by jQuery.
your looking for json
//php
echo json_encode($outData);
//javascript
$.ajax({
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
dataType: "json",
success: function(outData) {
console.log(outData); //this will be an object just like
//your php associative array
},
error: function() {
}
});
JSON can do the trick, but why not look at it from another angle?
If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.
There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.
jQuery can not read the echo of a PHP array. Use json_encode before you output it:
echo json_encode($outData);
That's a format jQuery actually can parse as the response.
I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.