console.log not printing the response

I have a function that calls another function over the server and returns a string back which i want to be printed in the browser's log windows, The function looks like:

function getErrorInfo() {
    setTimeout(function () {
        $.getJSON('Get/ErrorInfo', function (responseText) {
            console.log("Log: "+responseText);
        });
    }, 5000);
}
getErrorInfo();

The function on the server sides does gets hits and returns a valid string But nothing is being displayed in the browser's windows Moreover the function on the server side must get hit after every 5 secs. but it only gets his on time and not again.

Please explain what am i doing wrong here.

Answers


When using $.getJSON(), the return result is required to be a valid JSON string, meaning it needs to be parsable into an object or array. In this situation, you can probably simply use $.get(), which will autodetect the return data type, or use $.ajax() and set the dataType: plain if you want to skip the JSON requirement.

On the second issue of keeping the log running, you can call getErrorInfo() from inside the setTimeout() or the callback, and it will keep running:

function getErrorInfo() {
    setTimeout(function () {
        $.getJSON('/echo/json/', function (responseText) {
            console.log("Log: "+responseText);

            getErrorInfo();
        });
    }, 5000);
}
getErrorInfo();

http://jsfiddle.net/Er5Lg/

In my opinion, in this situation, it is better than setInterval(), since that can get backed up and end up overriding calls, and the errors might display out of order.


Your basic issue is that you need to have properly formatted JSON in order to get back any result. Your result (per above) is:

3/8/2014 5:27:16 PMSystem.NullReferenceException: Object reference not set to an instance of an object. at movie.Models.Genre.GetPosts(Int32 min)

Not only is this an exception text, but it isn't valid JSON. JSON format is fully described here. Rather than calling a real service, I would recommend starting by just getting a static JSON file from the server. Then you know the data is correct.

Side Note: The other issue here is how you print the OBJECT result from getJSON. When you try to print an object using "Console.log" it converts it to a string, which isn't probably going to show what you want. You should probably change your log statement to:

console.log(responseText);

In chrome at least, the console window will let you browse the contents of the object which can be really helpful. Between the note and the solution above I think you should have it. Best of luck!


Need Your Help

Value radio boxes to input text with javascript

javascript input radio-button

i try to get the value from a radio box in a input box

Using PHP retrieved variables in Javascript

php javascript google-maps

I will use the following javascript to display a Google Map Window in a webpage.