2

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 4

3

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

?>
Sign up to request clarification or add additional context in comments.

3 Comments

Don't forget to include the required JS file - you can find it at github.com/douglascrockford/JSON-js
Thanks edited. But actually all modern browsers supports JSON.stringify() without any libraries.
Better: data: {json: JSON.stringify(gossIncome)}.
0

try something like json_encode();

http://phpjs.org/functions/json_encode:457

Comments

0

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

0

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.
Wow, I muscled with it for a while and you're totally right. I could have swore I've used serialize() for this purpose before, but clearly I'm mistaken. Thanks for the catch and I've changed my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.