-1

How can I send this array back to the server so I can handle it in PHP?

<script>
var myJSONObject = {
        "onw": [ 
            {"name": "nilesh", "age": "31", "sal": "4000"},
            {"name1": "nitin", "age": "11", "sal": "14000"}]
};

document.write(myJSONObject.join());
</script>
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
Nilesh
  • 11
  • 2
  • 1
    What is the `document.write()` for? I think you'll find that `myJSONObject.join()` gives you an error given that `myJSONOBject` isn't an array. When you say "How to post?" do you mean you want to submit that data to PHP via Ajax, or...? You want to take the object (which is not JSON) and stringify it to JSON, submit the JSON, then in PHP parse it and do something with the values? – nnnnnn Nov 09 '13 at 05:11

3 Answers3

0

You can use serialization method. i.e serialize the javascript variable and pass it to php, in php file you can deserialize the same.

serializing : Serializing to JSON in jQuery

Ref: http://api.jquery.com/serializeArray/

Community
  • 1
  • 1
Krish R
  • 22,583
  • 7
  • 50
  • 59
0

Never use document.write as its outdated, the preferred way to add elements to DOM is using appendChild

Example Code for appending:

var textNode = document.createTextNode("some text"); // creates new text node

    textNode.appendChild(document.body); // adds to the end of the body

For posting data to php by using jquery:

Before sending it to server, you need to format it as String using JSON.stringify

var formattedData = JSON.stringify(myJSONObject )

$.ajax({
  type: "POST",
  url: "server.php",
  data: formattedData ,
  dataType: 'json',
  success: function () {
     alert("Data posted to php and processed succesfully"); 
  }
});
0

var json_text = JSON.stringify(myJSONObject, null, 2);

alert(json_text);

Nilesh
  • 11
  • 2