$ .jquery ajax returned data (json) is displayed as 'undefined'

Here I have a simple php script that displays some values ​​from a database in json format.

$source = $_GET['source']; $query = mysql_query("SELECT * FROM images WHERE big_thumb = '" . $source . "'"); $results = array(); while($row = mysql_fetch_array($query)) { $results[] = array( 'title' => $row['title'], 'date' => $row['upload_date'], 'time' => $row['upload_time'] ); } $json = json_encode($results); echo $json; 

This shows that this is an example output:

 [{"title":"Torus","date":"2012-04-04","time":"23:06:14"}] 

Then, when the image is clicked, this jquery is called:

 var image_src = $(this).attr("alt"); // <= This works fine $.ajax({ url: 'inc/get_image_details.php', data: {source : image_src}, dataType: "json", success: function(data) { title = data.title; alert(title); date = data.date; alert(date); time = data.time; alert(time); } }); 

However, variables (name, date and time) are displayed as "undefined" in the warning field. I tried several ways to implement ajax call, and the same thing happens every time. I tried this for the first time, but I cannot understand.

+6
source share
1 answer

Your json string is in array format. You need to access json object properties like this

 title = data[0].title; alert(title); date = data[0].date; alert(date); time = data[0].time; alert(time); 

If you control the json format and the array is not needed, use a json object with this format.

 {"title":"Torus","date":"2012-04-04","time":"23:06:14"} 

In this case, you can save your code as it is now.

+21
source

Source: https://habr.com/ru/post/912617/


All Articles