Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return responseText from jQuery.get()

I tried to do something like this :

var msg = $.get("my_script.php");

I thought msg would be set to the text returned by my_script.php,i.e. the responseText of the jqXHR object. It apparently doesn't work like that as msg is always set to "[object XMLHttpRequest]"

Is there a quick 1 line way to do what I want?

Thanks.

like image 634
Yann Milin Avatar asked Sep 29 '11 14:09

Yann Milin


2 Answers

After some testing, I ended up finding a solution.

I need the call to be synchronous, $.get shorthand function is always asynchonous, so I will need to use $.ajax, like this:

var msg = $.ajax({type: "GET", url: "my_script.php", async: false}).responseText;

I don't think there is a better way to do this, thanks for your answers.

like image 147
Yann Milin Avatar answered Sep 22 '22 07:09

Yann Milin


You can always use:

var msg;
$.get("my_script.php", function(text) {
  msg = text;
});

If for some reason the response is text, the remote script might be changing the content-type to something like JSON, and thus jQuery tries to parse the string before outputting to you.

like image 44
Vitor M Avatar answered Sep 24 '22 07:09

Vitor M