Show/hide html element on javascript xhr request function - javascript

i have a signle html element which i need to show and hide by jquery into a pure javascript xhr request method, for now it shows always the element without hiding when request is complete/success, on error i would like to hide that again.
html
<div class="ajax-loading">Loading ..</a>
xhr method
function post(_url, _callback,_data){
var xhr = createCORSRequest('POST',_url);
if (!xhr){
throw new Error('CORS not supported');
}
$('.ajax-loading').show();
xhr.send(_data);
/*SUCCESS -- do somenthing with data*/
xhr.onload = function(){
// process the response.
_callback(xhr.responseText);
$('.ajax-loading').hide();
};
xhr.onerror = function(e){
console.log(e);
$('.ajax-loading').show();
};
}
the problem is that i always do that by $.ajax() statements(error,success,beforeSend), this time i have pure javascript xhr requests and i don't know how to do that.
to be more clear i would like this converted to xhr javascript as shown:
$.ajax({
/*data etc ...*/
error:function(){
$('.ajax-loading').show();
},
success:function(){
$('.ajax-loading').hide();
},
beforeSend:function(){
$('.ajax-loading').show();
}
});
EDITED
i tryed also without success:
function get(_url, _callback){
var xhr = createCORSRequest('GET',_url);
if (!xhr){
throw new Error('CORS not supported');
}
xhr.send();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 /*COMPLETE STATEMENT*/){
alert(xhr.readyState);
}
};
/*SUCCESS -- do somenthing with data*/
xhr.onload = function(){
// process the response.
_callback(xhr.responseText);
};
xhr.onerror = function(e){
console.log(e);
};
}

Check this one:
Wiki for xmlhttprequest
In the xmlHTTPRequest you have to check the state of the object to find out what is going on with the request.

fixed with
xhr.onloadstart = function(){
$('.ajax-loading').show();
}
xhr.onloadend = function(){
$('.ajax-loading').hide();
}

Related

How to interface a DOM object when a link is pressed

I am on http://localhost:8000/index.html
When I press a link, I want it to go to localhost:8006/someAddress and select element with id='157579' AND press button with id='1787' which will cause an iframe further down my html to show something different.
I have made some pseudo code that somewhat shows what I want, but I am having a hard time converting it into something functional:
<body>
<script>
function Scenario1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
GoTo http://localhost:8006/SomeAddress
document.getElementById("157579").Select
Button("1787").Press
}
}
</script>
</body>
Is this possible to do, or is there an alternative? I understand that I have to do something with AJAX or jQuery or something similar, right?
use jquery click event when in your onload is triggered like $('#157579').click();
let xhr = new XMLHttpRequest();
xhr.open('GET', '/article/xmlhttprequest/example/load');
xhr.send();
xhr.onload = function() {
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
$('#157579').click();
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`);
}
};
xhr.onerror = function() {
alert("Request failed");
};

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

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

Recursively calling the web service not executing completely

I am working on Titanium Appcelerator to develop iphone application. I need to call a web service with different parameters about more than 1250 times. I have place the xhr.send() method inside the xhr.onload function. It working fine about 3-8 times but stop calling after that. No error or any issues displaying there. Please suggest.
function(e){
var xhr = Titanium.Network.createHTTPClient();
var Request = "<RefId>"+idArray[e.index]"</RefId>";
xhr.open("POST", url);
xhr.setRequestHeader("WWW-Authenticate","Basic");
xhr.setRequestHeader("Content-Type","text/xml", "charset=utf-8");
xhr.setRequestHeader("Content-Length", Request.length);
xhr.setRequestHeader("SOAPAction", "http://example.com");
xhr.onload = function() {
var doc = Titanium.XML.parseString(this.responseText);
var type = doc.getElementsByTagName("studentName");
Ti.API.info(type.item+';'+type.item.length);
if(type.item.length<1){
file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "textfile.txt");
}
doc=null;
type=null;
if(idArray.length>e.index){
//alert('Calling API');
var url="http://example.com";
var Request = "<RefId>"+idArray[e.index++]"</RefId>";
xhr.setTimeout(2500);
xhr.open("POST", url);
xhr.send(Request);
}
};
xhr.onerror = function(){
alert('Error')
};
xhr.send(Request);
}
I would try recreating the client each time not just calling send again

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

Categories

Resources