Json对象从PHP返回json_encode(),但在我的javascript中无效的json对象

Json对象从PHP返回json_encode(),但在我的javascript中无效的json对象

问题描述:

I echo a simple associative array read from a mySQL table back to my jquery b.m.o the json_encode($array) method. However, my .ajax call fails back in the jquery and it seems due to the object not being a valid json object. I did some debugging in chrome and under the network tab verified the response preview- does indeed look to be in perfect json format:

{"UserName":"DehanL","UserPassword":"admin","UserEmail":"dehan@rocketmail.com"}

Here is my php:

<html>
<body>

<?php



$servername = "localhost";
$username = "root";
$password = "";
$dbName ="dbPodiumPro";

$inUsername = $_POST["name"];
$inPassword = $_POST["password"];


// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//Use the dbPodiumPro
mysqli_select_db($conn,"dbPodiumPro");


$sql = "SELECT * FROM users WHERE UserName='$inUsername' AND UserPassword ='$inPassword' ";

$result = mysqli_query($conn,$sql);

// Fetch one row
$row=mysqli_fetch_assoc($result);

//Check to see if the username and password combo exists
if(!empty($row['UserName']) AND !empty($row['UserPassword'])) 
    { 

    //$_SESSION['UserName'] = $row['UserPassword']; 
    //echo $_SESSION; 

    echo json_encode($row);

    } 

else { echo "Be gone imposter!"; }


$conn->close();


?>

</body>
</html>

Then the jquery:

$.ajax({
        type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url: 'php/loginrequest.php', // the url where we want to POST
        data: formData, // our data object
        dataType: 'json' // what type of data do we expect back from the server

    })
    // using the done promise callback
    .done(function (data) {
        console.log("ajax done callback");
    })
    .fail(function (data) {
        console.log(data, "ajax failed callback");

        var IS_JSON = true;
        try {
            var json = $.parseJSON(data);
        } catch (err) {
            IS_JSON = false;
        }
        console.log(IS_JSON);
    });

Your PHP starts like this:

<html>
<body>

Whatever else it outputs after that, it isn't going to be valid JSON.

I did some debugging in chrome and under the network tab verified the response preview

Look at the raw preview. You seem to be looking at the rendered HTML preview.

You don't need to parseJSON when you have added dataType as JSON option in the AJAX.

The data you are getting after ajax is completed is already in JSON format.

"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

Docs: http://api.jquery.com/jQuery.ajax/

The data inside fail method is not what you've passed from server. It is the information related to the request.

If you are encoding your password using MD5 and the likes, Json will not encode you can choose to unset the password from you your array or define the column you want to select from your database excluding password column.

Change your ajax as

$.ajax({
        type:"POST",
        url: 'php/loginrequest.php',
        data:$("#form_id").serialize(),
        dataType:"json",
        success: function(data)
        {
            alert(data.UserName);
        }
    });

you can use both data:formData or data:$("#form_id").serialize(),

if you are getting alert message then everything is working fine