0

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.

here is the jquery code::

list_choice = "A";
content_choice = "Artists";             //globals to store default value

$(document).ready(function() {
$('.list-nav > a').click(function() {
    var ltext = $(this).text();
    list_choice = ltext;
    console.log(ltext+" <------>    ");        
    $.ajax({            
        url: 'retrieveFileFront.php',
        data: {type: content_choice, navtext: list_choice},
        type: 'POST',
        dataType: 'json',            
        complete: function(data) {                
            console.log(data['message']['Album_Name']);          
        }
    });
    return false;
});

});

i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.

here is the retrieveFileFront.php:

<?php

require './retrieveFiles.php';

$type = $_POST['type'];
$nav_text = $_POST['navtext'];

$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
    $data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
    echo json_encode($data);

} else {
    echo json_encode($data);
}

?>

and here is the /retrieveFiles.php

<?php

class retrieveFiles {        
    public $content_type;
    public $list_nav;
    public $connection;
    public $result;
    public $result_obj;
    public $tags_array;
    public $query;
    public $row;

    public function __construct($type, $nav_text) {            
        $this->content_type = $type;
        $this->list_nav = $nav_text;     
    }

    public function retFiles() {

        @$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
        if(!$this->connection) {
            die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
        }

        if ($this->content_type == "Artists") {                

            $this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";               

            try {
                $this->result = $this->connection->query($this->query);
                $this->row = $this->result->fetch_row();

                if (isset($this->row[0]) && isset($this->row[1])) {
                    $this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));

                    return $this->tags_array;
                }

        }   catch (Exception $e) {                
                echo 'Sorry an Error has occurred'.$e;
                return false;
            }
        }
   }

}

?>

I'm getting a 200 response in console in firebug, which indicates that its running okay.

<!DOCTYPE HTML>

{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}

Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.

Thanks in advance..

7
  • Are you prefixing a <!DOCTYPE HTML> to your JSON response? Commented Jul 3, 2013 at 14:16
  • 3
    1. you should no have that HTML doctype in your JSON response; 2. you should not print local paths to files, but URLs. Commented Jul 3, 2013 at 14:17
  • The response is sent as a string, not a Javascript object. See my answer below. Commented Jul 3, 2013 at 14:23
  • I didn't see you set dataType. You may want to create an error: function that lets you know if something went wrong. And if you're getting 200 OK, the success: should work. As I stated down below, you could try setting dataType to 'text' and alert(data) on success just to see what is coming back. Commented Jul 3, 2013 at 14:32
  • @techfoobar no the json is made with this nested associative array::$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1])); Commented Jul 5, 2013 at 2:07

4 Answers 4

1

JSON encoded data is usually not sent like

data['message']['Album_Name']);

But rather like:

data.message.Album_Name;

You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.

Sign up to request clarification or add additional context in comments.

8 Comments

That's not how you send JSON data - that how you access a JS object [which could have been deserialized from a JSON string, but that's totally unrelated].
Well it kinda is; after encoding it it looks more like { "message": { "Album_Name": "..." } }, which would make it objects and not associative arrays (Although in Javascript these are practically the same, but that's a whole different discussion.)
Bracket notation and dot notation are just two different ways to access same data, bracket one being useful if you want to provide a dynamic key for example.
What's your point? JSON encoded data are sent as Javascript Objects, not associative arrays; which is how he is trying to treat his data. data['message']; no longer exists as it did in PHP, but data.message does.
I see what you mean! I didn't know you could also call your objects like they were arrays. Javascript is one weird language. Thanks for the lesson!
|
1

You need to parse the json response using

data = $.parseJSON(data)

4 Comments

Not necessary if he specified dataType: JSON in the ajax req.
Wow, my bad. Apparently I skipped over that one. I would imagine something is getting echo'd that the OP doesn't want. Might be worthwhile to set dataType to text and alert(data) to see what is coming back.
@MichaelWheeler i did parsed it using $.parseJSON before posting my question, but it didn't helped. Like i said i've spent more than 10 hours on this problem, trying out various workarounds but none worked.
@MichaelWheeler on setting dataType to 'text' alert(data) gives [object Object] and console.log(data) give :: Object { readyState=4, responseText="<!DOCTYPE HTML>\n\n<!DOCT...tcleaner\/folder.jpg"}}", status=200, more...}
1

Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse

6 Comments

on doing var res = $.parseJSON(data) and alert(res) i get this:: SyntaxError: JSON.parse: unexpected character [Break On This Error] return window.JSON.parse( data ); in the console panel
use var res = JSON.parse(data); directly
this is what i get SyntaxError: JSON.parse: unexpected character [Break On This Error] var def = JSON.parse(data);
than alert you data that you get on response and i am sure your getting some error in response....
alert(data) gives [object Object]
|
0

well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually. Here is the working code

list_choice = "A";
content_choice = "Artists";             //globals to store default value

$(document).ready(function() {
$('.list-nav > a').click(function() {
    var ltext = $(this).text();
    list_choice = ltext;
    console.log(ltext+" <------>    ");

    $('#loading').css('visibility', 'visible');

    $.ajax({
        url: 'retrieveFileFront.php',
        data: {type: content_choice, navtext: list_choice},
        type: 'POST'
        dataType: 'json',
        complete: function(data) {

            var res = data.responseText;
            res = res.replace(/<!DOCTYPE HTML>/g, "");
            res = res.trim();

            console.log(res);
            var arr = JSON.parse("[" + res +"]");    //needed to parse JSON object into arrays
            console.log(arr[0].message.Album_Name);
            console.log(arr[0].message.Album_Art);               

            $('#loading').css('visibility','hidden');
        }
    });
    return false;

});

This works fine and gives the desired response. Anyways thanks for the help, guys.

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.