1

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format

[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...

I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:

var channelList;

$(document).ready(function() {
    $.ajax({    
        url: 'channellookup.php',    
        dataType: "json",    

        success: function(data) {    
            console.log(data.success);    
            channelList = data;    
        }    
    });
});

However the channelList variable remains empty when inspected via console. What am I doing wrong?

g.rand
  • 25
  • 1
  • 6
  • Check the net tab from the browser console, also see the incoming response from the server –  Feb 23 '15 at 00:47
  • Are the lines in the `success` function executed at all? If so, what is the value of `data`? Also make sure to look for errors or unexpected behaviour in the network tab and the script console. – GolezTrol Feb 23 '15 at 00:48
  • Success function contents do not seem to be reached, also no network activity (would it even be listed as it is in the same directory on the machine?) – g.rand Feb 23 '15 at 00:52
  • can you add ``error: function(){console.log(arguments)}`` to the ajax request and tell us what the console reads – Dustin Poissant Feb 23 '15 at 01:06
  • With `dataType:'json',` in the ajax options it says `"Invalid JSON: – g.rand Feb 23 '15 at 01:10
  • To be more precise the first case was `Arguments { 0: XMLHttpRequest, 1: "parsererror", 2: "Invalid JSON: – g.rand Feb 23 '15 at 01:16
  • something really wrong in server code if you see ` – charlietfl Feb 23 '15 at 01:19
  • http://pastebin.com/Nd5PSfnY everything except the last part is taken from a tutorial. when executed via terminal it returns a normal json string. There is no request in the network tab – g.rand Feb 23 '15 at 01:22
  • Are you running the code on the server or on the local machine. By this I mean to ask if the URL (which you are testing) looks like http://localhost.... or D:\path_to_your_folder. – progrAmmar Feb 23 '15 at 01:57
  • local machine. the database, html/js and php file are in the same directory. – g.rand Feb 23 '15 at 02:01
  • This is probably it, right? with the PHP file local there is no middle man to actually provide the data. Sorry, I am a beginner with this. Do I need to run a webserver to be able to develop this or is there another way to do it locally? – g.rand Feb 23 '15 at 02:56

2 Answers2

0

Please ensure that your PHP echoing the correct type of content.

To echo the JSON, please add the content-type in response header.

<?php
  header(‘Content-type:text/json’);     // To ensure output json type.
  echo $your_json; 
?>
Troy Young
  • 181
  • 1
  • 12
  • Hmm, this didn't seem to change anything. Also I am using `echo json_encode($channelList);` in the php file so that should be covered, no? When I run the PHP via terminal it echos what looks to me like a json string. – g.rand Feb 23 '15 at 02:07
0

It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.

Wrap the AJAX call in a function with a callback argument. Something like this:

function getChannels(callback){  
    $.ajax({    
    url: 'channellookup.php',    
    dataType: "json",    
        success: function(data) {    
            console.log(data);    
            if (typeof(callback) === 'function') {
                callback(data);
            }    
        }, 
        error: function(data) {
            if (typeof(callback) === 'function') {
                callback(data);
            } 
        }  
   });
}  

Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.

getChannels(function(channels){
    $('.channelDiv').html(channels.name);
    $('.channelDiv2').html(channels.someOtherProperty);
});

I didn't test this, but this is how the flow should go. This SO post may be helpful.

EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

Community
  • 1
  • 1
cpk
  • 809
  • 1
  • 6
  • 20
  • Thank you, but I think you are a step further than me. I have read about the synchronicity issue before. But should my example not update the variable regardless of if it can be used in the DOM? I have put an error handler `error: function(){console.log(arguments)}` into my original ajax request as someone requested and this was the result: `Arguments { 0: XMLHttpRequest, 1: "parsererror", 2: "Invalid JSON: – g.rand Feb 23 '15 at 04:09
  • It will update the variable, but it becomes a race condition of sorts, where the DOM is being rendered before the AJAX has time to call to the server and return the data. It might help to see the php code. before you return the array try `json_encode($data)`. – cpk Feb 23 '15 at 05:22
  • Also, I see you have opened a new question asking the same thing. You should probably just update this question so people trying to help you have all the information they need to do so. – cpk Feb 23 '15 at 05:30