How to make a jsonp POST request that specifies contentType with jQuery? How to make a jsonp POST request that specifies contentType with jQuery? javascript javascript

How to make a jsonp POST request that specifies contentType with jQuery?


It is not possible to make a JSONP POST request.

JSONP works by creating a <script> tag that executes Javascript from a different domain; it is not possible to send a POST request using a <script> tag.


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" );


There's a (hack) solution I've did it many times, you'll be able to Post with JsonP.(You'll be able to Post Form, bigger than 2000 char than you can use by GET)

Client application Javascript

$.ajax({  type: "POST", // you request will be a post request  data: postData, // javascript object with all my params  url: COMAPIURL, // my backoffice comunication api url  dataType: "jsonp", // datatype can be json or jsonp  success: function(result){    console.dir(result);  }});

JAVA:

response.addHeader( "Access-Control-Allow-Origin", "*" ); // open your api to any client response.addHeader( "Access-Control-Allow-Methods", "POST" ); // a allow postresponse.addHeader( "Access-Control-Max-Age", "1000" ); // time from request to response before timeout

PHP:

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

Doing like this, you are opening your server to any post request, you should re-secure this by providing ident or something else.

With this method, you could also change the request type from jsonp to json, both work, just set the right response content type

jsonp

response.setContentType( "text/javascript; charset=utf-8" );

json

response.setContentType( "application/json; charset=utf-8" );

Please not that you're server will no more respect the SOP (same origin policy), but who cares ?