Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 250
Alekc Avatar asked Apr 03 '09 13:04

Alekc


3 Answers

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.

like image 155
Paolo Bergantino Avatar answered Nov 19 '22 12:11

Paolo Bergantino


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

like image 7
Shadrack B. Orina Avatar answered Nov 19 '22 11:11

Shadrack B. Orina


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
like image 4
dstnbrkr Avatar answered Nov 19 '22 12:11

dstnbrkr