How do you convert a JS array into a PHP array? [duplicate] - javascript

Let's say I have a javascript array with a bunch of elements (anywhere from 50-200).
I want to send that to PHP (prepared statement) using ajax. Currently, I .load a php file many times inside of a loop, but I want to convert that into an array and send the array once, loading the PHP file once instead of 50-200 times.
array[i] = variable;

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

AJAX requests are no different from GET and POST requests initiated through a <form> element. Which means you can use $_GET and $_POST to retrieve the data.
When you're making an AJAX request (jQuery example):
// JavaScript file
elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})
It's (almost) equivalent to posting this form:
<form action="/test.php" method="post">
<input type="text" name="elements" value="1,2,9,15">
</form>
In both cases, on the server side you can read the data from the $_POST variable:
// test.php file
$elements = $_POST['elements'];
$elements = explode(',', $elements);
For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.

Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:
function obj2url(prefix, obj) {
var args=new Array();
if(typeof(obj) == 'object'){
for(var i in obj)
args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
}
else
args[args.length]=prefix+'='+encodeURIComponent(obj);
return args.join('&');
}
prefix is a parameter name.
EDIT:
var a = {
one: two,
three: four
};
alert('/script.php?'+obj2url('a', a));
Will produce
/script.php?a[one]=two&a[three]=four
which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.

So use the client-side loop to build a two-dimensional array of your arrays, and send the entire thing to PHP in one request.
Server-side, you'll need to have another loop which does its regular insert/update for each sub-array.

You can transfer array from javascript to PHP...
Javascript... ArraySender.html
<script language="javascript">
//its your javascript, your array can be multidimensional or associative
plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info';
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3';
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4';
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5';
function convertJsArr2Php(JsArr){
var Php = '';
if (Array.isArray(JsArr)){
Php += 'array(';
for (var i in JsArr){
Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
Php += ', ';
}
}
Php += ')';
return Php;
}
else{
return '\'' + JsArr + '\'';
}
}
function ajaxPost(str, plArrayC){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("POST",str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('Array=' + plArrayC);
}
ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>
and PHP Code... ArrayReader.php
<?php
eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);
?>

Related

How to fill javascript array from ajax data result

I have scripts like this.
javascript
$.ajax({
url : "load_data_person.php",
dataType:"json",
success:data_person(arrData)
});
function data_person(info_person){
var attr = [];
var len = [];
for(j=0;j<info_person.length;j++){
attr.push(info_person[j][0]);
len.push(info_person[j][1]);
}
return [attr, len];
}
How can I insert data to variable info_person like this:
info_person = [['fname',20],['lname',15],['addr',50]];
so I can get each value of attr and len?
Here is the script for data_person.php
<?php
$qStrPerson = mysql_query("SELECT atribut, len FROM tb_person ORDER BY fname ASC");
$arrFullPerson = array();
while($rStrPerson = mysql_fetch_array($qStrPerson)){
$arrFullPerson[] = array($rStrPerson[atribut],$rStrPerson[len]);
}
echo json_encode($arrFullPerson);
// it will return like this : Array 0 : ['fname', 20], Array 1 : ['lname',15], Array 2 : ['addr',50]];
?>
Thank you for your help.
You can use simple jquery to convert the JSON to Javascript array
var array = JSON.parse(your json string);
You can just format the array as you wanted in the server side and then echo it. While receiving the ajax response, you can simply
var info_person = json.parse(arData);
to convert the json-encoded value into javascript array.

Javascript JSON.stringify / PHP json_decode Not working

