This snippet doesn´t work. I´m trying to get the file size of an resource via jscript
I find this code:
var obj = new XMLHttpRequest();
obj.open('HEAD', 'resource.png', true);
obj.onreadystatechange = function()
{
if(obj.readyState == 4)
{
if(obj.status == 200)
{
alert('Size in bytes: ' + obj.getResponseHeader('Content-Length'));
}
else
{
alert('ERROR');
}
}
};
Whats wrong? thanks.
try this
var obj = new XMLHttpRequest();
obj.open('HEAD', 'resource.png', true);
obj.onreadystatechange = function()
{
if(obj.readyState == 4)
{
if(obj.status == 200)
{
alert('Size in bytes: ' + obj.getResponseHeader('Content-Length'));
}
else
{
alert('ERROR');
}
}
};
obj.send(null);
hope it helps.
Related
I have following code, which highlights (fadein/out) the replied comment (its a div element).
I show only 10 last comments on the page
If the comment is found, then I highlight it (working fine), otherwise I load all comments and then try to highlight necessary one. But after loadAllComments function in the else clause the hide() method is not working - I wonder why.
function showReply(reply){
var p = getElement(reply);
if (p) {
$("#" + reply).animate({
opacity: 0.5
}, 200, function () {
});
setTimeout(function () {
$("#" + reply).animate({
opacity: 1
}, 200, function () {
});
}, 1000);
}
else{
loadAllComments(); //load all elements. working fine
$("#"+reply).hide(); //nothing happens. :-(
}
function loadAllComments() {
deleteComments();
$('.show-more-button').hide();
var xhr = new XMLHttpRequest();
xhr.open('GET', api_url + 'video_comments/?video=' + video_id, true);
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert(xhr.responseText);
}
else {
var comments = JSON.parse(xhr.responseText);
for (var i = comments.results.length - 1 ; i >= 0 ; i--){
$('.comment-content-box').append(showComment(comments.results[i]));
}
}
}
};
xhr.send();
}
function deleteComments(){
var comments_count = $('.comment-content-box').children('div').length;
for (var i=0; i < comments_count; i++){
$('.comment-render-box').remove();
}
}
function showComment(comment) {
return "<div>" // example, there is plenty of code, but it's just a return function
}
You're performing an XHR which is asynchronous. Supply a callback function to loadAllComments to be executed after your XHR completes:
function loadAllComments(callback) {
deleteComments();
$('.show-more-button').hide();
var xhr = new XMLHttpRequest();
xhr.open('GET', api_url + 'video_comments/?video=' + video_id, true);
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert(xhr.responseText);
}
else {
var comments = JSON.parse(xhr.responseText);
for (var i = comments.results.length - 1 ; i >= 0 ; i--){
$('.comment-content-box').append(showComment(comments.results[i]));
}
// xhr is complete and comments are now in DOM
callback();
}
}
};
xhr.send();
}
...
// usage
loadAllComments(function() {
$('#' + reply).hide();
});
here is my ajaxHandler i want to convert this to native javascript i.e
using XMLHttpRequest but i am unable to understand how to convert.`
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
Paper.giffyLoading.style.display = 'block';
if (!attributes.nopopup) {
if (attributes.loadmsg) {
Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
attributes.loadmsg = null;
}
}
$.ajax(attributes);
}
}
i have try to convert the above code like this
XMLRequestDefaultHandler = function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'index.php/request', true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {
} else {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
}
};
xmlHttp.send(null);
}
I extracted ajax function of Jquery, to work without jquery.
And replace $.ajax(attributes); to ajax(attributes);
JQuery's ajax function, without JQuery :
function ajax(option) { // $.ajax(...) without jquery.
if (typeof(option.url) == "undefined") {
try {
option.url = location.href;
} catch(e) {
var ajaxLocation;
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
option.url = ajaxLocation.href;
}
}
if (typeof(option.type) == "undefined") {
option.type = "GET";
}
if (typeof(option.data) == "undefined") {
option.data = null;
} else {
var data = "";
for (var x in option.data) {
if (data != "") {
data += "&";
}
data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
};
option.data = data;
}
if (typeof(option.statusCode) == "undefined") { // 4
option.statusCode = {};
}
if (typeof(option.beforeSend) == "undefined") { // 1
option.beforeSend = function () {};
}
if (typeof(option.success) == "undefined") { // 4 et sans erreur
option.success = function () {};
}
if (typeof(option.error) == "undefined") { // 4 et avec erreur
option.error = function () {};
}
if (typeof(option.complete) == "undefined") { // 4
option.complete = function () {};
}
typeof(option.statusCode["404"]);
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
else { xhr = new XMLHttpRequest(); }
} else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }
xhr.onreadystatechange = function() {
if (xhr.readyState == 1) {
option.beforeSend();
}
if (xhr.readyState == 4) {
option.complete(xhr, xhr.status);
if (xhr.status == 200 || xhr.status == 0) {
option.success(xhr.responseText);
} else {
option.error(xhr.status);
if (typeof(option.statusCode[xhr.status]) != "undefined") {
option.statusCode[xhr.status]();
}
}
}
};
if (option.type == "POST") {
xhr.open(option.type, option.url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(option.data);
} else {
xhr.open(option.type, option.url+option.data, true);
xhr.send(null);
}
}
i don't understand why i get TypeError (this.req is undefined) on line :
if (this.req.readyState === 4) {
function RequestCORS(url) {
this.url = "http://crossorigin.me/" + url;
this.req = new XMLHttpRequest();
}
RequestCORS.prototype.send = function () {
this.req.open("GET", this.url);
this.req.onreadystatechange = function() {
if (this.req.readyState === 4) {
if (this.req.status === 200) {
console.log(this.req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
this.req.send();
};
function main() {
var url = "http://www.01net.com/rss/mediaplayer/replay/";
var requete = new RequestCORS(url);
requete.send();
}
window.addEventListener("load", main);
Thanks for reading.
this.req is undefined because you're making an asynchronous request and by the time your onreadystatechange fires this doesn't refer to your RequestCORS instance anymore.
You could declare a local variable that remains in scope inside the onreadystatechange function.
var req = this.req;
this.req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
console.log(req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
or use bind
this.req.onreadystatechange = function() {
if (this.req.readyState === 4) {
if (this.req.status === 200) {
console.log(this.req.responseText);
} else {
console.log("error request");
//handleError
}
}
}.bind(this);
or get rid of this.req entirely
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
console.log(req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
function setAction(){
var value;
var id = document.getElementById('id').value;
if(document.getElementById('action1').checked==true){
value = "Active"
}
else if(document.getElementById('action2').checked==true){
value = "Inactive";
}
else{
value = "other";
}
jConfirm('Are you continue?', 'Confirmation Dialog', function(r) {
if(r==true){
var strURL="process.php?task=setActionProposal&id="+id+"&status="+value+"&value="+document.getElementById('other').value;
var req = getXMLHTTP();
if (req) {
document.getElementById('loader').style.display='block'
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//alert(req.responseText);
obj = JSON.parse(req.responseText);
if(obj.valid==true){
document.getElementById('loader').style.display='none';
window.location.href='user.php';
}
}
else {
// alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
else{ }
//jAlert('Confirmed: ' + r, 'Confirmation Results'); });
}
My page is not redirecting what's wrong with this can any one solved out I need to redirect with window.location.href='user.php';
Try with your full project path
ie,
window.location = 'your project path/user.php';
At first,
You check that,
window.location.href = 'http://www.google.com';
this will work correctly.
Then the issue is your project path.
What I'm trying to do is limit the options of one select box based on what the user chooses in a prior select box. It works perfectly in Chrome and Firefox, but in IE 10 the only thing that shows up is the text "Not Found". I'm not sure, but my guess is that something is going wrong in request.status. What it is, however, I have no idea.
function prepForms() {
for (var i = 0; i<document.forms.length; i++) {
var thisform = document.forms[i];
var departCity = document.getElementById("departcity");
departCity.onchange = function() {
var new_content = document.getElementById("ajaxArrive");
if (submitFormWithAjax(thisform, new_content)) return false;
return true;
}
}
}
function getHTTPObject() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {}
return false;
}
return new XMLHttpRequest();
}
function submitFormWithAjax(whichform, thetarget) {
var request = getHTTPObject();
if (!request) {return false;}
var dataParts = [];
var element;
for (var i = 0; i<whichform.elements.length; i++) {
element = whichform.elements[i];
dataParts[i] = element.name + "=" + encodeURIComponent(element.value);
}
var data = dataParts.join("&");
request.open("POST", "flightlocationfilter.asp#ajaxArrive", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var matches = request.responseText.match(/<div id="ajaxArrive">([\s\S]+)<\/div>/);
if (matches.length > 0) {
thetarget.innerHTML = matches[1];
} else {
thetarget.innerHTML = "<p>--Error--</p>";
}
} else {
thetarget.innerHTML = "<p>" + request.statusText + "</p>";
}
}
};
request.send(data);
return true;
};
Edit: After walking through with the IE Developer Tools, it looks like the request.readyState is not moving beyond 1 to 4.