0

I am using the following jquery ajax call:

$(document).ready(function () {
    submitAct();

function submitAct(){
    var alldata = [];
    alldata.push( {
        "pid": 'd2a7d886-6821-3eaa-079f-fbe278c6a16a',
        "title": 'Fun with Gophers',
    });

    $.ajax({
        dataType: "jsonp",
        type: 'POST',
        url: '//[server path]/act',
        data: "data=" + JSON.stringify(alldata),
    });
}
});

On the server, the result of $_POST[data] is showing as:

[{"pid":"d2a7d886-6821-3eaa-079f-fbe278c6a16a","title":"Fun with Gophers"}]

I am having trouble accessing the keys and related values of 'pid' and 'title'. Would someone please provide some insight? I've tried things like below but haven't had any success:

$_POST['title']

$data = json_decode( $_POST['data']);
$data->title

Thanks!

2
  • 1
    What's the output of var_dump($data)? Commented Nov 10, 2013 at 20:56
  • var_dump($data) is empty. Could it be losing values in the json_decode method? Commented Nov 10, 2013 at 21:00

3 Answers 3

2

Several suggestions:

First you are enclosing the data object in an array, needlessly. To access it now:

$data = json_decode( $_POST['data']);
$data=$data[0];/* access object in array*/
$data->title;

The default content type for $.ajax is application/x-www-form-urlencoded; charset=UTF-8...exactly the same as sending a regular form. Think of each key in your data object as you would name of a form control.

There is no need to JSON.stringify to send. jQuery will serialize objects and arrays for you

You can simply send it like this:

var alldata = {
    "pid": 'd2a7d886-6821-3eaa-079f-fbe278c6a16a',
    "title": 'Fun with Gophers',
};
$.ajax({
    dataType: "jsonp",
    type: 'POST',
    url: '//[server path]/act',
    data: alldata 
});

Then in php:

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

1 Comment

Yes, much simpler :) Thank you again.
0
$a = json_decode($_POST['data']);
print_r($a[0]->pid);

Comments

0

Change the data part of the ajax request to the following:

$.ajax({
    dataType: "jsonp",
    type: 'POST',
    url: '//[server path]/act',
    data: {"data": JSON.stringify(alldata)},
});

Now you can access the sent content via $_POST["data"] in the appropriate php file.

Example:

$json = json_decode($_POST["data"]);
var_dump($json[0]->{"title"}); // [0] because of the array

2 Comments

Thanks. That is giving a blank value. It has a value while in the &_POST variable, but maybe is losing it after the json_decode?
@user2977016 change the data part of your ajax request to the one in my updated answer and try the given example

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.