When I have a normal array and multidimensional array in PHP and I return them like this
$data['normalArray'] = $array;
$data['multiArray'] = $multiArray;
echo json_encode($data);
How can I access them in jQuery? I tried using $.each but no results
/edit Some extra info I'm using ajax to get the objects, and the normal one works now but not sure how to do the multidimensional array
success: function (result)
$.each(result.normalArray, function (i, item) {
console.log(item.key);
});
}
You've to parse the JSON String to object using JSON.parse().
$.each() in jQuery is designed to loop through the DOM elements. You can also loop/iterate through Array of elements. But first you need to parse the JSON string returned from PHP using JSON.parse(JSON_STRING)
Try this code
$.getJSON('url',function(r){
for($i=0;$i<=r.length;$i++){
// your code with object r
}
});
Related
I have this PHP array storing code(the data of array is came from database query) then the array will be pass to JQuery. My problem is I'm getting Undefined value when I retrieve the data from php Array. I use $.Each loop in JQuery. My question is, how to iterate loop of php associative array using JQuery?
Here's my code so far:
CONSOLE.LOG/NETWORK IMAGE
PHP Array storing
**** loop here*****
$ListOfWorkOrderDates[$rowInnerJoin['WorkOrder']][$rowInnerJoin['DateField']] =
array('DatePosted' => $rowInnerJoin['DatePosted']);
echo json_encode($ListOfWorkOrderDates);
Jquery Loop
/// Here where I get confuse. How can I retrieve those data from php using jquery loop
$.ajax({
url:'getWorkOrders.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
console.log(output);
$.each(output, function(index, object){
counter++;
ListOfPercentage.push(object.DateField);
ListOfDates.push(object.DatePosted);
});
}
});
$ListOfWorkOrderDates[$rowInnerJoin['WorkOrder']][$rowInnerJoin['DateField']] =
array('DatePosted' => $rowInnerJoin['DatePosted']);
Did you check your exact json response using firebug or chrome dev tools.
I believe object.WorkOrder might return undefined, because your json does'nt seem to have a WorkOrder key?
for the js to work, your json response should be something like
[
{
"WorkOrder": "w1",
"DateField": "D1",
"DatePosted": "DP1"
},
{
"WorkOrder": "w2",
"DateField": "D3",
"DatePosted": "DP2"
}
]
a quick code i used to generate the above response
$response=array();
$response[0]=array("WorkOrder"=>"w1","DateField"=>"D1","DatePosted"=>"DP1");
echo json_encode($response);
I have a JSON encoded array, to which i am returning to an AJAX request.
I need to place the JSON array into a JS Array so i can cycle through each array of data to perform an action.
Q. How do i place the JSON array contents into a JS array efficiently?
The PHP/JSON Returned to the AJAX
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
header("Content-type: application/json");
echo json_encode($array);
You can use JSON.parse function to do so:
var myObject = JSON.parse(response_from_php);
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
console.log(myObject[i]);
}
}
You can also use jQuery.parseJSON() if you are using jQuery, however jQuery also uses same function under the hood as priority if available.
Adding to Safraz answer:
If you're using jQuery, there's another way to do that. Simply add json as last parameter to your ajax calls. It tells jQuery that some json content will be returned, so success function get already parsed json.
Below example shows you simple way to achieve this. There's simple json property accessing (result.message), as well as each loop that iterates through whole array/object. If you will return more structurized json, containing list of object, you can access it inside each loop calling value.objectfield.
Example:
//Assuming, that your `json` looks like this:
{
message: 'Hello!',
result: 1
}
$.post(
'example.com',
{data1: 1, data2: 2},
function(response){
console.log(response.message) //prints 'hello'
console.log(response.result) //prints '1'
//iterate throught every field in json:
$(response).each(function(index, value){
console.log("key: " + index + " value: " + value);
});
},
'json'
)
Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);
I'm trying to pass an array in an ajax request, but apparently it doesn't work...
$.post("process.php", array,
function(data) {
document.getElementById("output").innerHTML = JSON.parse(data);
});
My question is, how to use the data sent in the process file?
The array is built like that: [key (0/1/2...)] => ["prod_id"]. The id varies.
I read somewhere using $_POST["key"]; would work, but it doesn't.
It'd be even better if I could just get the array as is in the process file.
process.php (really basic - just to check wether it's working or not.):
<?php
print($_POST["test"]);
?>
Try to pass {data: array} instead of array. The AJAX call expects an object.
You need to build an Object of array elements. for example:
You can also try like:
{ 'key[]': [1, 2, 3] }
OR
{ key: [1,2,3] }
Read more about $.post()
In order to receive data in php you need to send key/value pairs, however you are only sending a value.
You receive in php with $_POST[key] which will return the value for that key.
JS:
$.post("process.php", {myAray: array}, function(data) {
$("#output").html(data);
});
php
$array= $_POST['myArray'];
To return this array from php as text just to test your ajax can use var_dump( $_POST) or var_dump($array);
If you intend to receive JSON in response from server, you do not need to use JSON.parse , jQuery will parse json internally. However you would need to add "json" as dataType argument to $.post
$.post("process.php", {myAray: array}, function(data) {
/* loop over json here*/
},'json');
if you want to pass an array, you have to "prepare" the key as following:
{'key[]' : ['value1', 'value2', 'value3']}
the same way you'd do it, when you want to pass an array in a form and set the name-attribute to "key[]".
Here is my PHP code, it's getting a listing of collections from mongodb
$list = $db->dbname->listCollections();
$result = array();
$i=0;
foreach ($list as $thiscollection) {
$result[$i++] = $thiscollection->getName();
}
echo json_encode( $result );
I do console.log in the callback and this is what I see.
["fruits", "dogs", "cars", "countries"]
The problem is that this is a string, not an array. I need to iterate through these values. How an I make this into a real object or get php to give me json rather than php array so I can use parseJSON on it.
Thanks.
js:
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
});
I see you are using jquery, if you want data to come back to you as a json object you need to do 1 of 2 things.
add header("Content-Type: application/json") to your php file, this will tell jquery to convert it to a json object instead of as text
Add a forth parameter to your $.post,
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
}, "json");
that will tell jquery to call your error handler if its NOT json, like if your php code fails and outputs html instead. You really should use $.ajax, i have no idea why anyone uses $.post, you can't do ANY meaningful error handling.
JSON is strings. If you want to be able to iterate over it then you need to decode it.