Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I get my JSON Data posted using AJAX in my PHP file?

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?

like image 961
Noel Delos Santos Perez Avatar asked Nov 27 '11 12:11

Noel Delos Santos Perez


2 Answers

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"];
like image 175
flesk Avatar answered Nov 10 '22 16:11

flesk


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'}
like image 30
ek_ny Avatar answered Nov 10 '22 16:11

ek_ny