http://kiwilocals.com.au/dev/
Hello, here is the ajax requests on a category in the middle of the page under the banner. Work everywhere, in addition to all versions of IE.
I checked the developer's tools, a query gives the correct structure, but nothing on the loading icon does not appear after loading. In what may be the reason? Thank you.
function scat(th) {
wait_loading('sub_lst');
if (request = create_request()) {
request.open("GET", "get_subcat.php?id=" + th + "&site=1", true);
request.onreadystatechange = function () {
//alert(request);
if (this.status == 200) {
if (this.readyState == 4) {
var doc3 = document.getElementById('sub_lst');
//alert(doc3);
doc3.innerHTML = this.responseText;
if (!scroll_start) {
$('.sub_scroll').jScrollPane({
animateScroll: true
});
$('.hidden_control').show();
scroll_start = true;
}
}
}
}
request.send(null);
}
}
function create_request() {
var request = false;
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
try {
request = new XMLHttpRequest();
} catch (e3) {
request = false;
}
}
}
if (!request) {
alert("Невозможно выполнить Ajax запрос.");
return false;
} else return request;
}
function wait_loading(el_id) {
document.getElementById(el_id).innerHTML = "<center><img style=\"padding-top: 60px;\" width=\"64\" height=\"64\" src=\"images/loading.gif\"></center>";
}
The problem is with your use of 'this' in the readstatechange event.
Give this a shot.
if(request = create_request()) {
request.open("GET", "get_subcat.php?id="+th+"&site=1", true);
request.onreadystatechange = function() {
if(request.status == 200) {
if( request.readyState == 4 ) {
var doc3 = document.getElementById('sub_lst');
doc3.innerHTML=request.responseText;
if(!scroll_start) {
$('.sub_scroll').jScrollPane({animateScroll: true});
$('.hidden_control').show();
scroll_start=true;
}
}
}
}
request.send(null);
}
But one question... you use jQuery throughout your code, except for this. Why not use:
$('#sub_lst').load("get_subcat.php?id="+th+"&site=1", function(){
if(!scroll_start) {
$('.sub_scroll').jScrollPane({animateScroll: true});
$('.hidden_control').show();
scroll_start=true;
}
});
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();
});
I've read a lot of how to try and make two xmlhttprequest in parallel, but it looks like something doesn't quite work.
I have 1 php file. which includes 2 .js files.
The first runs xmlhttprequest every 3 seconds.
I want the second to run on demand, but whenever i trigger it, it returns with status 4 but the responseText is always empty. (the PHP file prints with no question, i even tried to put on the PHP file just window.open('1') to see that the file is called and its not).
Here is the first JS :
var req1 = createXMLHttpRequest2();
var user_redirected = false;
function createXMLHttpRequest2() {
var ua2;
if(window.XMLHttpRequest) {
try {
ua2 = new XMLHttpRequest();
} catch(e) {
ua2 = false;
}
} else if(window.ActiveXObject) {
try {
ua2 = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua2 = false;
}
}
return ua2;
}
function set_user_redirected_false() {
user_redirected = false;
}
function get_user_redirected() {
return user_redirected;
}
function handleResponse(username, game_id, isInvitation) {
if(req1.readyState == 4 && req1.status==200) {
var response = req1.responseText;
if (response == "true") {
// Ask to set the game_accepted var to 1 (user is redirected and not leaving)
user_redirected = true;
if (isInvitation == "true") {
window.location.href = "game.php?game_id="+game_id+"&position=2";
} else {
window.location.href = "game.php?game_id="+game_id+"&position=1";
}
}
else {
setTimeout(function(){sendRequest();}, 3000);
}
}
}
function sendRequest() {
user_redirected = false;
var username = "";
var game_id = -1;
var isInvitation = "false";
username = document.getElementById("username").value;
game_id = document.getElementById("game_id").value;
isInvitation = document.getElementById("invitation").value;
if (isInvitation == "true") {
req1.open('GET', 'check_for_inviter.php?username='+username+'&game_id='+game_id ,true);
} else {
req1.open('GET', 'check_for_opponent.php?username='+username+'&game_id='+game_id,true);
}
req1.onreadystatechange = function(){handleResponse(username, game_id, isInvitation);};
req1.send(null);
}
This is the second JS file :
function createXMLHttpRequest() {
var ua;
if(window.XMLHttpRequest) {
try {
ua = new XMLHttpRequest();
} catch(e) {
ua = false;
}
} else if(window.ActiveXObject) {
try {
ua = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua = false;
}
}
return ua;
}
function delete_waiting_games(username) {
var req2 = createXMLHttpRequest();
req2.open('GET', 'delete_waiting_games_for_username.php');
req2.onreadystatechange = function(){
window.open(req2.readyState+'&'+req2.responseText);
};
req2.send(null);
}
As you can see i open a new window to see the response and the ready state (just for testing) and i always get status 4 and empty responseText.
Thanks.
Use setTimeout to separate the calls, and with to encapsulate the XMLHTTPRequest:
function xhr()
{
with(new XMLHttpRequest)
{
open("GET",{},true);
setRequestHeader("Foo", "Bar");
send("");
onreadystatechange = handler;
}
}
function handler(event)
{
!!event.target && !!event.target.readyState && event.target.readyState === 4 && ( console.log(event) );
}
setTimeout(xhr, 500);
setTimeout(xhr, 1000);
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.
I have an Ajax function which looks like :
function getData(p) {
loadingImage();
p = p.replace("frame_", "");
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
var __page =encodeURIComponent(p);
AJAX.open("GET", "page.php?page="+__page, false);
AJAX.send(null);
var __data = AJAX.responseText.match(/<data>[\s\S]*?<\/data>/gmi);
if(!__data) { return false; }
return __data;
} else {
return false;
}
}
then i have very simple loading function ( an loading image must appear in center of page ) :
function loadingImage(type)
{
document.getElementById("body").innerHTML = "<div class='loading'></div>";
}
then how i call ajax function :
var loadedData = getData("home");
if(loadedData)
{
document.getElementById("body").innerHTML = loadedData;
}
else
{
document.getElementById("body").innerHTML = "Error";
}
but the loading image won't appear, it's quite simple, but i'm stuck here , how make it to show that loading image while requesting data, then to replace loading image with loaded data. Thanks
function getData(p, cb) {
loadingImage();
p = p.replace("frame_", "");
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
var __page = encodeURIComponent(p);
AJAX.open("GET", "page.php?page=" + __page, true);
AJAX.onreadystatechange = function(e) {
if (AJAX.readystate === 4) {
var __data = AJAX.responseText.match(/<data>[\s\S]*?<\/data>/gmi);
cb(data);
}
};
AJAX.send(null);
} else {
cb(null);
}
}
getData("home", function(loadedData) {
if (loadedData) {
document.getElementById("body").innerHTML = loadedData;
}
else {
document.getElementById("body").innerHTML = "Error";
}
});
Use async = true in the .open call.
Bind an eventhandler to readystatechange. If the readystate is 4 (LOADED) then get the data and send it to your callback.
If the AJAX fails call the callback with null or false.
In your callback get the loadedData and either render it or throw an error if there is no data.
I am searching for a Javascript Library Which has only AJAX no other feature. e.g. a Small Simple XMLHttp Wrapper.
microajax is what I settled on.
This is not a library but it is a "Small Simple XMLHttp Wrapper" I made:
//params format:"bob=hi&id=1295&lol=haha"
function ajax_post(post_url,params,success_callback,fail_callback,timeout)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST",post_url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
//xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState == 4 )
{
clearTimeout(xmlHttpTimeout);
if(xmlHttp.status == 200)
{
success_callback();
}
else
{
fail_callback();
}
}
}
xmlHttp.send(params);
var xmlHttpTimeout=setTimeout(ajaxTimeout,timeout);
function ajaxTimeout()
{
xmlHttp.abort();
fail_callback();
}
}
function ajax_get(url,success_callback,fail_callback,timeout)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET",url, true);
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState == 4 )
{
clearTimeout(xmlHttpTimeout);
if(xmlHttp.status == 200)
{
success_callback(xmlHttp.responseText);
}
else
{
fail_callback();
}
}
}
xmlHttp.send();
var xmlHttpTimeout=setTimeout(ajaxTimeout,timeout);
function ajaxTimeout()
{
xmlHttp.abort();
fail_callback();
}
}
Here' a small chunk of a JavaScript PHP wrapper I wrote a long time ago when I virtually knew nothing about JavaScript... it barely contains any AJAX methods, just wrapper functions that communicate with a PHP backend in order to allow PHP to do all the work...
In all honesty, to get what it seems you're looking for... just sit down and write yourself an AJAX library with all the common helper functions. It should take you a few hours at the most.
The Javascript:
(function() {
var
PHPJS = window.PHPJS = window.$ = function() {
return new PHPJS.Strings;
};
PHPJS.Strings = PHPJS.prototype = {
InitAJAX: function(Library, ServerString)
{
var ResultCache = document.body;
var FunctionRequest;
try {
FunctionRequest = new XMLHttpRequest();
} catch (e) {
try {
FunctionRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
FunctionRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
throw new Error("The XMLHttpRequest() object is not supported by your browser.")
return false;
}
}
}
FunctionRequest.onreadystatechange = function() {
if (FunctionRequest.readyState == 4 && FunctionRequest.status == 200) {
ResultCache.innerHTML = FunctionRequest.responseText;
return FunctionRequest.responseText;
}
}
switch (Library) {
case 'Arrays' :
FunctionRequest.open("GET", "functions/arrays-lib.php" + ServerString, true);
break;
case 'Math' :
FunctionRequest.open("GET", "functions/math-lib.php" + ServerString, true);
break;
case 'Strings' :
FunctionRequest.open("GET", "functions/strings-lib.php" + ServerString, true);
break;
}
FunctionRequest.send(null);
},
/* String Functions */
addcslashes: function(str, charlist)
{
return this.InitAJAX('Strings','?function=addcslashes&String='+str+'&Charlist='+charlist);
},
addslashes: function(str)
{
return this.InitAJAX('Strings','?function=addslashes&String='+str);
},
bin2hex: function(str)
{
return this.InitAJAX('Strings','?function=bin2hex&String='+str);
},
chop: function(str,charlist)
{
return this.InitAJAX('Strings','?function=chop&String='+str+'&Charlist='+charlist);
},
chr: function(int)
{
return this.InitAJAX('Strings','?function=chr&Int='+int);
},
chunk_split: function(str, chunklen, end)
{
return this.InitAJAX('Strings','?function=chunk_split&String='+str+'&Chunklen='+chunklen+'&End='+end);
},
convert_cyr_string: function(str)
{
return this.InitAJAX('Strings','?function=convert_cyr_string');
},
/* more functions... */
}
})();
//PHPJS.bin2hex('afsdfadsafdsafdasfsaf');
The PHP:
<?php
switch($_GET['function']) {
case 'addcslashes' :
$charlist = (#$_GET['Charlist']) ? ','.$_GET['Charlist'] : '';
echo addcslashes($_GET['String'], $charlist);
break;
case 'addslashes' :
echo addslashes($_GET['String']);
break;
case 'bin2hex' :
echo bin2hex($_GET['String']);
break;
case 'chop' :
$charlist = (#$_GET['Charlist']) ? ','.$_GET['Charlist'] : '';
echo rtrim($_GET['String'], $charlist);
break;
case 'chr' :
echo chr($_GET['Int']);
break;
case 'chunk_split' :
echo chunk_split($_GET['String'], #$_GET['Chunklen'], #$_GET['End']);
break;
/** ...etc, etc... **/
?>