how to make the json data into jquery code? - php

the php json_encode($object) result is
[{"price_id":"1","website_id":"0","price_qty":2,"price":"90.0000"},
{"price_id":"2","website_id":"0","price_qty":5,"price":"80.0000"},
{"price_id":"3","website_id":"0","price_qty":8,"price":"70.0000"}]
someone tell me, var sorted = arrayWithJsonData.sort(function(a,b){}
how to use the above php json_encode($object) to arrayWithJsonData.
i used the following way, but it shows TypeError: object.sort is not a function
first: in php i did: echo '<div style="display:none;" id="object">'.$object.'</div>'; then using in jquery
var object=jQuery("#object").text(); // first sort the array var sorted = object.sort(function(a,b){}

You need to parse the object first so javascript(jQuery) can understand it:
JSON.parse(data);

var arrayWithJsonData = $.parseJSON($('#object').text());
$.parseJSON is a jQuery utitlity for converting a well-formed json string to a json object (jQuery doc: http://api.jquery.com/jQuery.parseJSON/). In our case, $('#object').text() method of the matched element returns the well-formed json string which is the output of the PHP function json_encode($object). Hope that helps.

var arrayWithJsonData = <?php json_encode($object) ?>;
var sorted = arrayWithJsonData.sort(function(a, b){
// Sort criteria between a and b
});

Related

Create a Javascript array from a PHP array

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]

Json decode in javascript

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>

foreach for javascript, json array

I have a JSON array that looks like this:
[{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}]
The code to get this json array is as of the following:
var unavailableDates1 = jQuery.parseJSON('<?php echo json_encode($noticesDates) ?>');
I am trying too get all of the dates in that array (which was originally a multidimensional array), and put it inside one array:
var unavailableDates = ["9-3-2012", "14-3-2012", "15-3-2012"]; for example
I am unsure of how to do this, I have tried a foreach but wasn't successful.
All help will be appreciated.
First of all, that parseJSON is unnecessary and actually dangerous. Take it out:
var unavailableDates1 = <?php echo json_encode($noticesDates) ?>;
Then, just use jQuery.map:
var unavailableDates = $.map(unavailableDates1, function(item) {
return item.RegDate;
});
Using a string like that is dangerous for the following three objects, for example:
{"key":"Backslash here: \\"}
{"key":"I'm a horse!"}
{"key":"Some\\backslash"}
They become, respectively:
SyntaxError: Unexpected end of input (Single escape escapes end of string)
SyntaxError: Unexpected identifier (Unescaped single quote breaks out of the string, actually an XSS vulnerability)
Object
key: "Someackslash" (\\b becomes the \b backspace control character)
__proto__: Object
You could escape it again, but there's no need; valid JSON is always a valid JavaScript object, and you can trust your own PHP not to include injection code in there.
var justDates = [];
for (var i=0; i < unavailableDates1.length; i++) {
justDates.push(unavailableDates1[i]['RegDate']);
}
Each Object ({'RegDate:'date'}) is an item in a javascript array. To get an item you use a numerical index. so to get the first item would be theArray[0] this would give you {"RegDate":"31-03-2011"}. Then to get that particular date string you just have to use the key theArray[0]['RegDate']!. So since you want to go through every member of a list, you should get the list length using .length.
For loops are usually used for this type of iteration and not for..in. because for in can access properties that are undesired! http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
have a look at how to iterate over an array.
You can do something like:
dates = new Array();
unavailableDates1.forEach(function (obj){
dates.push(obj.RegDate);
};
Try the following:
JavaScript:
var x = [{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}];
var ary = new Array();
for (foo in x) {
ary.push(x[foo].RegDate);
}
console.log(ary);
jsFiddle example.
I noticed you tag jquery in here as well so, here's a jquery solution:
http://jsfiddle.net/aztechy/DK9KM/
var foo = [
{"RegDate":"31-03-2011"},
{"RegDate":"29-07-2011"},
{"RegDate":"09-08-2011"},
{"RegDate":"09-08-2011"}
];
var datesArray = [];
$.each(foo, function() {
datesArray.push(this.RegDate);
});
console.log(datesArray);​
Try This, it may works.
var unavailableDates = [];
for(var i = 0; i < unavailableDates1.length; i++){
unavailableDates[i] = unavailableDates1[i].RegDate;
}
for(var i=0;i<unavailableDates.length;i++) {
unavailableDates[i] = unavailableDates[i].RegDate;
}

Parsing a JSON string to array, not object

I've got a PHP array and echo that into javascript with json encode, i need to do it this way because it's going to be very dynamic. This is the code it echo's:
{"notempty":true}
And i use this to, convert it to javascript:
var myarray = eval('(' + json + ')');
For some reason it creates an object instead of an array and for that reason i cant use .length or a for loop.
Does someone know what im doing wrong here?
Thanks
You're trying to treat an Object like an Array, and an Object is not an Array, it is an Object.
Any time you see {} in JSON, that means "What is contained within these hallowed brackets is a dynamic object". When you see [], that means "Behold! I am an Array" (there are notable exceptions to this one: jQuery does some special work with to make itself look like an array).
So, in order to iterate through an Object, you'll want to use for... in.
// eval BAD unless you know your input has been sanitized!.
var myObj = JSON.parse('{"notempty":true}');
// personally, I use it in for... in loops. It clarifies that this is a string
// you may want to use hasOwnProperty here as sometimes other "keys" are inserted
for( var it in myObj ) console.log( "myObj["+it+"] = " + myObj[it] );
{} is an object, which contains one attribute named notempty. If you want an array, it'd have to be
[{"notempty":true}]
which is an array with a single element at index 0, which is an object with the single attribute 'notempty';.
By default, if you use encode an assoc array in php, it will become a js object when you decode. In order to have it be an array, you need to make it an array in php:
PHP:
$arr = "['notempty','notempty2','notempty3']";
Otherwise, you should convert it to an array in JS, but that seems to me a waste since looping through the object in javascript is so much easier:
Javascript:
var arr = new Array();
for(var i in obj) arr[i] = obj[i];
You can use jQuery to parse it into an array like this:
var p = [];
$.each(jsonData, function (key, val) {
p.push([val.propertyOne, val.propertyTwo]);
});
I am presuming of course that you want to parse JSON, not an array or any other string.

Passing a multidimensional PHP array to javascript

I have an array($my_array) that looks something like:
array(2) {
[25]=>int(10)
[30]=>int(8)
}
I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?
Edit: At first, I thought I could just assign it like a string, but that isn't working:
var photo_limit = $my_array;
I tried also doing a var_dump into my js value.
I'm currently trying to use something like:
for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}
Thanks.
The best way is to use json_encode. See json_encode reference
Used like this:
<script>
var array = <?php echo json_encode($array)?>;
</script>
Note, hovewer, that you'll receive Javascript object, instead of array. At a glance the only difference is if you have string keys in your array, you'll be able to access them in JS like array.*string key*, i.e. using dot notation.
1: json_encode your PHP array.
2: Decode the JSON string in JavaScript using eval(alternative: jQuery.parseJSON)
<script>
var arr = eval('(<?php echo json_encode($thePhpArray); ?>)');
</script>

Categories