Recommended way to detect for Ajax support on mobile devices? - ajax

What is the standard method for detecting whether or not Ajax is supported on mobile devices? If it's not supported I need to replace Ajax content with static content. Did some Googling, but didn't find much.
Any suggestions or examples?
Thanks!

I don't know that there is necessarily a standard way--you can look at certain API/libraries/frameworks that use WURFL perhaps.
If WURFL is too heavyweight, here's what the UCLA Mobile Web Framework has developed thus far for it (ganked from https://github.com/ucla/mwf/blob/feature/core/root/assets/js/core/device.js):
/**
* Determine if device supports AJAX. This attempts to create an XHR object
* of the standard type and ActiveXObject varieties and, if any succeed, then
* it returns true.
*/
this.hasAJAX = function(){
var xhr = null;
try { xhr = new XMLHttpRequest(); } catch (e) {}
try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
return xhr != null;
}

Related

implementing PUT method of restful web services in javascript

I am developing a RESTful web service using NetBeans, GlassFish server and MySQL as the backend. I want to create a RESTful web service client using JavaScript which will consume all services through it. I already have created a client that implements the GET, POST and DELETE methods. However, I'd like to implement the PUT method in JavaScript.
It's pretty much a matter of changing type specification on the client side - but you may have to write some client or server-side logic (e.g. upper-casing or lower casing before evaluation, as part of your input sanitizing), depending on your support parameters. See the link at the end for more details.
With jQuery:
$.ajax({
url: restfulPutUrl,
type: "PUT"
}).done(function() {
$(this).addClass("done");
});
see jQuery docs, especially:
Other HTTP request methods, such as PUT and DELETE, can also be used [with the type parameter], but they are not supported by all browsers.
Without:
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}
var xhReq = createXMLHttpRequest();
xhReq.open("PUT", "restfulPutUrl", true);
see ajaxpatterns.org if needed
PUT is not implemented uniformly, http://annevankesteren.nl/2007/10/http-method-support for more details.

AJAX Newbie , POSTing data on server

I started learning AJAX recently and am trying a very simple project which involves capturing some form data and sending it to two servers.
The first server is the one which hosts the website and server side php handling. This worls fine
The second server is a python basic http server which handles only the POST operation request send from AJAX. This functionality works but is a bit weird.
Let me explain
Here is my AJAX code which is absolutely straight forward.
function xml_http_post(url, data) {
var req = false;
try {
// Firefox, Opera 8.0+, Safari
req = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
req.onreadystatechange = function() {
if (req.readyState == 4) {
// callback(req);
}
}
req.open("POST", url, true);
req.setRequestHeader("Content-type","text/plain");
req.send(data);
}
Since I do not intend to send back any response , my callback function on ready state change is empty.
But when I execute this code ( triggered by onclick on a button) , the POST doesnt work and server doesnt seem to receive anything.
But the most surprising thing is that if I keep a breakpoint at req.open( ) and then do a manual step execution then it works always. Which means , I guess that there is some timing issue which needs to be resolved.
It works fine without breakpoints if the third parameter "async" is set to false but that is anyway undesirable so I want to make it work with async = true.
Any help would be greatly appreciated.
Thanks
Shyam
As I figured out, the form page was getting unloaded by a php script which was invoked as a action of the form b the first server. This resulted in the javascript code being partially or not executed.
So I figured out that sync XHR is the only way for my.

With JavaScript Ajax polling for widget

I have the follow problem. I need to create a JS widget and set it on one blog, for example any blog from blogger.com. YOu can select there a box for javascript and I will post the JS in this box.
The problem what I have and don't know how to do this is, that the script should do an ajax polling for exmaple for 60 seconds. But how to execute an ajax call, when the host is not the same linke the host, where the JS is includet?
For example the easiest way to explai is: There is a search box and when enayone searches for anythign, then the JS script should streaming the results for 60 seconds from the server what I have set in the script and is different as the host, where the JS is includet, without to become a problem with the JS restriction for hosts.
Or for example a chat client, where the client is hosted on one other host and the server on another.
Can anyone tell me an idea, or send me an example how to do this?
Thanks
Nik
Well with this example is it possible but without JSONP?
function asyncreq(url) {
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlhttp = false;
}
}
}
if (xmlhttp){
try {
xmlhttp.open("GET", url);
xmlhttp.onreadystatechange=function() {
document.getElementById('mydiv').innerHTML = xmlhttp.responseText;
}
xmlhttp.send(null);
}
catch (failed) {
xmlhttp = false;
}
}
}
If you send the response in chunks, then everything is fine. But here is the call in ajax again. And when I use it in a different host, then I can't call the url because of the same-origin policy.
Is there another way?
I found a very interesting example here.
Take a look at the bottom, there is a job search box. If you investigate a litte bit, then you will see there is a usage of a class RSL() which is doing the request. How this class is doing the request without ajax? I can't understand wow this class works. Can anyone show me a better example?
There are two main options:
Put an iframe where you want the widget to go. Its src URL would be on the same server that will receive the AJAX call.
Use JSONP, which consists of inserting a script tag into the page to bypass the same-origin policy. This requires that the AJAX server wrap its JSON output in ?(...), where the URL includes callback=?. Then, as soon as a response has been received, start another request.

XDomainRequest object caching/asynchronous call issue

I have an aspx page on which I am using XDomainRequest object to populate two div(s) with html returned from AJAX response.
I have used Jquery to get the divs and perform "each()" on the retrieved List
var divs = $("div");
divs.each(function(index) {
if (window.XDomainRequest) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function() {
alert("XDR Response - " + xdr.responseText);
var currentDivID = divs[index].attributes["id"].value;
var selectedDiv = $("div[id='" + currentDivID + "']");
if (xdr.responseText == '') selectedDiv.attr("style", "display:none;");
else selectedDiv.append(xdr.responseText);
};
xdr.open("GET", xdrUrl);
try {
xdr.send();
} catch (e) {
alert(e);
}
} else {
alert('Create XDR failed.');
}
} else {
alert('XDR not found on window object .');
}
}
Now, whats happening is , i have two Divs on a page that have different IDs and when this code runs on "$.ready(function(){})" , both requests are asynchronously sent to the server and processed
the result is
1. sometimes the onload get the response for the second div in both div results.
2. IE sents only one request to the server(I am using fiddler to see what requests are sent to server).
Can anybody guide me whats wrong with the code ? As far as I know XDR does not support synchronous calls, and asynchronous calls are giving me wrong results. Any workaround/tip for this problem.
Issue solved by myself when I pointed out a mistake in my code:(.
xdr = new XDomainRequest();
should be
var xdr = new XDomainRequest();
For Point 2 , I added "Cache-Control:no-cache" header in my response and it solved the matter.

Problem with Ajax submission?

I am using Ajax to post data to the server(PHP code) and update it. i am posting many data one after the other, but in between the Ajax post fails and dont return a readyState to 4.
the code is as follows
function getHttpRequest()
{
var request=false;
if(window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
try
{
request=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
request=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
request=false;
}
}
}
return request;
}
the code begins here..
function updateAnswer(){
var request=getHttpRequest();
request.open('post','addAnswer.php');
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("answer="+ans);
if(request.readyState == 4)
{
var response=request.responseText;
document.getElementById("display").innerHTML=response;
}
}
i call this function to update answer in database but it donot return status=4 sometimes... please help
innerinnerHTML should be innerHTML. updateAnswer gets called each time readyState is changing from zero to four. Four is fully loaded, while those lesser are different loading stages.
Why not make life easier and use a framework like jQuery?
Also, can't you post all the data at once, in that way save a few roundtrips to the server?

Resources