views:

40

answers:

2

I have an ajax call in the head section of my index.html

$(function() {
  alert("Hello, World!");
  $.ajax({
    method: 'get',
    url : 'php/getRecord.php?color=red',
    dataType: "json",
    success: function (data) { 
        alert(data); 
    }  
  });
});

For some reason, that alert(data) never gets called but the "Hello, World!" gets called. Am I doing something wrong? The PHP file does give me data when testing it directly.

+3  A: 

You're probably getting an error somewhere.

Check the HTTP request in Firebug or Fiddler and make sure that it's doing what you expect.

Add an error: handler and see whether it gets fired.

SLaks
@SLaks: Added that as , `error: function(e) { alert(e); }` and it shows [object XMLHttpRequest] :|
Legend
@Legend - Instead of `alert(e)`, do a `console.log(e)` and inspect the error object in the console. Or step through code with a debugger.
Anurag
@Legend: Add `, error: console.log`.
SLaks
@Anurag: Doing that now... :) Shows parsererror and undefined. Precisely: XMLHttpRequest { readyState=4, more...} parsererror undefined
Legend
+1 to using a http sniffer like Fiddler to see what's actually being returned from the server.
great_llama
There was a comma missing from my JSON return data :) Thanks a lot for the help...
Legend
**You should use a PHP JSON library**. Don't concatenate it yourself.
SLaks
@SLaks: Point taken. Thanks for the suggestion.
Legend
Pick whatever function will do the job. (I don't know PHP)
SLaks
@SLaks: Sure. Using something that came up in Google :) Thanks again.
Legend
+2  A: 

Have you tried defining an error callback to see if there's a problem?

,error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert(textStatus);
}
great_llama
Ok, so it throws a parser error. I just moved the function from inside a plugin to directly inside index.html and it throws this error. Guess something went wrong somewhere.
Legend
@great_llama: Thanks for the pointers.
Legend