Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use type: "POST" in jsonp ajax call

People also ask

What is datatype JSONP?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.

Can JSONP used in combination with Ajax?

JSONP allows you to sidestep the same-origin policy and to some extent make cross-domain Ajax calls. It's not a silver bullet, and it certainly has its issues, but in some cases it can prove invaluable when fetching data from a different origin.

How do I use JSONP?

Method to use JSONP:In the URL include the callback parameter in the end. When the browser comes across the script element, it sends HTTP request to the source URL. The server sends back the response with JSON wrapped in a function call.

How does JSONP request work?

Standard JSON Asynchronous requestThe browser makes an asynchronous POST request to the server slapping its parameters to the service in the body. The server responds with a string of JSON data. A success handler of the request fires and the string is converted into a Javascript Object to be used in the application.


You can't POST using JSONP...it simply doesn't work that way, it creates a <script> element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.


Use json in dataType and send like this:

    $.ajax({
        url: "your url which return json",
        type: "POST",
        crossDomain: true,
        data: data,
        dataType: "json",
        success:function(result){
            alert(JSON.stringify(result));
        },
        error:function(xhr,status,error){
            alert(status);
        }
    });

and put this lines in your server side file:

if PHP:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');

if java:

response.addHeader( "Access-Control-Allow-Origin", "*" ); 
response.addHeader( "Access-Control-Allow-Methods", "POST" ); 
response.addHeader( "Access-Control-Max-Age", "1000" );

Modern browsers allow cross-domain AJAX queries, it's called Cross-Origin Resource Sharing (see also this document for a shorter and more practical introduction), and recent versions of jQuery support it out of the box; you need a relatively recent browser version though (FF3.5+, IE8+, Safari 4+, Chrome4+; no Opera support AFAIK).


JsonP only works with type: GET,

More info (PHP) http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/

.NET: http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks