AJAX : What is the equivalent function of beforeSend function in XMLHttpRequest - javascript

In $.ajax there is beforeSend function, but now I'm trying to use XMLHttpRequest, I'm looking for equivalent function of beforeSend in $.ajax. How can i implement it in here.
Here is my xhr code,
xhr = new XMLHttpRequest();
var url = '../ajax/ajax_edit/update_ajax_staffUser.php';
if(file.files.length !== 0){
if(!check(fileUpload.type)){
alert("This file format not accepted");
return false;
}
xhr.open('post', url+param, true);
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.setRequestHeader('X-File-Name', fileUpload.name);
xhr.setRequestHeader('X-File-Size', fileUpload.size);
xhr.setRequestHeader('X-File-Type', fileUpload.type);
xhr.send(fileUpload);
}else{
xhr.open('post', url+param, true);
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.send(fileUpload);
}
xhr.onreadystatechange = function(e){
if(xhr.readyState===4){
if(xhr.status==200){
$('.bounce_dim').show();
setTimeout(function(){
$('.trigger_danger_alert_changable_success').show().delay(5000).fadeOut();
$('#palitan_ng_text_success').html('User successfully modified');
$('#frm_edit_staffUser')[0].reset();
$('#modal_staff').modal('hide');
$('.bounce_dim').hide();
},1000);
getUserStaffTable();
}
}
}
Since the users are uploading image to my web, I need to make a waiting interface before fires the call since the image size are too large.

You can do this by just putting the beforeSend() function before your XHR intantiation, like this:
beforeSend();
xhr = new XMLHttpRequest();
But you should define your beforeSend() function before the code above:
var beforeSend = function(){
// your code here
}

.beforeSend just calls the function before running .send, so just put your code before the line:
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.setRequestHeader('X-File-Name', fileUpload.name);
xhr.setRequestHeader('X-File-Size', fileUpload.size);
xhr.setRequestHeader('X-File-Type', fileUpload.type);
beforeSend(); // Put any code to run before sending here
xhr.send(fileUpload);

Related

JavaScript: How to "refresh" data from same URL?

Having this API:
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
How can I write using pure JS request that downloads me different data after button click event?
All I get from this code is the same quote all the time:
function getQuote (cb) {
var xmlhttp = new XMLHttpRequest();
var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && this.readyState==4) {
cb(this.responseText);
}
};
xmlhttp.open("GET", quoteURL, true);
xmlhttp.send();
}
document.querySelector('button').addEventListener("click", function() {
getQuote(function(quote) {
console.log(quote);
});
})
I tried xmlhttp.abort() and stuff but it didnt want to cooperate.
Thanks in advance!
Your response is being cached by the browser. A common trick to avoid this is to perform a request to
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}
Notice how the r={random_number} will make the URL different each time.
This is a caching problem. Add a timestamp as a query parameter and you should be able to bust the cache.

show loading status with ajax call

I'm looking for a JavaScript solution to show some sort of status while an ajax request is taking place. I tried document.getElementById("status").innerHTML = "<h2>Loading....</h2>"; but that didn't work. Any ideas?
function codesDelete(id) {
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
if (ajax.readyState === 4 && ajax.status === 200) {
document.getElementById("status").innerHTML = "<h2>Data Deleted!</h2>";
}
}
// this is what i tried
document.getElementById("status").innerHTML = "<h2>Loading....</h2>";
ajax.open("GET", "code.php?id=" + id, true);
ajax.send();
setTimeout(function() {
document.getElementById("status").style.display = "none";
}, 3000);
}
You can use JQuery's when/done. Start your status indicator and then use when/done like this:
// start the status indicator wherever it's appropriate
StartStatusIndicator();
//Make your ajax call
$.when($.ajax({
type: "POST",
...more stuff...
success: function (json) {
...even more stuff...
}
})).done(function () {
KillYourStatusIndicator();
});
The code inside done gets fired when the ajax call is finished.
Another method you could do is to use the beforeSend and complete callbacks on jQuery.ajax, like so:
$.ajax({
beforeSend:function(){
// Create and insert your loading message here as you desire
// For example, a version of what you were trying to do would be:
$("#status").html("<h2>Loading....</h2>");
},
// ... whatever other things you need, such as a success callback, data, url, etc
complete: function(){
// Remove your loading message here, for example:
$("#status").html("");
}
});
As the names suggest, beforeSend will be executed before the AJAX call is made. Complete will execute, regardless whether the AJAX succeeded or failed, after the call is finished.

XMLHttpRequest is always calling "load" event listener, even when response has error status

