1

I am trying to pass json with ajax, the call is goin okay. I can see the data at the Request Payload section but not in post variable.

var p = {
            c: c,
            g: g,
            t: t
        };

    var myJSON= JSON.stringify(p);

  $.ajax({
            url: "addedit.php",
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: myJSON,
            success: function () {
                alert("success");
            }
        });

PHP code :

$myjson= array();

$myjson= json_decode($_POST['myJSON']);

var_dump($myjson);die;

networking section

POST data

Phil
  • 157,677
  • 23
  • 242
  • 245
John
  • 21
  • 5
  • Does this answer your question? [Receive JSON POST with PHP](https://stackoverflow.com/questions/18866571/receive-json-post-with-php) – Phil Jul 13 '22 at 02:58

1 Answers1

2

You have to pass the data as the object

data: {
    myJSON:              myJSON
},

Full ajax request

$.ajax({
    url: "addedit.php",
    type: 'POST',
    data: {
        myJSON:              myJSON
    },
    success: function () {
        alert("success");
    }
});

My Input data

var p = {
        c: 1001,
        g: 4,
        t: 100
    };

In your php file just do this

$myjson= json_decode($_POST['myJSON'],true);
var_dump($myjson);

The output of var_dump below

array(3) { ["c"]=> int(1001) ["g"]=> int(4) ["t"]=> int(100) }
A.A Noman
  • 5,244
  • 9
  • 24
  • 46
  • thanks for the help, but i have already tried this, yet the same result like "Notice: Undefined index: myJSON in C:\xampp\htdocs\fne\addedit.php on line 8 NULL" and also the alert "success" is also not firing up – John Jul 12 '22 at 11:08
  • @John, I have updated my answer. Please check now. It's working fine for my local – A.A Noman Jul 12 '22 at 11:48
  • same result as earlier "Notice: Undefined index: myJSON in C:\xampp\htdocs\fne\addedit.php on line 10 NULL – John Jul 12 '22 at 11:55
  • perhaps i must clear this, the variable c,g,t are the values from the table that i'm trying to pass as json – John Jul 12 '22 at 11:56
  • @John, I pass your data like your input and share the output edited answer – A.A Noman Jul 12 '22 at 12:24
  • i change data to var p = { c: 1001, g: 4, t: 100 }; still it shows NULL in output – John Jul 12 '22 at 12:52
  • @John, Please careful `ajax` code. No need two lines of code `dataType: 'json', contentType: 'application/json',` – A.A Noman Jul 12 '22 at 13:21