user3371398
user3371398

Reputation: 477

Jquery returns json as string

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.

Upvotes: 1

Views: 61

Answers (1)

Quentin
Quentin

Reputation: 944434

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.

Upvotes: 4

Related Questions