I'm using FormData to ajax a file upload. The upload works, but the problem is that the "error" callback is never invoked. Even when my HTTP response is a 500 internal server error (to test this I tweak server to respond with 500), the "load" callback is invoked.
function upload_image() {
var form = document.getElementById('upload_image_form');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(e) {
alert("Success callback");
}, false);
xhr.addEventListener("error", function(e) {
alert("Error callback");
}, false);
xhr.open("POST", "/upload_image");
xhr.send(formData);
}
Any ideas? I'm testing this on Chrome.
This setup should work better for your needs:
var req = new XMLHttpRequest();
req.open('POST', '/upload_image');
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
alert(req.responseText);
else
alert("Error loading page\n");
}
};
req.send(formData);
In your code error callback is never called because it is only triggered by network-level errors, it ignores HTTP return codes.
The load event is called whenever the server responds with a message. The semantics of the response don't matter; what's important is that the server responded (in this case with a 500 status). If you wish to apply error semantics to the event, you have to process the status yourself.
Expanding on #rich remer's answer, here's how you could access the status yourself:
function upload_image() {
var form = document.getElementById('upload_image_form');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(e) {
if(e.currentTarget.status < 400)
alert("Load callback - success!");
else
alert("Load callback - error!");
}, false);
xhr.addEventListener("error", function(e) {
alert("Error callback");
}, false);
xhr.open("POST", "/upload_image");
xhr.send(formData);
}
Please note accessing of the e.currentTarget.status property of the response event (e). Looks like the status is actually available via any of e.{currentTarget,target,srcElement}.status - I'm not sure which one should be used as the best practice, though.
function get(url) {
return new Promise(function(succeed, fail) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.addEventListener("load", function() {
if (req.status < 400)
succeed(req.responseText);
else
fail(new Error("Request failed: " + req.statusText));
});
req.addEventListener("error", function() {
fail(new Error("Network error"));
});
req.send(null);
});
}
code from EJS
by the example code
it is clear that network error has no response, it trigger error event.
response trigger load event
and you have to decide what to do with the response status

Call HttpHandler from javascript

I have a simple page with button which calls HttpHandler via JavaScript.
HttpHandler gets lots of files and adds them to a zip file, after finishing work zip file will be added to Response.
This operation can take several minutes. I would like to execute some JavaScript function after finishing work of HttpHandler.
How can I do it?
My code:
<asp:Button ID="btnDownload" runat=server Text="Download" OnClientClick="Download()" />
<script type="text/javascript">
function Download()
{
var url = 'FileStorage.ashx';
window.open(url);
}
</script>
UPD 1:
I have found other solution. Using XMLHttpRequest.
Code:
<script type="text/javascript">
var xmlHttpReq = createXMLHttpRequest();
function Download() {
var url = 'FileStorage.ashx';
xmlHttpReq.open("GET", url, false);
xmlHttpReq.onreadystatechange = onResponse;
xmlHttpReq.send(null);
}
function onResponse() {
if (xmlHttpReq.readyState != 4)
{ return; }
var serverResponse = xmlHttpReq.responseText;
alert(serverResponse);
}
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch (e) { }
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
alert("XMLHttpRequest not supported");
return null;
}
</script>
In onResponse() I can see my zip file in responseText (binary). But I don't have any idea how I can say to browser to download result of working httphandler such as file.
Any ideas?
I would use JQuery AJAX and then on success, write a function that will do whatever work you need it to. Plus with AJAX you can show the user an icon that says loading so they know something is actually processing, instead of the page just hanging and nothing appearing to happen.
$.ajax({
url: "FileStorage.ashx",
context: document.body,
success: function(){
// Whatever you want to do here in javascript.
}
});

Problem of using ajax call at the same time

Now, I have a problem with the ajax call which is when the web page is loaded, in the onload event of body, I assign it to call the functions which are startCount() and updateTable() this two functions contain the code that use ajax call to get the data from DB on the server side. The problem is when the ajax return it will return only one call and another call does not response. Please help me what happen and how I can slove it.
This is the onload in the body
<body onLoad="setAjaxConnection();startCount();updateTable()">
I use the XMLHttpRequest with the normal javascript, I do not use jQuery....
Use javascript closures. This link may help
http://dev.fyicenter.com/Interview-Questions/AJAX/How_do_I_handle_concurrent_AJAX_requests_.html
function AJAXInteraction(url, callback) {
var req = init();
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
if (req.readyState == 4) {
if (req.status == 200) {
if (callback) callback(req.responseXML);
}
}
}
this.doGet = function() {
req.open("GET", url, true);
req.send(null);
}
this.doPost = function(body) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(body);
}
}
function startCount() {
var ai = new AJAXInteraction("/path/to/count.php", function(){alert("After startCount");});
ai.doGet();
}
function updateTable() {
var ai = new AJAXInteraction("/path/to/update.php", function(){alert("After updateTable");});
ai.doGet();
}
Have the 'onSuccess' of one call initiate the next ajax call. So you would call startCount() and when that returns you fire off updateTable().
function setAjaxConnection(){
//call Ajax here
setAjaxConnectionResponce;
}
function setAjaxConnectionResponce(){
//on readystate==4
startCount();
}
function startCount(){
// code for count
updateTable();
}
function updateTable(){
// code for update
}
<body onLoad="setAjaxConnection();">

Categories

Resources