Ajax message best practices - javascript

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.

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

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

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.

Related

Content-Type Ajax json missing

I wrote some php code that outputs some valid json, and sets the content-type header to application/json in my dev setup. However when I deploy this script to a embedded webserver it works fine except it's not capable of sending the content-type. It's not possible to run a other webserver.
Now I have the following code for Dynatable. Even though my dev and my embedded webserver, serve exactly the same file, and the only difference is the content-type. It works for my dev setup, however it doesn't work for my embedded setup.
I use the following code to load the json file to dynatable.
document.ready(
$.ajax({
url: 'phpApi.php',
success: function(data){
$('#myTable').dynatable({
dataset: {
records: data
}
});
}
}));
So can someone explain me why the content-type is so important for ajax? How can I tell my code manually its json?
Without the content-type the returned data is assumed to be plain text. There is nothing in your code to tell it otherwise.
One way to get json would be to specify the return type in the jquery code. Just add dataType: 'json' into the ajax configuration.
Or you could use eval() to transform the returned text to json.
document.ready(
$.ajax({
url: 'phpApi.php',
success: function(data){
$('#myTable').dynatable({
dataset: {
records: eval(data)
}
});
}
}));
Using JSON.stringify(eval(data)) might give you better results by making sure its json.
As pointed out below, JSON.parse(data) would probably be safer. (Eval is evil after all.)
So can someone explain me why the content-type is so important for ajax?
It's important so the client can identify what type of content the server returned, content-type: application/json tells jQUery to parse the data as an object. If no content type is returned, the client will assume the returned data is just plain text.
How can I tell my code manually its json?
Add dataType: "json" parameter to $.ajax()
document.ready(
$.ajax({
url: 'phpApi.php',
dataType: "json",
success: function(data){
$('#myTable').dynatable({
dataset: {
records: data
}
});
}
}));

jquery mobile web application developement( need help)

Can any one please tell me how to send data to web service using jquery and receive data from web service?
If we are using web service should we need to use url to get records?
$j.ajax({
type: "GET",
url: "testing.json",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
$j.each(data, function(index,element){
$j('#json').append("<li class='ui-li ui-li-static ui-btn-up-c ui-corner-top ui-corner-bottom ui-li-last'>"+element+"</li>");
});
}
})
});
I am developing web application using jQuery mobile.
Can any one please tell me how to send data to web service using jquery
Put it in a data property on the object you pass as the first argument to ajax().
How you format the data will depend on the particular web service.
Your existing code claims that it will be JSON so the data you pass to data should be a string representation of a JSON Text.
You will need to change the type to POST in order to do this though. The content-type request header describes the request body and you don't get one of those with a GET request.
(If the web service does not expect to receive JSON data then you will need to change the code to represent whatever it does expect).
and receive data from web service?
Read it from the first argument to the callback function you pass to the success function.
If it is in a known data format (XML, HTML or JSON), then jQuery should automatically parse it. Note that you have dataType: 'json' which will override whatever the server says it is sending back and try to parse it as JSON data regardless.
If we are using web service should we need to use url to get records?
Yes. URLs are how web server end points are identified.
a liitle example to get data from a web service using jquery ajax call
function GetData() {
$.ajax({
type: "POST",
url: "Members.asmx/GetMemberDetails",//your webservice call
data: "{'MemberNumber': '" + $("#txt_id").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnGetMemberSuccess,
error: OnGetMemberError
});
}
function OnGetMemberSuccess(data, status) {
//jQuery code will go here...
}
function OnGetMemberError(request, status, error) {
//jQuery code will go here...
}
Example: Introduction to using jQuery with Web Services

How do I do an ajax call to a database using Javascript, a URL and a key

I have been given a url of type xxxx.xxxxx.com as well as a key of type FGHyehgvc787vbhj
in order to gain read-only access to an sql database and retrieve data from it using javascript.
I have no prior experience with databases and maybe my question will sound completely stupid but I was wondering how can I combine the above information in order to get access to the database (e.g. do an ajax call and retrieve data from it..)
I'm familiar with doing ajax calls to a webpage and getting data from it using jQuery, as in :
$.ajax(/*url of website*/, function (data)
{
var dataRetrieved = $(data);
// do something with the data retrieved...
});
so I was wondering whether there is something equivalent to the above when it comes to making an ajax call to a database, using however a key.
Thank you for any help, and please delete this post if you find it completely pointless and excuse me in advance for that by the way.
It is usually very bad design to allow client side code to interact with your database in any way. This can be a huge security issue. Generally you will want your server side code to do this (e.g PHP, node, etc.). You would send a request to your server with client side code, and the server side code would do the actual work of updating the database.
you can create a wcf service and call that service through ajax, that wont be huge security issue.
try this
$.ajax({
cache: false,
type: "GET",
async: false,
data: {},
url: http:xxxxxxxxxxxx.svc/webBinding/Result?metaTag=" + meta,
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
success:function(result){},
error: function(){alert(err);}
});
Use this
$.ajax({
url: 'path/to/server-side/script.php', /*url*/
data: '', /* post data e.g name=christian&hobbie=loving */
type: '', /* POST|GET */
complete: function(d) {
var data= d.responseTXT;
/* Here you can use the data as you like */
$('#elementid').html(data);
}
});
Hope this helps...

javascript json request with some parameters

So a simple question:
JavaScript needs to send to server that request:
myserver/scipt.php?LANG=EN&AGENT={"Login":{"name":"user","pass":"user"}}
How I need to form url and data in Ajax?
Is this right?
var formData = {
"login":$("#field1").val(),
"pass":$("#field2").val()
};
$.ajax({
url:'http://myserver/scipt.php?LANG=EN&',
type:'GET',
data:'AGENT=' + $.toJSON(formData),
success: function(res) {
alert(res);
}
});
Thank you!
I'd recommend sending JSON via POST instead of GET. GET has some limitations that you want to avoid.
A part from that, yes, your code seems ok.
EDIT:
Sorry, your code is not ok.
Change the data line to:
data: $.toJSON(formData),
You need to send the data to the server in the form of a map ..
Your data is already in json format.. You need not do $.toJSON again
Instead of
data:'AGENT=' + $.toJSON(formData),
send it this way
data:{ 'AGENT' : {'Login' : formData } },
You need to URL encode any strings you want to pass through Ajax.
If jQuery works anything like a normal form, you also need to put all your query string data into data to avoid the existing query string being destroyed.
url:'http://myserver/scipt.php',
type:'GET',
data: {
"AGENT": $.toJSON(formData),
"LANG": "EN"
},
Note, you should use POST requests if you are transmitting user credentials. You don't want them cached or stored in server access.log files.

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?
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.
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.
As easyXDM can't serialize properly you need to serialize data manually:
JSON.stringify(myData)
Since the request will now contain a json string rather than object then Index.html should not parse the properties to create json structure. Go to index.html that comes with easyXDM and locate the following code:
var pairs = [];
for (var key in config.data) {
if (config.data.hasOwnProperty(key)) {
pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(config.data[key]));
}
}
data = pairs.join("&");
Don't execute this code in a case of POST request. Just assign config.data to data:
data = config.data;

Categories

Resources