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?
Related
I am trying to configure an oncomplete method for all ajax requests so that I can handle session timeout.
I tried adding the following script but it didn't work the same way as setting oncomplete property for p:ajax element. It wouldn't execute each time an Ajax request is made.
$.ajaxSetup({method: post,
complete: function(xhr, status, args){
var xdoc = xhr.responseXML;
if(xdoc == null){
return;
}
errorNodes = xdoc.getElementsByTagName('error-name');
if (errorNodes.length == 0) {
return;
}
errorName = errorNodes[0].childNodes[0].nodeValue;
errorValueNode = xmlDoc.getElementsByTagName('error-message');
errorValue = errorValueNode[0].childNodes[0].nodeValue;
alert(errorValue);
document.location.href='${pageContext.request.contextPath}/login/login.jsf';
}
});
Any help would be appreciated
PrimeFaces newer versions (using PF 5 here)
var originalPrimeFacesAjaxUtilsSend = PrimeFaces.ajax.Request.send;
PrimeFaces.ajax.Request.send = function(cfg) {
if (!cfg.oncomplete) {
cfg.oncomplete = doYourStuff;
}
originalPrimeFacesAjaxUtilsSend.apply(this, arguments);
};
Just to keep it somewhere, tried to find at stackoverflow but only older versions..
hope someone find this useful.
I managed to implement this by wrapping Primefaces AjaxUtils method.
var originalPrimeFacesAjaxUtilsSend = PrimeFaces.ajax.AjaxUtils.send;
PrimeFaces.ajax.AjaxUtils.send = function(cfg) {
if (!cfg.oncomplete) {
// register default handler
cfg.oncomplete = oncompleteDefaultHandler;
}
originalPrimeFacesAjaxUtilsSend.apply(this, arguments);
};
In primefaces there is component ajaxStatus which you can use for this purpose. Read documentation to see some more details about it, but for your use-case it can be something like this:
<p:ajaxStatus oncomplete="ajaxStatusHandler(xhr, status, args)"/>
and you can use your JavaScript function as is:
function ajaxStatusHandler(xhr, status, args) {
// your code ...
}
NOTE: this method can be used just for global AJAX requests (which is default in PrimeFaces), also, as I know, cross-domain script or JSONP (JSON with padding) requests can't be global.
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.
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;
}
Ok so this is driving me nuts. I am probably tired and the answer is looking at me.
public ActionResult _Login(LoginViewModel loginViewModel)
{
if (User.Identity.IsAuthenticated)
{
return JavaScript("window.location=" + "'" + loginViewModel.ReturntUrl + "'");
}
if (ModelState.IsValid)
{
if (Session["loginCount"] == null) //setup the session var with 0 count
{
Session.Add("loginCount", 0);
}
_loginStatus = _authenticationService.Authenticate(loginViewModel.SiteLoginViewModel.EmailAddress,
loginViewModel.SiteLoginViewModel.Password);
if(!_loginStatus.UserExists)
{
ModelState.AddModelError("SiteLoginViewModel.EmailAddress", _loginStatus.ErrorMessage);
return PartialView();
}
// This will only be true if the user types in the correct password
if(!_loginStatus.IsAuthenticated)
{
Session["loginCount"] = (int)Session["loginCount"] + 1;
Response.Write(Session["loginCount"]); // Counter is incremented twice!!!!
//_userService.SetInvalidLoginAttempts(loginViewModel.SiteLoginViewModel.EmailAddress, 1);
ModelState.AddModelError("SiteLoginViewModel.EmailAddress", _loginStatus.ErrorMessage);
return PartialView();
}
// DELETE ANY OPENID Cookies
var openidCookie = new HttpCookie("openid_provider");
if (openidCookie.Value != null)
{
openidCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(openidCookie);
}
_userService.SetInvalidLoginAttempts(loginViewModel.SiteLoginViewModel.EmailAddress, 0);
SetAuthTicket(loginViewModel.SiteLoginViewModel.EmailAddress, _userService.GetUserId(loginViewModel.SiteLoginViewModel.EmailAddress),
loginViewModel.SiteLoginViewModel.RemeberLogin);
if (!string.IsNullOrEmpty(loginViewModel.ReturntUrl))
{
return JavaScript("window.location=" + "'" + loginViewModel.ReturntUrl + "'");
}
return JavaScript("location.reload(true)");
}
return PartialView();
}
This almost seems that the request is being processed twice however when i step through with the debugger I only see it once. Please ignore the non important parts of the ActionMethod
This looks like you are tying to code for stuff that you automatically get with .Net's Membership provider.
Your first line "User.Identity.IsAuthenticated" looks like you are using part of membership provider but it would seem the rest is trying to code around it.
Also, why are you returning javascript to direct the user's browser to a new URL? Regarless of what .net platform you are on there are plenty of ways to redirect the user's browser without having to return raw javascript, which in my book is REALLY BAD.
##
This fixed the problem and will be removed rather than commented out. Including this twice is very bad obviously :)
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.