Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: get JSON via ajax, but with POST instead of GET

Tags:

jquery

ajax

jsonp

I'm using jQuery's $.ajax to make a request to a third-party server, using JSONP. I specify the method as POST, but it uses GET anyway:

    $.ajax({
        type: "POST",
        dataType: "json",
        url: other_server + "/run?callback=?",
        data: {
            code: $(code).val()
        },
        success: function(obj) {
            var res = obj.results;
            $(results).val(res);
        }
    });

Looking in the jQuery source, I see these two lines that seem to force all cross-domain requests to GET, but I don't understand why it needs to be so:

if ( s.crossDomain ) {
    s.type = "GET";

Is it possible to do this with a POST instead of a GET? Why does jQuery force the use of GET?

like image 499
Ned Batchelder Avatar asked Sep 25 '11 00:09

Ned Batchelder


People also ask

Does Ajax use POST or GET?

post() methods provide simple tools to send and retrieve data asynchronously from a web server. Both the methods are pretty much identical, apart from one major difference — the $. get() makes Ajax requests using the HTTP GET method, whereas the $. post() makes Ajax requests using the HTTP POST method.

Can I use fetch instead of Ajax?

Fetch is compatible with all recent browsers including Edge, but not with Internet Explorer. Therefore, if you are looking for maximum compatibility, you will continue to use Ajax to update a web page. If you also want to interact with the server, the WebSocket object is also more appropriate than fetch.

What is Ajax POST get?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.


1 Answers

JSON-P works by inserting a <script> element into the document, hence it can only make GET requests.

If you want to make a POST request to a remote server then you need to look at XHR instead and set up CORS permissions. Note that this has limited browser support.

Alternatively, keep your requests to the same origin (and have your server make the request to the remote server).

like image 147
Quentin Avatar answered Nov 15 '22 07:11

Quentin