1

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?

3
  • Try adding contentType : "application/json" property to options of jquery .ajax to force the response encoding. Commented Nov 28, 2014 at 21:31
  • Enable error_reporting. Commented Nov 28, 2014 at 21:33
  • contentType : "application/json" for this still get same result Commented Nov 28, 2014 at 21:39

2 Answers 2

4

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()));
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.