I am new to web services.I have the following code and when I try to run it on the local host I am not geting the required output...it shows FirstName:undefined
LastName:undefined
..
following is my code
$(document).ready(function(){
var employees = [
{ "firstName":"John" , "lastName":"Doe" }
];
$.ajax({
url: "MyService.php",
type: "POST",
data: employees,
dataType: "json",
success:function(data) {
alert("Firstname:"+data.firstName+", LastName: "+data.lastName);
},
error:function(data) {
alert('error');
} });
});
The php code is
echo json_encode($_POST);
-
1Can you show us the output of echo json_encode?Ido Green– Ido Green2012年12月12日 09:12:34 +00:00Commented Dec 12, 2012 at 9:12
-
The out put is FirstName:undefined LastName:undefinedMidhuN– MidhuN2012年12月12日 09:14:01 +00:00Commented Dec 12, 2012 at 9:14
-
1We want to see the output of the PHP echo not the alert of your javascript, this can be done by opening your console in your browser and read out the response.Rick Kuipers– Rick Kuipers2012年12月12日 09:24:53 +00:00Commented Dec 12, 2012 at 9:24
1 Answer 1
The value of data
should be an object. You are passing an array containing an object. Get rid of the array.
This:
var employees = [
{ "firstName":"John" , "lastName":"Doe" }
];
... is submitting the following to the server:
undefined=
It should be:
var employees = {
"firstName": "John",
"lastName":"Doe"
};
which would submit this:
firstName=John&lastName=Doe
Additionally, you don't appear to be specifying a Content-Type
header, so PHP is defaulting to text/html
. This is forcing you to write JavaScript that says "Don't believe the server, threat this as JSON and not HTML".
You can fix that with:
header('Content-Type: application/json');
echo json_encode($_POST);