I'm trying to send an array to PHP from JS.
JS:
var json = JSON.stringify(extraFields);
url += "&json="+json;
PHP:
$json = json_decode($_GET['json'], true);
foreach($json as $K=>$V){
echo "json".$K . "=" . $V ."; ";
}
Assume extraFields is a valid array in this format:
extraFields['key1'] = 'val1';
extraFields['key2'] = 'val2';
extraFields['key3'] = 'val3';
The PHP error I'm getting is invalid argument for Foreach
When I loop through the $_GET values and just echo them, PHP shows empty brackets for $_GET['json'] so it's recognizing it as json..
What am I doing wrong?
Answer to TJ's comment
var extraFields = new Array();
var countFields = THIS.$_FIELDS.length;
var Row = new Array();
while(countFields--){
var name = THIS.$_FIELDS[countFields]['name'];
var id = THIS.$_FIELDS[countFields]['id'];
var elemVal = getElmVal(id);
extraFields[name] = elemVal;
window.alert(name +"="+ elemVal);
}
Two things:
You can't just dump JSON on the end of a URL and expect it to go through to the server correctly.
At the very least, you have to URI-encode it:
url += "&json="+encodeURIComponent(json);
The way you're using extraFields in your code snippet, it is not being used as an array. If you've created it as an array, those keys will not be serialized. The way you're using it, the correct way to create extraFields is:
extraFields = {}; // NOT `= []` and NOT `= new Array()`
That's an object, not an array. (Don't let the PHP term "associative array" fool you; that term is fairly PHP-specific and not related to the term "array" in the general sense. If you want arbitrary name/value pairs in JavaScript code, the term is "object" [or sometimes "map" or "dictionary", but they're objects].)
If you add non-index properties to an array, JSON.serialize will ignore them (leave them out). Only use arrays ([]) with JSON for numerically-indexed data. Using objects ({}) for name/value pairs.

Why does body onload require htmlentities on nested json_encode'd array?

I read database records, and create one PHP array() for each database record, then store each of these arrays as an element of a top-level PHP array(). The top level array is thus an array of arrays, and the nested arrays each contain the fields of one database record. Nothing special here.
I need to pass the nested array of database record arrays to two different javascript functions and so I use json_encode in PHP before passing the nested array:
CASE #1: the first pass of the nested json_encoded-d is to a Javascript function doSomeStuff( theNestedJsonEncodedArray) -- I used a hidden iframe technique to pass the nested array into javascript code (see below)
CASE #2: the other pass of the nested array is to my web page's body onload=handleLoad( theNestedJsonEncodedArray )
With Case #1, I do not need to use htmlentities( theNestedJsonEncodedArray ) in order for this json encoded array to be successfully used in my doSomeStuff() function.
With Case #2, the body onload=handleLoad( ) function will NOT EVEN EXECUTE. Unless I add an extra step. The extra step is this: after json_encode'ing the nested array, I have to call htmlentities() -- then and only then will my body onload=handleLoad( ) behave correctly.
I 100% fail to understand this. I do not understand why, in the case of my "PHP/iframe/javascript" scenario, json_encode() is sufficient to pass the nested array -- but my "body onload=handleLoad()** case, I need to use htmlentities() on the nested array, or the onload javascript function will not even execute.
Note here: there is zero html in my database records.
CASE #1 CODE -- uses a hidden iframe to pass javascript code to my web page:
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
$theTopLevelArray= array();
for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$recordNum = $theRow[0];
$lat = $theRow[1];
$lng = $theRow[2];
$city = $theRow[3];
$state = $theRow[4];
// EACH NESTED ARRAY IS A TOWN with City, State, Latitude, Longitude
$nestedArray = array( $lat, $lng, $i, $recordNum, $city, $state);
$theTopLevelArray[] = $nestedArray;
}
$jsonArray = json_encode($theTopLevelArray);
echo '<script type="text/javascript">' . "\n";
echo 'var parDoc = parent.document;' . "\n";
$sendToWebpageStr = "parent.doSomeStuff( $jsonArray );";
echo $sendToWebpageStr;
echo "\n".'</script>';
// And in my web page's javascript code......
function doSomeStuff( theNestedJsonArray )
{
// Traverse the array of Towns and show their latitude and longitude
for (var i = 0; i < theNestedJsonArray.length; i++)
{
var town = theNestedJsonArray[i];
var lat = town[1];
var long = town[2];
alert("The lat, long are: " + lat + ", " + long);
// ALL THIS WORKS FINE.
}
}
CASE #2 CODE -- REQUIRES AN EXTRA STEP, A CALL TO htmlentities( )
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
$theTopLevelArray= array();
for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$recordNum = $theRow[0];
$lat = $theRow[1];
$lng = $theRow[2];
$city = $theRow[3];
$state = $theRow[4];
// EACH NESTED ARRAY IS A TOWN with City, State, Latitude, Longitude
$nestedArray = array( $lat, $lng, $i, $recordNum, $city, $state);
$theTopLevelArray[] = $nestedArray;
}
$jsonArray = json_encode($theTopLevelArray);
$readyNowArray = htmlentities( $jsonArray );
// AND HERE'S THE 'body' ON MY PAGE:
<body onload="handleLoad( <?php echo $readyNowArray ?> )">
// HERE IS handleLoad()
function handleLoad( theNestedArray )
{
var town = theNestedArray[0];
alert("bl.js, handleLoad(), town is: " + town);
alert("bl.js, handleLoad(), town[0] is: " + town[0]);
alert("bl.js, handleLoad(), town[1] is: " + town[1]);
}
If I do not call html entities for CASE #2 -- the handleLoad() function does not even execute.
Is there some nuance here when echo'ing a PHP array in the body onload tag that is requiring the extra step of calling htmlentities() on the json array, while passing the json array directly into javascript from PHP code by way of an iframe is bypassing that somehow?
Is there some nuance here when echo'ing a PHP array in the body onload
tag that is requiring the extra step of calling htmlentities() on the
json array
Yes. You're echoing into HTML, for which you of course need htmlentities. If you don't, any quotes from the JSON will end your HTML onload attribute value, and the resulting js is nothing but a syntax error.
while passing the json array directly into javascript from PHP code
is bypassing that somehow?
Inside a <script>, nothing but </script> does need to be escaped.

