jQuery and jsonp

I recently has recourse to build a jQuery jsonp integration. A workaround to the browsers same origin policy.
I discovered this little black art that is not well documented at all. 
There's a few useful links on the web but not alot to go on, even on jQuery site.
Here's my code with some explanation below:


     // I setup an object literal to set the data, then stringify it (name your fields as you need)
     //
     var callData = {
                   Field1: "Denis",
                   Field2: "0",
                   Field3: "Test"
            };

     var JSONRequestData = JSON.stringify(callData);


     $.ajax({  
                dataType: 'jsonp',
                jsonpCallback: 'postProcessingCallBack',
                url: 'http://myserver.com/myjsonphandler?jsoncallback=?',
                data: JSONRequestData,
                async: false       
            });   


You must set dataType to jsonp. 

'postProcessingCallBack is the name of a js function already defined to handle the callback i.e. postProcessingCallBack = function (data) { ... }

The data transferred depends on what the server expects e.g. if server just expects a string then you could just use "Field1=Denis" for data: property. 
But my server expected a json string so I created the data as an object literal, set my params and then called JSON.stringfy() to convert to string.

jQuery will automatically insert your callback name defined in property jsonpCallback: into the url string to be sent to the server which is then used by the server to wrap the response. jQuery makes sure the callback is called and you just need write your handler.

Important note: my call is synchronous hence "async: false". If async then need different handling.

That's it.

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more