How to pass javascript associative array in ajax to php file

How to transfer data (associative array) to php file.

 function ajax(url,data,callback)
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                xmlhttp.onreadystatechange = function() {
                    if ( xmlhttp.readyState === 4 ) {
                        callback( xmlhttp.responseText );
                    }
                }
            }
            xmlhttp.open("POST",url,true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send(data);
        }
+3
source share
2 answers

As I read this, you are in javascript and you have a javascript object (javascript has no associative arrays, just arrays and objects). So, whatever data you have, you need to turn it into a string and send it via POST or GET to your php script. I would recommend enabling JSON3 as a polyfill to make sure that your page will JSON.stringify(for cross-browser). The code would be something like this:

var data = {
    someData: 'data',
    moreData: [
        'blah',
        'bleh'
    ]
};

var stringData = JSON.stringify( data );

// using jquery ajax for brevity (http://api.jquery.com/jQuery.ajax/)
$.ajax({
  type: "POST",
  url: "your-php-script.php",
  data: { data: stringData }
});

Now your php script can intercept this line and return it back to json:

<?php
    $dataString = $_POST['data'];
    $data = json_decode($dataString);

Hope this is what you were looking for. Hooray!

+6

PHP JSON. / , javascript.

0