0

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);
j0k
22.8k28 gold badges81 silver badges90 bronze badges
asked Dec 12, 2012 at 9:09
3
  • 1
    Can you show us the output of echo json_encode? Commented Dec 12, 2012 at 9:12
  • The out put is FirstName:undefined LastName:undefined Commented Dec 12, 2012 at 9:14
  • 1
    We 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. Commented Dec 12, 2012 at 9:24

1 Answer 1

2

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);
answered Dec 12, 2012 at 9:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.