I'd like to pass arrays through JSON like this:
<?php
for(i=0;i<5;i++) {
$arrayA[i] = "A" . i;
$arrayB[i] = "B" . i;
}
echo json_encode($arrayA,$arrayB);
?>
I know it's not possible, but is there other way to pass dynamicly loaded arrays and read them in javascript after that?
Just put both array in another array.
$returnArr = array($arrayA,$arrayB);
echo json_encode($returnArr);
On JS side just decode with a library of your choice and access the returned array like any normal array.
echo json_encode(array('arrayA' => $arrayA, 'arrayB' => $arrayA));
Just create wrapper for your arrays:
for(i=0;i<5;i++) {
$arrayA[i] = "A" . i;
$arrayB[i] = "B" . i;
}
$arrayC = array($arrayA,$arrayB);
echo json_encode($arrayC);
On jQuery side:
$.getJSON('ajax/yourPhpFile.php', function(data) {
$.each(data, function(key, val) {
// each `val` is one of the arrays you passed from php
});
});
You can use AJAX to load up a script that will return a PHP generated array. If you're using jQuery, you call it using either $.get() or $.getJSON(). You can read up on PHP JSON manual here http://php.net/manual/en/book.json.php and on jQuery .getJson() function here http://api.jquery.com/jQuery.getJSON/
Related
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]
Here is my code:
var var_ids = new Array();
var i = 0;
jQuery("select").each(function() {
var_ids[i] = jQuery("option:selected",this).val();
i++;
}
var $data = {
action: "do_something",
var_ids: var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
And in my php:
$ids = mysql_real_escape_string(trim($_POST['var_ids']));
exit(print_r($ids));
And it just returns garbage...So my question is how to pass an array via AJAX to post php?
Thank you.
Most likely you get unexpected results because you apply string-related functions trim and mysql_real_escape_string to array $_POST['var_ids']
As long as it is just an array of integers - the only mysql sanitize you need is casting to int:
$ids = array_map('intval', $_POST['var_ids']);
print_r($ids);
$_POST['var_ids'] is an array in your example on the PHP side. You can only call trim and mysql_real_escape_string on strings not arrays. Try this in php:
$postData = isset($_POST['var_ids'])?$_POST['var_ids']):null;
if(is_array($postData)){
foreach($postData as $key=>$value){
$postData[$key] = mysql_real_escape_string(trim($value));
}
}
Viola, $postData is now a PHP array with trimmed and escaped values.
It's in the docs about 1/4 of a way down titled pass arrays of data to the server
var var_ids = new Array('10','12','13');
var $data = {
action: "do_something",
'var_ids[]': var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
Make it json_encoded array ... And then You can json_decode() the array properly.
You'll have better luck converting the array to a JSON object (Javascript Object Notation) and sending it that way.
Javascript JSON Instructions
JSON PHP Reference
You can either post each of the items with the key items[], then you could access the array as $_POST['items'] or you can serialize the array, send it and unserialize in PHP (JSON.stringify and PHP json_decode).
My php script sends back a JSON encoded string.
I'm just lost on how to actually use the array now it sits nicely in Javascript?
The end goal is to loop through the the multi-dimensional array in JavaScript to extract values (prices)...
I've managed to get JavaScript to receive the encoded string (tested by printing it onto screen), but I'm not sure how I can actually use the array, or how I would loop through it like I would in PHP..
I basically need to do the JavaScript equivalent to this PHP code
foreach ($array as $item => $value){
foreach ($value as $item2 => $value2){
//peform action on $value2;
}
}
Thanks for any help.
Oz
Assuming you've called the variable arrayFromPhp, you can use a simple nested for loop:
for(var i = 0, l = arrayFromPhp.length; i < l; i++) {
for(var j = 0, l2 = arrayFromPhp[i].length; j < l2; j++) {
var value = arrayFromPhp[i][j];
//Do stuff with value
}
}
Using jquery, you can iterate on a json object like that:
$.each(obj, function(key, value) {
if ($.type(value) == "object") {
$.each(value, function(key, value) {
// value would be $value2 here
})
}
});
Also, if you get a json encoded string from PHP, you can use http://api.jquery.com/jQuery.parseJSON/ to get a json object
var obj = jQuery.parseJSON(stringFromPhp);
You can also directly use $.getJSON() (http://api.jquery.com/jQuery.getJSON/) to automatically get the json object in the callback.
edit: a parenthesis was missing.
i have a variable $visitRecord->getReferallist() which get the list of doctors in an array . i need to send the array to a php file and do foreach action in php file.. how do i send this array variable in the jquery . This code did not work.
function seekOpinion()
{
var queryUrl = "<?php echo $this->url(array('controller' => 'consultant', 'action' =>'opiniondoclist'));?>";
$.post(queryUrl,{referal:'<?php echo $gotreferal; ?>',visitId:'<?php echo $gotvisitId; ?>',referalList:'<?php echo $visitRecord->getReferallist(); ?>'},function(data)
{
$('.opiniondoclistData').html(data);
});
document.getElementById('opiniondoclistDiv').style.display = "";
}
Your problem is that you're working with an Array in PHP.
echo $visitRecord->getReferallist(); // Returns array of referrals.
When you cast the array to a string by echo'ing it (because echo outputs strings) then you get the text "Array".
In order to send this over the wire(from javascript via AJAX ($.post)) you will need to convert your referral list into a string. One method is serialization. You can convert your array into a "stringable format" using the serialize() function. www.php.net/serialize.
When this is received from PHP in the AJAX request you can convert your "stringable formatted" array back into a pure array using the unserialize() function. www.php.net/unserialize.
Your code should change from
$visitRecord->getReferallist();
to
serialize($visitRecord->getReferallist());
Then when it's received you should change your code from
$referrals = $_POST['referalList']; // Stringable version of the array
to
$referrals = unserialize($_POST['referalList']); // Pure PHP array
Use Serialize() to transform your array into a string, send it , then use unserialize() to get it back into an array in php;
Serialize()
I think you can use json_encode() to encode the array as a string that jquery will be able to read back as a javascript array
EDIT: sorry I didn't read your question properly, I see that you don't want to read the array in javascript, but in PHP so probably serialize() and unserialize() is better than json_encode() assuming that it escapes properly for use with javascript.
var sendData = 'referal=<?php echo $gotreferal; ?>&visitId=<?php echo $gotvisitId; ?>&referalList=<?php echo implode('-', $visitRecord->getReferallist()); ?>';
$.post(queryUrl, sendData,function(data) { //etc
Then the receiving script can (in addition to any necessary sanitization):
$referalList = explode('-', $_POST['referalList']);
Don't forget to addslashes to all the variables you are echoing if necessary
PHP will automatically create an array variable from a query string, or posted data, which contains a "[]" at the end of the name. For example, you can do a jQuery load call as follows to pass an array to PHP.
$('#target').load('index.php?foo[]=a&foo[]=b');
On the PHP side, you will have an array called foo in $_GET
<?php
echo 'I have ' . $_GET['foo'][0] . ' and ' . $_GET['foo'][1];
?>
jQuery's AJAX functions, e.g. $.post, $.get and $.ajax can pass javascript arrays like this in their data sections - just be sure to name the variable with a "[]" at the end so that PHP knows how to handle it.
I found a solution on this problem...
Use this function in your javascript...
function js_array_to_php_array (a)
{
var a_php = "";
var total = 0;
for (var key in a)
{
++ total;
a_php = a_php + "s:" +
String(key).length + ":\"" + String(key) + "\";s:" +
String(a[key]).length + ":\"" + String(a[key]) + "\";";
}
a_php = "a:" + total + ":{" + a_php + "}";
return a_php;
}
a is the array you passed in this function
then.. on your php where you get the return array of this function write this code...
$my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
// print_r ($my_array);
Hope it helps...