user2158382
user2158382

Reputation: 4510

PHP not correctly returning JSON for an AJAX call

I have a PHP function that is supposed to return a JSON object to an AJAX call, but instead it is returning a string. Here is the PHP that I am calling from an AJAX call.

<?php
  echo json_encode(array("error", 0, "Success!"));
?>

Here is the AJAX call.

    $.ajax({
        type: "POST",
        url: "../api/login.php",
        data: { id: username, password: password },
        success: function(response) {
            alert( "Data Saved: " + response );
            $("#login_username").val("");
            $("#login_password").val("");
        }
      });

When this function returns, I try to access response in the console, and this is what happens

response
> "["error",0,"Success!"]"
response[0]
> "["

Upvotes: 1

Views: 1663

Answers (3)

Shea
Shea

Reputation: 1950

Your implementation appears to be using jQuery, or some mock-up of jQuery. If it is not using jQuery, I will be happy to share more solutions to your problem.

Add dataType

 $.ajax({
        dataType: 'json',
        type: "POST",
        url: "../api/login.php",
        data: { id: username, password: password },
        success: function(response) {
            alert( "Data Saved: " + response );
            $("#login_username").val("");
            $("#login_password").val("");
        }
      });

The problem is that, by default, jQuery expects a string.

var foo = "bar";
foo[1] === "a"; // true

Documentation: jQuery.ajax

Upvotes: 2

walu
walu

Reputation: 11

add a param in your ajaxcall

$.ajax({
    type: "POST",
    url: "../api/login.php",
    data: { id: username, password: password },

    dataType: "json" //-< add this param.

    success: function(response) {
        alert( "Data Saved: " + response );
        $("#login_username").val("");
        $("#login_password").val("");
    }
  });

http://api.jquery.com/jQuery.post/

Upvotes: 1

PSL
PSL

Reputation: 123739

If you are expecting an object then specify the dataType:json in the ajax settings. It will also ensure that if there are any invalid JSON being sent from the server, it gets erred out with parse error. Most probably you don't have a content-type (application/json; charset=utf-8) specified in your response header which lets jquery to determine the mime type itself, so specify the dataType ensure that you get an object or an error back(incase of invalid JSON).

  $.ajax({
    type: "POST",
    dataType:'json'
    url: "../api/login.php",
    data: { id: username, password: password },
    success: function(response) {
        alert( "Data Saved: " + response );
        $("#login_username").val("");
        $("#login_password").val("");
    }
  });

Upvotes: 4

Related Questions