views:

67

answers:

3

Say I need to use ajax to asynchronously ask the server for an xml file containing relevant data. What is the best practice on what this message should look like? Should it be a string like get_data or something similar? Should it be xml? I don't really need long polling since its a one-time (or close to it) request.

Thanks.

A: 

The message should be the url.

For example: http://www.example.com/get_data could return the data you need in the format you need (xml, json).

If you need some other data, use an other url. http://www.example.com/someotherdata

marapet
what then if I need to requests more than 1 type of data? How will the server distinguish between requests if I am just sending it the url?
hhj
just edited my answer which responds to this question. In case you have simple parameters, you may include them in the url as well: /get_data?page=2 or /get_data/2
marapet
+1  A: 

You can use standard a HTTP Post or Get to send the request to your server. If you don't need to specify any parameters to your server side script ( user_id, etc ) then simply appending get_data as a url parameter will work fine.

http://www.domain.com/script?get_data

If you need to send any parameters to the server in order to retrieve data it is best to encode the parameters in JSON or XML and send them as the data portion of your AJAX request. With JQuery and JSON data:

$.ajax({
    type: "GET",
    url: "http://www.domain.com/script",
    data: { key: "value", key2: "value2" },
    async: true,
    dataType: "json",
    success: function( data, textStatus ) { 
        someCallbackFucntion( data );
    }   
});
johnny_bgoode
Note that in this example the dataType parameter refers to the format which jQuery expects data to be returned as, not the format by which data is sent to the server
johnny_bgoode
A: 

It really depends on the purpose, if everything else is XML, go for XML. Personally I perfer JSON (for the client-side at least).

In a recent implementation I made, I used a simple POST request where the key represented the type of data and the value contained the time-interval it should return.

Which could be (jQuery):

$.ajax({ 
    type: "POST", 
    url: "http://www.domain.com/script", 
    data: { stock_value: "last_30_min", group_activity: "last_20" }, 
    async: true, 
    dataType: "json", 
    success: function( data, textStatus ) {  
        someCallbackFucntion( data ); 
    }    
});

A server-side controller would then handle the request appropriately and the client-side would know what data to expect when it returned. Also the key and value would be humanly readable from both client- and server-side. Of course the time-intervals could be a timestamp or otherwise, whatever fits the need.

Mads Jensen