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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Abdullah Al Shakib
  • 2,034
  • 2
  • 15
  • 16

8 Answers8

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'];
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • So what if I am sending json to server? how do I receive it? And why does it differ from MVC.NET? – Ayyash Aug 27 '13 at 09:22
  • @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. – gen_Eric Aug 27 '13 at 14:23
  • 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 Aug 27 '13 at 16:02
  • @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`](http://www.php.net/manual/en/reserved.variables.httprawpostdata.php) if [`php://input`](http://www.php.net/manual/en/wrappers.php.php) doesn't work. – gen_Eric Aug 27 '13 at 16:08
  • 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! – Ayyash Aug 28 '13 at 08:01
  • @Ayyash. That's because in ASP.NET MVC you are forgetting that when you posting a jsonResult string to the cshtml view page from the controller and on the actual view you are handling json. Then you post it back to the controller using ajax for processing. Hope that helps. – yardpenalty.com Mar 19 '16 at 03:25
  • Thank you. I didn't realise, that I did not have to encode the object to JSON myself. – Emil Rosenius Apr 17 '17 at 03:06
  • Lose the `contentType: "application/json; charset=utf-8",` help me alot... you are my hero. – inMILD May 09 '22 at 04:44
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"));
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
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;
Akhan Ismailov
  • 161
  • 1
  • 3
12

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;
tedi
  • 6,350
  • 5
  • 52
  • 67
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
)
ContextSwitch
  • 2,830
  • 6
  • 35
  • 51
  • 1
    Lose the `contentType: "application/json; charset=utf-8",`. You're `POST`ing a standard query string, not JSON. Then `print_r($_POST)` should give you the array you show. – gen_Eric Jun 08 '12 at 19:44
2

just remove:

...
//dataType: "json",
url: "index.php",
data: {myData:postData},
//contentType: "application/json; charset=utf-8",
...
  • 2
    You should probably keep `dataType: "json",`, that's the data type the server returns. – gen_Eric Jun 08 '12 at 19:54
  • yes its true, but json must be returned to avoid another error –  Jun 08 '12 at 20:01
  • 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. – gen_Eric Jun 08 '12 at 20:03
  • from [here](http://api.jquery.com/jQuery.ajax/) "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. –  Jun 08 '12 at 20:16
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 = ...
xackobo
  • 261
  • 2
  • 4
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!

Jack
  • 170
  • 2
  • 15