简体   繁体   中英

PHP json_encode function is not working on ajax call

In page load I am calling this function

function myFunction(selectedCinemaID) {    
    $.ajax({
        type: "POST",
        url: "show_details.php",
        data: {cinema_id: selectedCinemaID }
    }).done(function( show_list ) {
        console.log(show_list.length);

    });

And my code in show_details.php

$query = "SELECT * FROM `show` WHERE cinema_id=2;";
    $result = mysql_query($query);

    if($result){
        $show_list = array();
    while($row = mysql_fetch_array($result)){
        array_push ($show_list, array($row['id'], $row['cinema_id'], row['show_time']));   
    }
    echo json_encode($show_list);        
    } else {
        echo mysql_error();
    }

In my database I have only two row and three column but the length showed in the console is 64. But according to the database length should be 2. console.log(show_list) output [["2","2","2014-11-01 01:00:00"],["3","2","2014-11-01 04:00:00"]] but it seems everything here is treated as an array element or string. What is wrong in this code?

You haven't told jquery that you're sending JSON. As such, it'll treat the json text that the server is sending as text. That means

    console.log(show_list.length);

is outputting the length of the json string, not the count/size of the array you're building in PHP.

You need either

$.getJSON(....);

or

$.ajax( 
    dataType: 'json'
    ...
)

However, note that if your mysql query fails for any reason, then outputting the mysql error message as your are will cause an error in jquery - it'll be expecting JSON, and you could potentially be sending it a mysql error message, which is definitely NOT json.

Once you switch to JSON mode, you should never send anything OTHER than json:

if (query ...)
    output json results
} else {
    echo json_encode(array('error' => mysql_error()));
}

The JavaScript function .length is counting the length of the entire serialized array string. You need to parse it first:

.done(function( show_list ) {
    var data = JSON && JSON.parse( show_list ) || $.parseJSON( show_list );
    console.log( data.length );
});

Thanks,

Andrew

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM