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;
-
14JSON is your friend :-)Ben Everard– Ben Everard2011年02月17日 22:33:28 +00:00Commented Feb 17, 2011 at 22:33
-
1The quality of advice we can give is limited by the vagueness of your answer. Can you post some sample code of the loop you're using?user229044– user229044 ♦2011年02月17日 22:36:03 +00:00Commented Feb 17, 2011 at 22:36
-
1How can I send the data through JSON/retrieve it on the other end?switz– switz2011年02月17日 22:47:59 +00:00Commented Feb 17, 2011 at 22:47
6 Answers 6
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.
7 Comments
mysql_real_escape_string(), and anything that will be put onto the screen through htmlentities()JSON.stringify(array), do you have to insert it into a JSON object literal, like datavar = { array: array} ? Or can you just pass array in place of datavar in the parameter of your .getJSON() request? e.g. .get(script.php, array, function(data) {.... Also, is it always jsondata within your $_POST ?.get(script.php, JSON.stringify(array), function(data{... and then retrieve it with $postvars=file_get_contents('php://input');$array=json_decode($postvars, true);, or you can use: .get(script.php, {array: JSON.stringify(array)}, function(data{... and retrieve it with $array=json_decode($_POST['array'], true);.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.
1 Comment
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.
1 Comment
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.
1 Comment
To anyone looking to accomplish this with support for the default PHP $_POST array handling, you need to append multiple values to the same key[] of your FormData.
e.g.
var form_data = new FormData();
my_array_elements.forEach(x => {
form_data.append('your_array_field_name[]', x);
});
Comments
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);
?>