I have a php array like this one :
Array
(
[0] => banana, peach, cherry
[1] => strawberry, apple, lime
)
I pass it to Jquery using json_encode($myArray)
In Jquery I receive my array like this : ["banana, peach, cherry","strawberry, apple, lime"]
Now I wanna extract each value : "banana, peach, cherry" & "strawberry, apple, lime"
When I try to use this :
$.each(data, function(key, value){
alert(value);
});
it alerts me each chars : [ " b a n a n................ etc instead each value.
Do you know why ?
EDIT :
This is how I receive my data from php :
$.post('ajax/fruits.php', function(data) {
var obj = $.parseJSON(data);
var chunks = obj['chunks'] // gives me : ["banana, peach, cherry","strawberry, apple, lime"]
if (obj['error']==0) {
mix_fruits(chunks); // a function that should extract each value
}
});
You don't show how you are passing and receiving the data, but somewhere in the process you are making a mistake.
It is evident from the description that data is a string, not an array as it should have been based on the PHP variable. And since the string begins with the characters that make up the JSON representation of your data, this means the JSON is being wrapped into a string instead of parsed as a JavaScript literal.
Assuming that passing/receiving is not done through an AJAX request (in which case jQuery would almost certainly parse the data automatically) I 'm guessing that you are doing this:
var data = '<?php echo json_encode($data); ?>';
while you should instead be doing this:
var data = <?php echo json_encode($data); ?>; // no quotes!
You need to parse the JSON object before you can use it,
var jsonObj = jQuery.parseJSON(data);
then to loop through each item use this,
for(var key in jsonObj)
{
curr = jsonObj[key];
}
And if you want to use non-jquery one,
Parse JSON in JavaScript?
Related
I've been experiencing a lot of trouble with my issue all afternoon. Endless searches on Google and SO haven't helped me unfortunately.
The issue
I need to send an array to a PHP script using jQuery AJAX every 30 seconds. After constructing the array and sending it to the PHP file I seemingly get stuck. I can't seem to properly decode the array, it gives me null when I look at my console.
The scripts
This is what I have so far. I am running jQuery 1.11.1 and PHP version 5.3.28 by the way.
The jQuery/Ajax part
$(document).ready(function(){
$.ajaxSetup({cache: false});
var interval = 30000;
// var ids = ['1','2','3'];
var ids = []; // This creates an array like this: ['1','2','3']
$(".player").each(function() {
ids.push(this.id);
});
setInterval(function() {
$.ajax({
type: "POST",
url: "includes/fetchstatus.php",
data: {"players" : ids},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}, interval);
});
The PHP part (fetchstatus.php)
if (isset($_POST["players"])) {
$data = json_decode($_POST["players"], true);
header('Content-Type: application/json');
echo json_encode($data);
}
What I'd like
After decoding the JSON array I'd like to foreach loop it in order to get specific information from the rows in the database belonging to a certain id. In my case the rows 1, 2 and 3.
But I don't know if the decoded array is actually ready for looping. My experience with the console is minimal and I have no idea how to check if it's okay.
All the information belonging to the rows with those id's are then bundled into a new array, json encoded and then sent back in a success callback. Elements in the DOM are then altered using the information sent in this array.
Could someone tell me what exactly I am doing wrong/missing?
Perhaps the answer is easier than I think but I can't seem to find out myself.
Best regards,
Peter
The jQuery.ajax option dataType is just for the servers answer. What type of anser are you expexting from 'fetchstatus.php'. And it's right, it's json. But what you send to this file via post method is not json.
You don't have to json_decode the $_POST data. Try outputting the POST data with var_dump($_POST).
And what happens if 'players' is not given as parameter? Then no JSON is returning. Change your 'fetchstatus.php' like this:
$returningData = array(); // or 'false'
$data = #$_POST['players']; // # supresses PHP notices if key 'players' is not defined
if (!empty($data) && is_array($data))
{
var_dump($data); // dump the whole 'players' array
foreach($data as $key => $value)
{
var_dump($value); // dump only one player id per iteration
// do something with your database
}
$returningData = $data;
}
header('Content-Type: application/json');
echo json_encode($returningData);
Using JSON:
You can simply use your returning JSON data in jQuery, e.g. like this:
// replace ["1", "2", "3"] with the 'data' variable
jQuery.each(["1", "2", "3"], function( index, value ) {
console.log( index + ": " + value );
});
And if you fill your $data variable on PHP side, use your player id as array key and an array with additional data as value e.g. this following structure:
$data = array(
1 => array(
// data from DB for player with ID 1
),
2 => array(
// data from DB for player with ID 2
),
...
);
// [...]
echo json_decode($data);
What I suspect is that the data posted is not in the proper JSON format. You need to use JSON.stringify() to encode an array in javascript. Here is an example of building JSON.
In JS you can use console.log('something'); to see the output in browser console window. To see posted data in php you can do echo '<pre>'; print_r($someArrayOrObjectOrAnything); die();.
print_r prints human-readable information about a variable
So in your case use echo '<pre>'; print_r($_POST); to see if something is actually posted or not.
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'
)
I am having trouble converting from a PHP array to a Javascript array and then accessing the value. I have tried JSON encoding and decoding.
PHP:
$simpleArray= [];
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null,$_product);
foreach($childProducts as $child) { //cycle through simple products to find applicable
$simpleArray[$child->getVendor()][$child->getColor()] = $child->getPrice();
var_dump ($simpleArray);
}
Javascript:
var simpleArray = <?=json_encode($simpleArray)?>;
//..lots of unrelated code
for(var i=0; i < IDs.length; i++)
{
console.log(simpleArray);
//which color id is selected
var colorSelected = $j("#attribute92 option:selected").val();
console.log('Value of color selected is ' + colorSelected);
$j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}
Edit:
I have gotten rid of the simpleArrayJson declaration in the php and changed the first line of the javascript.
The is no reason for you to json_decode() the value you are trying to output. Just echo it directly:
var simpleArray = <?= $simpleArrayJson ?>;
This will output a javascript object literal.
Remove from the php.
$simpleArrayJson=json_encode($simpleArray, JSON_FORCE_OBJECT);
here you are converting the php array into a json string.
Change in the javascript
var simpleArray = <?= json_encode($simpleArray, JSON_FORCE_OBJECT); ?>;
Here you are just outputting the sting. previously you where doing this
var simpleArray = <?=(array) json_decode($simpleArrayJson)?>
which after json_decode was returning an array, which you where casting to an array which then was cast to a string by the <?= so what ended up going to your browser was something like:
var simpleArray = Array;
try a for in loop.
for( item in data ) {
console.log(data[item]);
}
this is because json has keys that match the indexes of the array that was json_encoded, instead of necessarily 0->n indexes.
Edit thanks to comments changed data.item to data[item]
i have encoded my required data in the json object ,but i want to decode the json object into a javscript array, my json encoded object is :
{"product_id":"62","product_quantity":"65"}
however i want to use this json in my java script and want it to be available to a java script array
so if i do :
var arr = new Array()
arr = <?php json_decode('$json_object',TRUE); ?>;
however when i check my page source i get null i.e arr =
how can i assign my json object converted to array to java script array ?
further how to access the json objects from java script array ?
json_decode returns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it through json_encode (and then actually echo the string that it returns).
Note that json_encode outputs a JavaScript data structure that is safe for injecting into a <script> element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren't legal JSON on their own).
Note that there is also no point in creating a new array and assigning it to arr if you are going to immediately assign something else to arr.
Also note that '$json_object' will give you a string starting with the $ character and then the name of the variable. Single quoted string in PHP are not interpolated.
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
Also note that this JSON:
{"product_id":"62","product_quantity":"65"}
Will transform in to a PHP associative array or a JavaScript object (which is not an array).
So given this PHP:
<?php
$json_object = '{"product_id":"62","product_quantity":"65"}';
?>
<script>
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
alert(arr.product_id);
</script>
You get this output:
<script>
var arr;
arr = {"product_id":"62","product_quantity":"65"};
alert(arr.product_id);
</script>
Which alerts 62 when run.
You could push the JSON objects into javascript array and iterate through the array, selecting the appropriate fields you need.
Fixed it..
var json = {"product_id":"62","product_quantity":"65"};
var array = new Array();
array.push(json);
for(var i = 0; i < array.length; i++){
console.log(array[i].product_id)
}
Okay so to start off :
the json string generated in PHP can be used in Javascript as an Object. If you declare the variable as an array to start with then it might conflict.
anyway this should work :
<?php
$error_fields_structure = array(
'product_id' => 4531
,'main_product_quantity' => 2
);
$json_object = json_encode($error_fields_structure);
?>
<html>
<head>
<script>
var jsonstring = <?php echo (isset($json_object) ? $json_object : 'nothing here'); ?>
for( var i in jsonstring ){
alert( i +' == ' +jsonstring[i] );
}
</script>
</head>
<body>
</body>
</html>
Hello there I have a really complex php script that produces a javascript file in jquery
There is a string that is stored in an input type text and I want to converted into json.
The input type text has undedined number of elements.
So I initisialize the string in the input box
<input type="text" id="selectbuttons" value="{}">
After some actions the string in the input box is something like that:
{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}
etc...
Then this is my script , i use the function addScriptto to add it to the document's header, also I am using the core of jquery jquery-1.6.2.min.js to make the json object
$document->addScriptto('
$.noConflict();
jQuery(document).ready(function($) {
var loaded=$("#selectButtons").val();
var obj = jQuery.parseJSON(loaded);
}); //end of dom ready
');
But I can't make it work, when the string is not empty
Is there something wrong with my json syntax? Also, I would be later able to loop all the elements and retrieve the data? Thanks in advance
Your JSON string should be in an array format like below
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
And then you can use the $.each to loop through the JOSN values as below:
$.each(yourJSONstring,function(i,values) {
//yourJSONstring holds the JSON array
// i is just the loop index. it will increment by 1 in every loop
alert(values.button) //will alert bt1 in the 1st loop, bt2 in 2nd
alert(values.style) //will alert style1 in 1st loop, style2 in 2nd
//You can have values here of the keys in JSON using the dot notation as above and do your operations.
})
maybe just put [ ... ] around the JSON so it is understood as an array, something like:
var obj = jQuery.parseJSON( '[' + loaded + ']' );
Yes, your JSON syntax is wrong. You should have it like:
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
and then you will have array of your objects.