1

I am sending json object from PHP to Jquery ajax

I am able to receive json data but in string format instead of object.

PHP code

$userdata=json_encode(array("FirstName"=> $fName,"LastName"=>$lName,"PhoneNumber"=>$phone,"EmailId"=> $email,"Balance"=>$balance));
echo $userdata;

Javascript

$(document).ready(function(){
  alert();
  $.ajax({
    type:"post",
    url:"viewprofile.php",
    contentType: "json",
    data:{"somedata":"anydata"},
    success:function(response) {
      alert(response);
      $.each(response, function(key, value) {
        alert(key + ' ' + value);
      });
    }, 
    error: function (xhr, ajaxOptions, thrownError) {
      alert("error : "+xhr.status+" "+thrownError);     
    }
  });
});

I am getting entire json in first alert of success function

But when i iterate over json it returns index and value from a string.

For Example  

in first alert output is {"fname":"abc","lname":"def"}

during iteration output is

0 {  
1 "  
2 f  
3 n  
4 a  
5 m  
.......so on  

Am i wrong any where,Please help.

1 Answer 1

4

PHP, by default, declares that its output is HTML. Consequently, you are processing data as a string of (invalid) HTML.

Add:

header("Content-Type: application/json");

Also remove contentType: "json", from the JavaScript. That is not a valid content-type, and you aren't encoding the data you are POSTing as JSON.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.