Reputation: 163
I have an AJAX script that post data in one of my PHP file:
var _lname = $('#ptLastName').val();
var _fname = $('#ptFirstName').val();
var _mname = $('#ptMiddleName').val();
$.ajax({
type: "POST",
url: ".././CheckPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var res = response.d;
if (res == true) {
jAlert('Person Name already exists!', 'Error');
return;
}
It works fine and I can see the JSON Data posted in the Firebug console. The problem is with this PHP code:
$firstname = json_decode($_POST['firstName']);
$lastname = json_decode($_POST['lastName']);
$middlename = json_decode($_POST['middleName']);
$response = array();
The above PHP code seems that it can't recognize the 'firstName'
,'lastName'
, and 'middleName'
as a posted JSON parameter, and return an Undefined index: firstName in C:...
something like that for all the posted parameters.
I also tried using $data = $_POST['data']
and $_REQUEST['data']
to get all the JSON parameters and decode it using json_decode($data);
but didn't work.
I've also used the AJAX shortened code for post $.post('.././CheckPerson.php', {data: dataString}, function(res){ });
, it works great with my PHP file and my PHP file can now read lastName
, firstName
, and middleName
, but i think it is not a JSON data but only a text data because firebug can't read it as JSON data. Now,i'm confused how will my PHP file read the JSON data parameters.Do you guys have any suggestions about this?
Upvotes: 5
Views: 4669
Reputation: 7579
The problem is that dataType: "json"
doesn't mean that you're posting json, but that you're expecting to receive json data from the server as a result of your request. You could change your post data to:
data: {myPostData : "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}"}
and then parse it on your server like
$myPostData = json_decode($_POST['myPostData']);
$firstname = $myPostData["firstName"];
$lastname = $myPostData["lastName"];
$middlename = $myPostData["middleName"];
Upvotes: 7
Reputation: 10243
One issue- you're using single quotes for your json. You should be using double quotes (according to spec).
{"lastName":"Smith", "firstName":"Joe"}
instead of
{'lastName':'Smith', 'firstName':'Joe'}
Upvotes: 2