Abs
Abs

Reputation: 57926

JQuery AJAX Post Request keeps failing with absolute URL

I am trying to test an API via AJAX. I have used JQuery:

$(document).ready(function(){

    $('#ajax').click(function(e){

        var sampleHTML = '<html></html>';

        var api_key = 'asfasasfs2';        

        $.post('http://google.com/', { api_key: api_key, html: sampleHTML },

           function(data) {

             alert("Data Loaded: " + data);

        });

    });

});

When ever I use an absolute URL, which I need to as this is an external API, firebug shows me nothing. As if no post request was made!

I thought I would test it on chrome and it shows the status as cancelled and the type as pending. What does this mean?

Please note, I've put Google's URL to hide my API URL.

Upvotes: 1

Views: 9069

Answers (2)

jk.
jk.

Reputation: 14435

See the jquery documentation. If the url is not on the same domain, it won't work:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

You could try an ajax post with script or jsonp as the return data if you can adjust your api:

Script and JSONP requests are not subject to the same origin policy restrictions.

Upvotes: 5

Kishore
Kishore

Reputation: 1912

Try this

$(document).ready(function(){

    $('#ajax').live("click", function(e){


            $.ajax({
                        type: "POST",
                        url: "http://www.google.com",
                        data:   "api_key"="asfasasfs2"
                            "&html="<html><html>", 
                        success: function(html){
                            alert(data);
                        },
                         error: function(request){
alert(request.responseText);
                          },
                            complete    : function(){
                            }
                        });
    });

});

Try this. it should work. and the same-origin policy does not apply to forms being posted. if the fire bug doesn't show anything that means the click event is not generated

Upvotes: 0

Related Questions