I have a link on click of which a request should go to web server and on successful execution a redirection should happen. I have used ajax for this but I am getting NS_Binding_Aborted error in HTTpFox.
The code:
<a id="lnkredirect" href="javascript:void(0);" onclick="myfunction();">Some text</a>
The ajax code:
function myfunction(){
$.ajax({
url: Web server Url,
type: 'POST',
datatype: 'JSON',
timeout: 20000,
data: null,
success: function{ $("#lnkredirect").attr('href','redirection link...');},
error : function{ $("#lnkredirect").attr('href','redirection link...');}
)};
return true;
}
The redirection is happening but I am getting NS_Binding_Aborted error in Firefox. In both success and error scenario, the redirection should happen but why NS_Binding_Aborted is coming, I am not sure of this. NS_Binding_Aborted error should come only if one event is cancelling some prior running event but I have already suppressed href of the link and redirecting it once the ajax request is executed, so there should be only one server call and NS_Binding_Aborted should not come. Please let me know where am I going wrong?
I got a similar trouble, also while using both a href and a XmlHttpRequest inside a onclick. My XMLHttpRequest was aborted (ns_binding_aborted) and thus never reached status 200. I also could see that my XHR was "blocked by devtools" in Firefox console.
This was because the page was reloaded (by the href) before it could finish its job (what was in the onclick).
I had something like this:
<script type="text/javascript">
function incrementNumberOfDownloads() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // 4 = request ended, 200 = success
//update displayed number of downloads
document.getElementById("numberOfDownloads").innerHTML = this.responseText;
}
};
xhttp.open("GET", "incrementNumberOfDownloads.php", true);
xhttp.send();
return true;
}
</script>
<p id="numberOfDownloads">42</p>
Download my file !
I fixed the problem by adding a target="_blank" to my download link, so that the page is no more reloaded when clicking, enabling the XMLHttpRequest to finish with success.
This is caused by another request that abort your request. Generally when your goal is reload data o all page just end request and don'ts is synchronized request, a little novell error.
In this case the "return " sentence is the problem, the return sentence must be in success seccion.
My issue fixed, when I've changed calling native js form submit event to jQuery submit event.
// this code
form[0].dispatchEvent(new Event("submit"));
// changed to
form.submit();
Related
I am presently developing a web application with jQuery mobile. However, I found that when a "changePage" fails, I can no longer send ajax requests. After the failure, all ajax requests return an error. Here's the code executed when the submit button on the form is clicked (it's a basic user login screen):
// Event when user click the Submit login button
$('#submitLogin').on("click", function () {
// submit the user credentials to the server
$.ajax({
type: "POST",
url: "./LogUser",
data: {
EmployeeID: $('#EmployeeID').val(),
EmployeePIN: $('#EmployeePIN').val()
},
dataType: "text",
async: true,
cache: false,
error: function (rqst, text, thrownError) {
$('#dlg-login-error-message').text(thrownError);
$('#dlg-login-error-popup').popup("open");
},
success: function (data) {
if (data == "Success") {
$.mobile.changePage("./LoadScreen/Menu");
}
else {
$('#dlg-login-error-message').text(data);
$('#dlg-login-error-popup').popup("open");
}
}
});
return false;
});
If the post itself fails, I can resubmit without problem. If the .mobile.changePage fails, a "page not found" is displayed, but I am not able to resubmit, ajax no longer making request to the server and jumping directly to the error callback with a "not found" error.
I am guessing the problem comes from the fact that jQuery mobile uses AJAX request to load pages, and that somehow, ajax calls are getting mixed up somewhere.
I did more tests, even intercepted the pageloadfailed event, but nothing works. After the page change failure, AJAX calls no longer sends anything to the server and jump automatically to the error callback function.
I tried with async=false, same problem. I tried debugging jQuery-mobile, but I am still not able to find the "changePage" function itself ( the .code is quite confusing ).
I just spent the last two days trying to figure out a way to resolve this and I am seriously thinking of using something else than jQuery-mobile for our development.
I have found a workaround for my problem, but I do not know the full impact of this solution yet.
To prevent the problem, I had to set the "pushStateEnabled" configuration option to "false".
So if you find yourself with the same problem, try putting the following in a script right before the loading of the "jQuery-mobile" script.
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
Example:
<!-- Load the script for jQuery -->
<script src="~/Scripts/jquery-2.1.4.js"></script>
<!-- Set default for jQuery-Mobile, before it is actually loaded -->
<script>
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
</script>
<!-- Load the script for jQuery-Mobile -->
<script src="~/Scripts/jquery.mobile-1.4.5.js"></script>
I have an ajax request which invokes GetTierNamesServlet:
$('#application').change(function() {
$.ajax({
url : 'GetTierNamesServlet',
data : {
name : $('#application').find(":selected").text()
},
type : 'get',
cache : false,
success : function(data) {
},
error : function() {
alert('error');
}
}).done(function() {
var test = '<c:out value="${tiers}" />';
alert(test)
})
});
GetTierNamesServlet saves 'tiers' to a session attribute as follows and forwards back to the same page (index.html).
HttpSession session = request.getSession(false);
session.setAttribute("tiers", tiers);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
When alert(test) is called, it alerts the selected tiers from the previous time the ajax request was processed.
The session attribute 'tiers' always seems to "lag" one refresh behind.
What am I doing incorrectly here? I would expect that by placing the alert within the .done portion of the ajax request it would wait the asynchronous call to return before doing something.
This fragment of JavaScript:
var test = '<c:out value="${tiers}" />';
is rendered with the value of ${tiers} before your servlet is called. If you inspect the HTML on the page you will likely find something like:
...
}).done(function() {
var test = 'null'; // or some other "old" value
alert(test)
})
the JSP content is translated to HTML and sent to the browser (page 1)
some event on page 1 causes the JavaScript to be executed
the AJAX call results in the page being rendered again and returned to the browser (page 2)
the JavaScript in page 1 finishes executing via the .done(...) function.
You AJAX call is returning a page when it should probably return a JSON fragment containing your tiers content which will then be consumed by the .done function.
I have a JavaScript application that works like this:
Uploads a file, receives the uploaded file ID as a response
This is done using the BlueImp uploader
Uses the file ID to refer to the file in subsequent requests, in this case to receive a preview of the uploaded file.
This is the code for the file upload 'complete' handler. It's originally written in Coffee Script (http://pastebin.com/708Cf9tu).
var completeHandler = function(e, data) {
var url;
if (data.textStatus !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget i konsollen");
console.group('Upload failure');
console.error(data.textStatus);
console.error(data.result);
console.groupEnd('Upload failure');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
return;
}
self.fileUploadResponse = data.result;
url = "" + config.api_root + "/" + config.api_path_tabulardatafilepreview;
return $.ajax(url, {
type: 'POST',
dataType: 'json',
async: false,
data: {
'file_handle': data.result.file_handle,
'rownum': 5
},
complete: function(req, text_status) {
if (text_status !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget " + "i konsollen");
console.group('Failed to receive data file preview');
console.log(text_status);
console.log(req.responseText);
console.log(req);
console.groupEnd('Failed to receive data file preview');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
}
self.previewData = JSON.parse(req.responseText);
return self.setStage(2);
}
});
};
This works brilliantly in FireFox, but in Chrome I just started to get an error in the second jQuery Ajax request. It now returns with status "error", with no responseText and with statusText set to "Error: NETWORK_ERR: XMLHttpRequest Exception 101". Though this doesn't happen in all cases. The uploaded file doesn't seem to have anything to do with the issue, because a 10KB csv file works, a 120KB xlsx file fails but a 1.2MB xlsx works. Additionally it's the second Ajax request that fails, and it doesn't do anything but send two small integers to the server. Why does that fail!?
Also this just started happening today. I haven't changed anything that I know of, and I have not updated Chrome.
Does anyone have a clue as to why Chrome is doing this? Can it have anything to do with an Ajax request being launched in the complete handler of a previous Ajax request?
Thanks for any guesses that can help me solve this
Turns out it's a bad idea to start lengthy processes inside Ajax event handlers. In my case, starting a new synchronous Ajax request in the event handler was the mistake. I have since made both requests asynchronous and separated the code into neat functions, and I'm no longer bothered by the exception.
I have a web application that must work with IE7 (yeah i know..) where the frontend is entirely made with ExtJS4, and theres a servlet used to download files. To download a file i send some parameters so i cant simply use location.href. it must be a POST.
So far it works, but when an exception is thrown in the servlet i dont know how to handle it to show the user some alert box or some message without redirecting to another page.
In my webapp im also using DWR and im aware of the openInDownload() function, but it triggers a security warning in IE.
So, (finally!) the question is
Using this code:
post = function (url, params) {
var tempForm=document.createElement("form");
tempForm.action=url;
tempForm.method="POST";
tempForm.style.display="none";
for(var x in params) {
// ...snip boring stuff to add params
}
document.body.appendChild(tempForm);
tempForm.submit();
return tempForm;
}
is it possible to stay in the same page after submitting ?
or with this other one:
Ext.Ajax.request({
url: './descargaArchivoNivs',
method: 'POST',
autoAbort: true,
params: {
nivs: jsonData
},
success: function(response){
// HERE!!
// i know this is wrong
document.write('data:text/plain,' + response.responseText );
/* this looked promising but a warning pops up
var newwindow = window.open();
newwindow.document.open();
newwindow.document.write('data:text/plain, ' + response.responseText );
newwindow.document.close();*/
},
failure: function(resp){
alert('There was an error');
}
});
is it possible to open the file download dialog // HERE!! with the response content??
or is there some other way to open the file download dialog on success, and on failure show a friendly message without losing the users input (the params of the POST) ?
(sorry if this post was too long)
Can any one help me with the following code:
$(document).ready(function() {
$("#add_user").submit(function() {
$.post( "../php/register_sql_ins.php",
{r_fname: $("#fname").val(),
r_lname: $("#lname").val(),
r_uname: $("#uname").val(),
r_pass: $("#pass").val(),
r_authLevel: $("#authLevel").val(),
r_email: $("#email").val(),
r_company: $("#company").val(),
r_phone: $("#phone").val(),
r_address: $("#add").val()}, function(result) {
alert(result);
}
);
return false;
});
});
This should store my user data in a sql table. the php part of code(register_sql_ins.php) works fine. but this query piece of code just doesn't work!! and I have no idea what is the problem!
With Firebug it returns false every time!
By the way sorry for bad english. It's not my mother tong!
There are two places where I would look for the cause of such error:
Network tab in Firebug. Check what is sent to the server and what is the response. If data sent is correct and server replies with status 200, then you have to debug your PHP script, else
Server logs. If the request failed to complete succesfully, log will contain the reason.