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);
The value of
datashould be an object. You are passing an array containing an object. Get rid of the array.This:
… is submitting the following to the server:
It should be:
which would submit this:
Additionally, you don’t appear to be specifying a
Content-Typeheader, so PHP is defaulting totext/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: