I have an array in JavaScript that is grossIncome.Tthis array contains 6 elements. Now I want to send this array to an another PHP page using $.ajax method but how can I encode this array in JSON format?
4 Answers
Use JSON.stringify() (if you want to support older browsers, you have to include this file from Douglas Crockford):
$.ajax(
{
"url": "some_script.php",
"data": {json: JSON.stringify(gossIncome)},
"success": function()
{
// Do something!
}
});
In a PHP script you could decode it with json_decode:
<?php
$json = isset($_GET['json']) ? $_GET['json'] : exit('No JSON passed!');
$array = json_decode($json);
if ( json_last_error() != JSON_ERROR_NONE )
exit('JSON invalid!');
?>
3 Comments
JSON.stringify() without any libraries.data: {json: JSON.stringify(gossIncome)}.This should do the job: http://www.openjs.com/scripts/data/json_encode.php
If you use jQuery or other JS Frameworks, look at there plugin repositories, normally they have a JSON class to de/encode arrays/objects...
Comments
The array is already technically in JSON, though to be passed via HTTP to a file, you'll want to serialize the data to maintain the name pair values as a string. Fortunately, jQuery has a built-in param() method. You could use it like this:
$.ajax({
url: 'path/to/file.php',
type: 'POST',
data: $.param(grossIncome),
success: function(msg) {
console.log(msg); // or whatever
}
});
Unfortunately, param() in only useful for arrays in the form of object maps... ie:
var grossIncome = {
valueOne: "123",
valueTwo: "321"
};
2 Comments
grossIncome seems to be an array, you cannot call serialize on it.serialize() for this purpose before, but clearly I'm mistaken. Thanks for the catch and I've changed my answer.