views:

115

answers:

8
$.get("http://localhost/test.php", (function(data){
    alert(data);
}))

The alert is empty. I'm new to this, and I can't see what I'm doing wrong. Help?

A: 

The callback function should be the third parameter to $.get:

 $.get("http://localhost/test.php", {}, (function(data){
     alert(data);
 }))
dionyziz
That does not matter. You can pass the callback as second parameter.
Felix Kling
It doesn't need to be. http://api.jquery.com/jQuery.get/
Andy_Vulhop
A: 

If you type http://locahost/test.php in your browser, do you get any data back?

There is no difference whether jquery gets the url or you do, the result should be the same.

James Connell
A: 

Does test.php actually output something?

This works for me.

DGM
+2  A: 

Perhaps you're not telling the code to run? Try putting it in $(document).ready() with

$(function() {
  $.get("http://localhost/test.php", function(data){
    alert(data);
  });
});

http://api.jquery.com/ready/

sidewaysmilk
A: 

It's basic, just checking....Do you included jquery.js?

Topera
Yep, I did. (filler to exceed 15 chars)
Dataflashsabot
A: 

What is the mime-type of the response?

The doc says

The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.

So depending on the datatype of the data parameter to your callback, the alert may be trying to show you an object that doesn't translate readily to a string.

LarsH
A: 

Okay, solved it: Works when the html file is in the webserver dir and called from localhost, doesn't work when the html is file://. This is inconvenient, but oh well. (it seems I can't mark my own answer as the solution until 2 days.)

Dataflashsabot
read: http://stackoverflow.com/questions/3533934/jquery-why-wont-this-work/3534366#3534366 which is a real answer
Sirber
+2  A: 

It does work with a file:// URL but not http://? I smell same origin policy.

Are you opening the file with the jQuery in your browser via a file:// URL then trying to fetch via http://? Because your protocol and host have to match when you do Ajax.

Make sure that you're opening the file in your browser as http://localhost/index.php and not file://localhost/index.php. Then you should be able to fetch that file via http://localhost/test.php.

sidewaysmilk
Thanks! That makes sense from a security viewpoint.
Dataflashsabot