[javascript] 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

This question is related to javascript jquery arrays json

The answer is


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.


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


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

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?