0

I'm trying to pass JSON data from jQuery to PHP so I can overwrite a JSON file. The problem I'm having is that I can't figure out how to tell if the PHP file is receiving my json that I am sending. I'm a bit of a novice..

I currently have this - it's not doing the trick and I'm a bit stuck. Any advice would be great. I am getting alert - 'Right' but nothing from PHP.

var testjson = [{
  "name": 1,
  "myArray": [{ 
    "0":"1",
    "2":"3"
  },{
    "1":"2",
    "3":"4"
  }],
  "friends":40  
}];

$.ajax({
  type: "POST",
  url: "php/write.php",
  data: testjson,
  dataType: "html",
  contentType : 'application/json; charset=utf-8'
}).done(function(data, status) {
  alert('Right');
}).fail(function(data, status) {
  alert("Wrong: " + status);
});
$value = json_decode($_POST);
print_r($value);
11
  • So, what do you get when you run your code? You need to tell us the issue. Commented Jul 20, 2017 at 9:49
  • try to change this dataType: "html", to dataType: 'json', Commented Jul 20, 2017 at 9:50
  • 1
    @vietnguyen09 - That setting is for what the ajax request expects back. It has no effect on what it sends. In this situation, changing it to json would most likely just make jQuery throw a "parse error", since it doesn't actually return a json string. Commented Jul 20, 2017 at 9:51
  • So what's your problem? Commented Jul 20, 2017 at 9:52
  • 1
    Oh, you're setting "contentType". Remove that from your request and PHP will get the data correctly out of the box. Then in your PHP, just do a print_r($_POST) (remove the json_decode()) Commented Jul 20, 2017 at 9:54

2 Answers 2

1

Use the below code

var testjson =[{"name":1,"myArray":[{"0":"1","2":"3"},
            {"1":"2","3":"4"}],"friends":40}];

var myString = JSON.stringify(testjson);

$.ajax({
    type: "POST",
    url: "write.php",
    data: myString,
    dataType: "html"
     }).done( function (data, status) {
    alert('Right');
})
.fail( function (data, status) {
    alert("Wrong: "+status);
});
});

And in php

$json = json_decode(file_get_contents("php://input"));
print_r($json);
Sign up to request clarification or add additional context in comments.

Comments

0

Got it.

Knew it was super simple. Thanks for your help!

$value = $_POST;
print_r($value);

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.