5

I am going to send a array of json object through jquery ajax call to a php file.

var arr = new Array();
var record1 = {'a':'1','b':'2','c':'3'};
var record2 = {'d':'4','e':'5','f':'6'};
arr.push(record1);
arr.push(record2);

How can I send the array through jquery ajax? and how can I get the values in php? Thanks.

asked Jan 25, 2013 at 13:58
1
  • 2
    you need to serialize json object and deserialize that in you PHP code.... !! Commented Jan 25, 2013 at 14:00

4 Answers 4

17
$.ajax({
 url: "api",
 type: "POST",
 dataType: 'json',
 data: JSON.stringify(arr),
 success: function(response){}
 });

And with PHP:

$strRequest = file_get_contents('php://input');
$Request = json_decode($strRequest);
answered Jan 25, 2013 at 14:05
Sign up to request clarification or add additional context in comments.

Comments

2

I think JSON.stringify() might be useful.

or, you can use json_decode() in php file.

answered Jan 25, 2013 at 14:02

Comments

1

First download and add plugin : jquery.json-2.4.js to your project. This plugin offers a lot of helpers that will make your life easy.

Then in your $.ajax , use data : $.toJSON(arr),

answered Jan 25, 2013 at 14:06

Comments

1

The first thing you have to know is that you need to be with two files to make things simple for yourself . 1. Where you going to put your php code phpcode.php 2. Where you going to put your ajax codes ajax.html In the page where you going to put your ajax code make sure you connect to jquery plugins Then

 <script> 
 $(document).ready(function(){
 // your ajax code here delete mine and put your codes
 $.getJSON(' phpcode.php ', function(data) {
 $('#myJson').html('<table style="color:red"><tr><td>' + data.name + '</td><td>' + data.user + '</td></tr></table>');
 });
 });
 </script>
 <body>
 <!—You may put the bellow div in the ajax page so that u load your data in it ---->
 <div id="myJson"></div>
 </body>
 </html>
 In your php page you need something like this at the end of your code 
 // The JSON standard MIME header.
 header('Content-type: application/json');
 echo json_encode($array);
 Note: I took an example from my working codes just to save the time but I think you get the Idea
answered Jan 25, 2013 at 14:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.