How to get multidimensional array data using java script and php

I have a multidimensional array in php, and i want to get its data from javascript but i didn't work
here my code in php
$managername = $_SESSION['managername'];
$sqls = "select s.*,m.* from rm_allowedmanagers m inner join rm_services s on s.srvid = m.srvid where m.managername = '$managername' ";
$sql = mysql_query($sqls);
$newservices = array();
while($row = mysql_fetch_array($sql))
{
$nsrvid = $row['srvid'];
$nsrvname = $row['srvname'];
$nunitprice = $row['unitprice'];
$nunitpricetax = $row['unitpricetax'];
$ntotal = $nunitprice + $nunitpricetax;
$newservice = array($nsrvid, $nsrvname , $ntotal);
array_push ($newservices, $newservice);
}
and here my java script code
<script>
function changeserviceprice(id)
{
var newservice = $("#newservice").val();
var data = '<?= $newservices ?>';
var asd = data;
var asd2 = data[0][0];
$("#qq4").val(asd);
$("#qq5").val(asd2);
}
</script>
PHP code i think it is work fine, and i think the error is in javascript function.
when i try to print the data using javascript it print the "Array" word when i print the whole row "array", but
it print "a" character when i try to print the first element in the first array!!
try encoding the $newservices array:
var data = <?php echo json_encode($newservices); ?>;

Convert js Array() to JSon object for use with JQuery .ajax

in my app i need to send an javascript Array object to php script via ajax post. Something like this:
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
alert(saveData);
$.ajax({
type: "POST",
url: "salvaPreventivo.php",
data:saveData,
async:true
});
Array's indexes are strings and not int, so for this reason something like saveData.join('&') doesn't work.
Ideas?
Thanks in advance
Don't make it an Array if it is not an Array, make it an object:
var saveData = {};
saveData.a = 2;
saveData.c = 1;
// equivalent to...
var saveData = {a: 2, c: 1}
// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;
Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.
If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by Paolo Bergantino
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
//creating a json object
var jObject={};
for(i in saveData)
{
jObject[i] = saveData[i];
}
//Stringify this object and send it to the server
jObject= YAHOO.lang.JSON.stringify(jObject);
$.ajax({
type:'post',
cache:false,
url:"salvaPreventivo.php",
data:{jObject: jObject}
});
// reading the data at the server
<?php
$data = json_decode($_POST['jObject'], true);
print_r($data);
?>
//for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
//include the follwing files
//<!-- Dependencies -->
//<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
//<!-- Source file -->
//<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>
Hope this helps
You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:
var a = [];
for (key in saveData) {
a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1
There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
There is no need of converting it into JSON because its already a json object.
To view the same use json.toSource();
When using the data on the server, your characters can reach with the addition of slashes eg
if string = {"hello"}
comes as string = {\ "hello \"}
to solve the following function can be used later to use json decode.
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = $_POST['jObject'];
$array = stripslashes_deep($array);
$data = json_decode($array, true);
print_r($data);
?>

Categories

Resources