Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send an javascript object/array as key-value pairs via an AJAX post with easyXDM?

Recently I realized that I needed to use easyXDM instead of jQuery's $.ajax in order to make a cross domain post request. After getting easyXDM set up I see that the functions line up fairly closely:

jQuery:

$.ajax({
    url: "/ajax/",
    method: "POST",
    data: myData
});

easyXDM:

xhr.request({
    url: "/ajax/",
    method: "POST",
    dataType: 'json', // I added this trying to fix the problem, didn't work
    data: myData
});

myData is setup something like:

myData = {};
myData[1] = 'hello';
myData[2] = 'goodbye';
myData[3] = {};
myData[3][1] = 'sub1';
myData[3][2] = 'sub2';
myData[3][3] = 'sub3';

When I make the request with jQuery it handles the sub fields properly, but not with easyXDM.

Here is how the POST request comes into the server with jQuery:

screenshot-with-shadow.png http://img37.imageshack.us/img37/4526/screenshotwithshadow.png

And here is how it comes in with easyXDM:

screenshot-with-shadow.png http://img204.imageshack.us/img204/4526/screenshotwithshadow.png

How can I send an javascript object/array of key-value pairs via an easyXDM / XHR request like jQuery does?

like image 711
Steve Brown Avatar asked Oct 25 '12 21:10

Steve Brown


2 Answers

In light of the limitations of easyXDM discussed in the comments, the only way you can use it would be to serialize your data manually when passing it to .request i.e.

xhr.request({
    url: "/ajax/",
    method: "POST",
    data: {jsonData: JSON.stringify(myData)}
});

Alternatively you could create your own postMessage solution but you will be excluding IE7 and below.

like image 118
robC Avatar answered Sep 30 '22 05:09

robC


I think you are mistaken about sending a request cross-domain via AJAX. You CAN indeed send a request cross-domain via AJAX regardless of the JavaScript API. However, in order to receive a response cross-domain, the response needs to be of data type JSONP.

JSONP is simply JSON with padding, for example:

JSON:

{ Key: "Hello", Value: "World" }

JSONP:

callback({ Key: "Hello", Value: "World" })

It is a subtle difference but JSONP by-passes browser same-origin policy and allows you to consume JSON data served by another server.

To consume JSON data coming from another server via jQuery AJAX try this:

$.ajax({
    url: "http://mydomain.com/Service.svc/GetJSONP?callback=callback",
    dataType: "jsonp",
    data: myData,
    success: function(data) {
        alert(data);
    }
});

For this to work you must make sure that your web service is returning results as JSONP and not JSON.

like image 41
Christopher.Cubells Avatar answered Sep 30 '22 06:09

Christopher.Cubells