79

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;

switz
  • 24,384
  • 25
  • 76
  • 101

5 Answers5

139

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.

Gareth
  • 5,693
  • 3
  • 28
  • 37
  • 19
    don't forget to sanitize your inputs, or you're toast! :D – Stephen Feb 17 '11 at 23:06
  • 14
    You should assume that any input to your PHP scripts could have been compromised by someone with malicious intentions. Run any variables that you are planning to put into a database query through `mysql_real_escape_string()`, and anything that will be put onto the screen through `htmlentities()` – Gareth Feb 18 '11 at 19:21
  • @Gareth after you use `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 ? – LazerSharks Jun 28 '13 at 07:04
  • 1
    @Gnuey You can either do this: `.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);`. – Gareth Jun 28 '13 at 10:05
  • Just to make sure, will stringify also work if I have an $array integers, and in an SQL query I need to match $array (the array of integers) with integers in an attribute column? I read that integers are not specially distinguished, but I just wanted to make sure in this case. – LazerSharks Jun 28 '13 at 23:49
  • I think if you want to send dynamic javascript data to php then you can't use this function nor any other function, because then you need to refresh the page in order to make php accept the new data – Yosra MH Jan 22 '21 at 12:00
  • the JSON.stringify(array) sent via $.post gets quotes replaced by " so json_decode doesn't work with it unless you do $array=json_decode(htmlspecialchars_decode($_POST['jsondata'])); – klm123 Mar 18 '21 at 16:53
41

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.

Alexey Lebedev
  • 11,988
  • 4
  • 39
  • 47
  • 2
    I don't know why this isn't accepted answer as it is exactly what OP asked for and causes less hassle, especially that some frameworks automagically explode POST arrays for you – zakius Aug 05 '15 at 07:36
3

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.

mgraph
  • 15,238
  • 4
  • 41
  • 75
Dennis Kreminsky
  • 2,117
  • 15
  • 23
0

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • @Switz I assumed you were using the `data` parameter of a [`$.get`](http://api.jquery.com/jQuery.get/) or [`$.post`](http://api.jquery.com/jQuery.post/) call. – user229044 Feb 17 '11 at 23:02
-1

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);

?>
Reha Ozenc
  • 39
  • 4