2

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}.

2
  • 4
    Why don't you first check what data contains? Perhaps php echoed out a warning or error. Commented Nov 20, 2012 at 18:07
  • When I print data to the screen it says [] Commented Nov 20, 2012 at 18:51

3 Answers 3

4

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

5 Comments

So what is the proper way to return the album_id in the json object? Sorry I am very new to javascript.
@PrestonTighe Updated my answer. If you try to write data itself on the console, you will see that it is already parsed.
I have tried something of this nature and it gives me an error. The error is: TypeError: Cannot read property 'album_id' of undefined. When I try to print with console.log(data); it gives me an object where the album property is of length 0.
@PrestonTighe Use the Network tab of your inspector (I use the built-in Chrome Inspector) to analyze what data is coming back from the server. The response must be valid JSON.
When I do this and look at the response tab. The response is blank.
1

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.

9 Comments

Ok well If I had 15 rep I would up vote this. Thank you so much for the help but I still have a problem. The returned data is of length 0 still. Any solutions?
Ok that was from my debuging but it didn't effect anything since it was null in the first place. How do I get this line to work?console.log(data[0].album_id); The data is still coming back with length 0.
@Preston Tighe Does the php script work for a normal request?
Yes I tried it with $albumsArray = array( "album" => ""); then I set album to something then echoed it. I could pull the album key from the albums.js file. And like I said /getalbums.php?uid=tusik works too.
@bažmegakapa That's what I thought so the comment of the OP did not make a lot of sense to me...
|
-2

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.

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.