34

I want to send some data in json format to php and do some operation in php. My problem is i can't send json data via ajax to my php file.Please help me how can i do that. I have tried this way..

<script>
$(function (){
 $("#add-cart").click(function(){
    var bid=$('#bid').val();
    var myqty=new Array()
    var myprice=new Array()

    qty1=$('#qty10').val();
    qty2=$('#qty11').val();
    qty3=$('#qty12').val();

    price1=$('#price1').val();
    price2=$('#price2').val();
    price3=$('#price3').val();

    var postData = 
                {
                    "bid":bid,
                    "location1":"1","quantity1":qty1,"price1":price1,
                    "location2":"2","quantity2":qty2,"price2":price2,
                    "location3":"3","quantity3":qty3,"price3":price3
                }
    var dataString = JSON.stringify(postData);

    $.ajax({
            type: "POST",
            dataType: "json",
            url: "add_cart.php",
            data: {myData:dataString},
            contentType: "application/json; charset=utf-8",
            success: function(data){
                alert('Items added');
            },
            error: function(e){
                console.log(e.message);
            }
    });
});
});
</script>

And in PHP i use:

if(isset($_POST['myData'])){
 $obj = json_decode($_POST['myData']);
 //some php operation
}

When in add print_r($_POST) in php file, it shows array(0) {} in firebug.

1
  • Remove the contentType: "application/json; charset=utf-8",. Commented Jun 8, 2012 at 19:34

8 Answers 8

52

Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don't need to use JSON.stringify or json_decode here at all. Just do:

data: {myData:postData},

Then in PHP:

$obj = $_POST['myData'];
Sign up to request clarification or add additional context in comments.

8 Comments

So what if I am sending json to server? how do I receive it? And why does it differ from MVC.NET?
@Ayyash: If you were sending JSON, you'd have to read the raw input data (from php://input). I don't know anything about MVC.NET, so I can't answer that.
or maybe its an IIS vs Apache issue? I use the same ajax function in both, but in .NET i just grab Request.Post, in PHP that doesn't work, neither did php://input for some reason, the only thing that worked was passing query string attributes and using $_REQUEST... that hurts
@Ayyash: What's wrong with using query strings and $_POST? That's how HTML forms are submitted. If you really want to send JSON, you can try $HTTP_RAW_POST_DATA if php://input doesn't work.
I think I get it, "I THINK", see in MVC if you do not set content-type to json, you won't be a happy person sending back json objects that map to models, but it also is possible to read it from Request... that isn't the case in PHP. On the other hand if you do choose to go with JSON contentType, JSON.stringify the whole data object is required in MVC forms, but it wouldn't pass in my PHP form!
|
24

That's because $_POST is pre-populated with form data.

To get JSON data (or any raw input), use php://input.

$json = json_decode(file_get_contents("php://input"));

1 Comment

If I were going to do this, I wouldn't be using jQuery, for one. For another, I'd be doing everything manually.
16

To send javascript obj to php using json and ajax:

js:

var dataPost = {
   "var": "foo"
};
var dataString = JSON.stringify(dataPost);

$.ajax({
   url: 'server.php',
   data: {myData: dataString},
   type: 'POST',
   success: function(response) {
      alert(response);
   }
});

to use that object in php:

$obj = json_decode($_POST["myData"]);

echo $obj->var;

Comments

13

If you want to get the values via the $_POST variable then you should not specify the contentType as "application/json" but rather use the default "application/x-www-form-urlencoded; charset=UTF-8":

JavaScript:

var person = { name: "John" };

$.ajax({
    //contentType: "application/json", // php://input
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: {data: person}
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

// $_POST

$jsonString = $_POST['data'];

$newJsonString = json_encode($jsonString);
header('Content-Type: application/json');
echo $newJsonString;

Else if you want to send a JSON from JavaScript to PHP:

JavaScript:

var person = { name: "John" };

$.ajax({
    contentType: "application/json", // php://input
    //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: person
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

$jsonString = file_get_contents("php://input");
$phpObject = json_decode($jsonString);

$newJsonString = json_encode($phpObject);
header('Content-Type: application/json');
echo $newJsonString;

2 Comments

I am not the questioner, but however it helped me a lot :D
This is the most accurate answer
4

I believe you could try something like this:

var postData = 
            {
                "bid":bid,
                "location1":"1","quantity1":qty1,"price1":price1,
                "location2":"2","quantity2":qty2,"price2":price2,
                "location3":"3","quantity3":qty3,"price3":price3
            }
$.ajax({
        type: "POST",
        dataType: "json",
        url: "add_cart.php",
        data: postData,
        success: function(data){
            alert('Items added');
        },
        error: function(e){
            console.log(e.message);
        }
});

the json encode should happen automatically, and a dump of your post should give you something like:

array(
    "bid"=>bid,
    "location1"=>"1",
    "quantity1"=>qty1,
    "price1"=>price1,
    "location2"=>"2",
    "quantity2"=>qty2,
    "price2"=>price2,
    "location3"=>"3",
    "quantity3"=>qty3,
    "price3"=>price3
)

1 Comment

Lose the contentType: "application/json; charset=utf-8",. You're POSTing a standard query string, not JSON. Then print_r($_POST) should give you the array you show.
2

just remove:

...
//dataType: "json",
url: "index.php",
data: {myData:postData},
//contentType: "application/json; charset=utf-8",
...

4 Comments

You should probably keep dataType: "json",, that's the data type the server returns.
yes its true, but json must be returned to avoid another error
I assume the OP is returning JSON, but just didn't show that. I don't think there'd be an error if you returned nothing. You'd only get an error if what you returned wasn't JSON.
from here "In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown." That means the user -must- call json_encode() or get an error, tested.
1

You are tryng to send js array with js object format.

Instead of use

var a = new array();
a['something']=...

try:

var a = new Object();
a.something = ...

Comments

0

I know it's been a while, but just in case someone still needs it:

The JSON object I need to pass:

0:{CommunityId: 509, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}
1:{CommunityId: 510, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}

The Ajax code:

data: JSON.stringify(The-data-shows-above),
type: 'POST',
datatype: 'JSON',
contentType: "application/json; charset=utf-8"

And the PHP side:

json_decode(file_get_contents("php://input"));

It works for me, hope it can help!

Comments

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.