jquery ajax get responsetext from http url
Asked Answered
P

10

30

Neither:

var response = $.ajax({
    type: "GET",   
    url: "http://www.google.de",   
    async: false,
    success : function() {
        alert (this);
    }
});

Nor:

var response2 = $.get("http://www.google.de", function(data) {
    alert("Data Loaded: " + data);
});

give me an object. How do I get access to the responseText?

Prebendary answered 20/7, 2009 at 9:58 Comment(0)
F
37

You simply must rewrite it like that:

var response = '';
$.ajax({ type: "GET",   
         url: "http://www.google.de",   
         async: false,
         success : function(text)
         {
             response = text;
         }
});

alert(response);
Fasto answered 20/7, 2009 at 11:5 Comment(6)
it is empty -> no response - but why?Prebendary
@all - cross domain ajax doesn't work unless the domain has jsonp enabled - which google does notMoneybags
Even with jsonp compatible API, this does not work, because it seems that jQuery don't want to do sync ajax request to other domain... So the request is async. That's really, really boring... :-/Exoteric
That is no better, the only difference is where you alert the user to the value of the variable. Also, the second option OP listed used $.get which is async by default. If he used your logic with the alert outside the event handler, it would always return '' whether the request was successful or not.Sheers
This isn't even correct jsonp syntax. In order for jQuery to use JSONP, it expects a callback parameter in the url, which this example doesn't have.Anabolite
response will be empty if you remove async: false which is what you are meant to be correcting.....Derzon
M
30

As Karim said, cross domain ajax doesn't work unless the server allows for it. In this case Google does not, BUT, there is a simple trick to get around this in many cases. Just have your local server pass the content retrieved through HTTP or HTTPS.

For example, if you were using PHP, you could:

Create the file web_root/ajax_responders/google.php with:

<?php
  echo file_get_contents('http://www.google.de');
?>

And then alter your code to connect to that instead of to Google's domain directly in the javascript:

var response = $.ajax({ type: "GET",   
                        url: "/ajax_responders/google.php",   
                        async: false
                      }).responseText;
alert(response);
Mannose answered 23/10, 2011 at 1:40 Comment(0)
H
4

First you have to download a JQuery plugin to allow Cross-domain requests. Download it here: https://github.com/padolsey/jQuery-Plugins/downloads

Import the file called query.xdomainsajax.js into your project and include it with this code:

<script type="text/javascript" src="/path/to/the/file/jquery.xdomainajax.js"></script>

To get the html of an external web page in text form you can write this:

$.ajax({
    url: "http://www.website.com",
    type: 'GET',
    success: function(res) {
        var text = res.responseText;
        // then you can manipulate your text as you wish
    }
});
Hardfavored answered 7/12, 2011 at 15:5 Comment(1)
Totally unrelated to this question, but I thought you might find this JSFiddle interesting. It's related to the question you posted yesterday.Snuffer
G
3

in jquery ajax functions, the success callback signature is:

function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}

depending on the data type you've asked, using the 'dataType' parameter, you'll get the 'data' argument.

from the docs:

dataType (String) Default: Intelligent Guess (xml or html). The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response.

The available types (and the result passed as the first argument to your success callback) are:

"xml": Returns a XML document that can be processed via jQuery.

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.

"json": Evaluates the response as JSON and returns a JavaScript Object.

"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)

"text": A plain text string.

see http://docs.jquery.com/Ajax/jQuery.ajax#options

Gilmour answered 20/7, 2009 at 10:13 Comment(1)
see first other comment - response is empty -> no googleHtml text?! as response :-/Prebendary
A
2

The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).

And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)

Adolpho answered 6/8, 2010 at 8:20 Comment(0)
I
1

Actually, you can make cross domain requests with i.e. Firefox, se this for a overview: http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3

Webkit and IE8 supports it as well in some fashion.

Incommodious answered 6/8, 2010 at 8:37 Comment(0)
L
0

Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.

Suppose a PHP file responder.php has these contents:

$url = "https://www.google.com";
$ch      = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;

Your AJAX request should be to this responder.php file so that it executes the cross-domain request.

Loran answered 19/4, 2015 at 12:33 Comment(0)
G
0

How about this?

$.get(some-url, some-data, function(d, s, x){
    // d is text response data
    // s is text status
    // x is a XMLHttpRequest object
    // so... you can code like that:

    console.log(x.responseText);
})

Enjoy! :)

Geffner answered 28/7, 2021 at 21:3 Comment(0)
G
-1

This is super old, but hopefully this helps somebody. I'm sending responses with different error codes back and this is the only solution I've found that works in

$.ajax({
    data: {
        "data": "mydata"
    },
    type: "POST",
    url: "myurl"
}).done(function(data){
    alert(data);
}).fail(function(data){
    alert(data.responseText)
});

Since JQuery deprecated the success and error functions, it's you need to use done and fail, and access the data with data.responseText when in fail, and just with data when in done.

Gordon answered 14/7, 2018 at 17:57 Comment(0)
P
-2

try this

alert( data['responseText'] );
Piccoloist answered 13/8, 2016 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.