Toosick
Toosick

Reputation: 470

JSON encode PHP AJAX jQuery response error

I am having a problem with getting back the response from my PHP code. The JavaScript file says the JSON object is of length 0.

Here is my returned JSON from my getalbums.php script:

[
  {
    "album_id": "50ab2c3db9396",
    "username": "tusik",
    "title": "testalbum",
    "cover_photo_url": "http:\/\/s3.amazonaws.com\/Looking_Glass_Images\/tusik_testalbum_testpic.jpeg"
  },
  {
    "album_id": "50ab3b75a46fe",
    "username": "tusik",
    "title": "test",
    "cover_photo_url": "http:\/\/s3.amazonaws.com\/Looking_Glass_Images\/tusik_test_test.png"
  }
]

getalbums.php

<?php

session_start();
include("db.php");

$albumsArray = array();

$username = $_GET['uid'];
//Preventing MySQL injection
$username = stripslashes($username);
$username = mysql_real_escape_string($username);

$sql = "SELECT album_id,username,title,cover_photo_url FROM albums WHERE   albums.username='$username'";
$result = mysql_query($sql) or die(mysql_error());

echo $count;

while ($row = mysql_fetch_object($result)) {

    $albumsArray[] = $row;
}

echo json_encode( $albumsArray );
?>

If I type /getalbums.php?uid=tusik I get the JSON from above so I know that page works.


albums.js

$.urlParam = function(name){
var results = new RegExp('[\\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
return results[1] || 0;
}

var username = $.urlParam('uid');

var data = "uid=" + username;    
$.ajax({
  type: "GET",
  url: "getalbums.php",
  data: data,
  dataType: "json",
  processData: false
}).done(function(data) {
    //Do work

}).fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

The code gives me this error.

TypeError: Cannot read property 'album_id' of undefined

Can anybody see what I am doing wrong?

Edit: Fixed my problem jeroen's suggestion was partially right. {'uid':username} should of read {"uid":username}.

Upvotes: 2

Views: 7925

Answers (3)

Dipak Patil
Dipak Patil

Reputation: 93

Can you try simple eval() function. Click here if you want more details about JSON and eval().

var test = eval("(" + data + ")"); OR var test = eval(data);

I have already tried this in my lots of application and this is working fine for me.

Upvotes: -2

jeroen
jeroen

Reputation: 91734

You need to send both the key and the value to the server in you ajax call:

$.ajax({
  type: "GET",
  url: "getalbums.php",
  data: {'uid': username},    // here
  dataType: "json",
  processData: false
}).done(function(data) {

You were just sending the data without a key, so that is why $_GET['uid'] was empty / unset and your query returned 0 rows.

Edit: You are also invalidating your json with this line:

echo $count;

You need to make sure that only the json_encode line gets echoed / returned to the jQuery callback function so just remove it or comment it out.

Upvotes: 1

kapa
kapa

Reputation: 78671

If you set dataType: 'json', data should already contain the parsed data, not the JSON string. So calling parseJSON() is an unnecessary step - it will try to parse your (already parsed) Javascript array, which is of course not a string containing JSON, so it fails and returns null.

You can also check this on the manual page for .ajax() (emphasis mine):

dataType

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

This means you should be able to simply write:

...
}).done(function(data) {
    console.log(data[0].album_id);
})
...

Upvotes: 4

Related Questions