Amaynut
Amaynut

Reputation: 4271

Read json data in PHP sent with an Ajax call

A front-end developed is sending a array of data formated as a JSON object with an Ajax call. The json object looks like this:

{
 "name": " Test Name ",
 "image_url": "test URL",
 "include": [
  "1"
 ],
 "dimension": [
  null
 ],
 "media_type": [
  null
 ],
 "match": [
  "1"
 ],
 "content": [
  "test content"
 ],
 "sorting": {
  "rating": "50",
  "language": "50",
  "CS Weight": "50",
 }
}

How I can read it in my PHP controller. Can I just get it just this way:

$data = $_POST;

Because the variable that contains the JSON object in this case has no name, I cannot get it this way

$data = $_POST['data']

Edited Part


From the front-end, the data is sent this way:

 sendAjax: function(value, url, callback){
            xhr = $.ajax({
                type: 'POST',
                url: url,
                data: value
            }).done(function(message){
                callback(message);
            }).fail(function(jqXHR, textStatus){
                console.log('failed to submit form, error type: '+textStatus);
            });
        }

Upvotes: 0

Views: 619

Answers (2)

Camway
Camway

Reputation: 1062

This should work assuming you're using jquery on your front end. Just paste this into your javascript console and run it (make sure you replace the path with your web address. The parameters should come through correctly.

data = {
 "name": " Test Name ",
 "image_url": "test URL",
 "include": [
  "1"
 ],
 "dimension": [
  null
 ],
 "media_type": [
  null
 ],
 "match": [
  "1"
 ],
 "content": [
  "test content"
 ],
 "sorting": {
  "rating": "50",
  "language": "50",
  "CS Weight": "50",
 }
}

$.ajax({url:'/YOUR/PATH/HERE', data: {data: data}, type: 'post', dataType: 'json'})

Occurred to me after posting, are you asking how do you parse the JSON once received or how to get it to show in the $_POST hash?

Upvotes: 0

Marc B
Marc B

Reputation: 360602

Read it from the script's input, which is where you can get the "raw" POST data:

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

Upvotes: 1

Related Questions