I have this javascript code which returns an ajax request
function showUser(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("lister").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","popup.php?qq="+str,true);
xmlhttp.send();
}
I tried to execute a jquery that can't be done , unless ajax request returns , yet it's not working
$('#scrollbar2').tinyscrollbar();
So how should I execute that last jquery after the ajax load ?
Put it inside the callback after you set lister’s innerHTML:
document.getElementById("lister").innerHTML = xmlhttp.responseText;
$('#scrollbar2').tinyscrollbar();
But since you have jQuery, why not use its Ajax functionality?
$.ajax({
url: "popup.php",
data: { qq: str },
dataType: "text",
success: function(response) {
$('#lister').html(response);
$('#scrollbar2').tinyscrollbar();
}
});
Add the jQuery call inside your onreadystatechange callback. The reason for this is that ajax completes asynchronously (as per its name). Think of it like this:
onAjaxComplete = function () {
// this will run second
}
// this will run first
All work that depends on the result of the ajax call must be in the callback.
Additionally, since you are using jQuery anyway you might as well use their ajax API which is a lot simpler.
function showUser(str) {
$.get("popup.php", "qq=" + str).done(function (responseText) {
$("#lister").html(responseText);
$("#scrollbar2").tinyscrollbar();
});
}
Related
I have the following generic Ajax response writer which I recently added some logic to, in order to dynamically parse the results for script objects, and run them when I find them using jQuery.globalEval().
Here is the code:
//Generic Results Writter method for Ajax Calls
function writeAjaxResponse(targetId, response) {
document.getElementById(targetId).innerHTML = response;
try {
var dom = $j(response);
dom.find('script').each( function(){
$j.globalEval(this.text || this.textContent || this.innerHTML || '');
});
} catch (e) {
console.error("Error parsing for script reloads: "+e);
}
}
This solution works very nicely the first time its called. However writeAjaxResponse(targetId, response); is called each time a user loads some dynamic Ajax content. And unfortunately after the first time, the scripts are no longer loaded. To be clear, after the server side generated page is loaded, there are numerous links on the page which the users may click, which invoke this handler for the Ajax response.
No error occurs, and no console.error() is written.. The Ajax data loads as normal, its just that the scripts in the response are no longer loaded.
In debugging, $j.globalEval is still getting called and this.text still has the script content in it, and the data looks correct, but still no joy.
Any light someone could shed on this would be very much appreciated!
Adding main ajax call for GET for reference:
function doAjaxGet(targetId, getUrl, handler) {`
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
handler(targetId, xmlhttp.response);
}
catch (err) {
alert("Failed calling handler, detail: " + err + " Got responseText: " + xmlhttp.responseText);
}
}
}
xmlhttp.open("GET", getUrl, true);
xmlhttp.send(null);
}
I understand that jQuery will not run when the DOM content is being loaded via AJAX. But I'm confused as to the reason why. My understanding was that the DOM elements didn't exist at the time the jQuery was initiated therefore it won't find the correct IDs or classes.
But I have a situation where the jQuery is only called AFTER all the content has been loaded via AJAX. yet it still does not work.
Here is my code. I am trying to get the function decorateGains() to run after AJAX completes.
loadData('7-days'); // Runs the default AJAX for 7 days
function loadData(type){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){document.getElementById("home-table").innerHTML=xmlhttp.responseText;}
}
xmlhttp.open("GET","actions/get-data-"+type+".php",true);
xmlhttp.send();
decorateGains();
}
You can see that I am including a call to the function decorateGains() right at the end of the loadData() function.
The decorateGains() function does run, as I can see my console message. However it does not do the task that it should.
function decorateGains() {
console.log('here');
$(".gains").each(function() {
var num = +($(this).text());
if (num > 0) {
console.log('here');
$(this).addClass("positive");
}
if (num < 0) {
console.log('here');
$(this).addClass("negative");
}
});
}
(The script searches for all elements with a class of .gains and adds a new class of positive or negative depending on the content of the element. Essentially it decorates the .gains element to be red or green depending on whether the number is negative or positive).
This is because the AJAX call is asynchronous. The request has not been completed (and therefore the new content has not been appended to the DOM) when you call your decorateGains() function. You need to place the call to the function inside the onreadystatechange handler, after setting the innerHTML:
loadData('7-days'); // Runs the default AJAX for 7 days
function loadData(type) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("home-table").innerHTML = xmlhttp.responseText;
decorateGains(); // <-- move this in here
}
}
xmlhttp.open("GET", "actions/get-data-" + type + ".php", true);
xmlhttp.send();
}
I use the simple AJAX and use google debug then find that the url is not exist...
The code is very simple:
var http;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
http=new XMLHttpRequest();
} else {
http=new ActiveXObject("Microsoft.XMLHTTP");
}
try {
http.open("GET", 'http://'+ip+':5000/test.html', true);
http.onreadystatechange = onRcvData;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
http.send(null);
} else {// code for IE6, IE5
http.send();
}
} catch(e) {
http.abort();
}
function onRcvData() {
if (http.readyState==4) {
if (http.status==404) {
} else if(http.status==200) {
} else {
}
}
}
It's okay if the file test.html exists.
When the file isn't exist, the error show in the part:
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
http.send(null);
} else { // code for IE6, IE5
http.send();
}
So, even if I use the onreadystatechange method cannot prevent the error...
The file is in a directoy beside my web pages.
Then what should I do to combine with httprequest?
Any advice appreciate.
Add:
I have used the method 'Head' but it is return 404... (No matter jQuery plugin/javascript)
Like the picture:
What should I do...
Is the direction of the error I found misleaded?
Try this function
function urlExists(testUrl) {
var http = jQuery.ajax({
type:"HEAD", //Not get
url: testUrl,
async: false
})
return http.status!=404;
}
//Usage
if(!urlExists('http://www.mysite.com/somefileOrImage.ext')) {
alert('File not found');
}
HEAD
The HEAD method is identical to GET except that the server MUST NOT
return a message-body in the response. The metainformation contained
in the HTTP headers in response to a HEAD request SHOULD be identical
to the information sent in response to a GET request. This method can
be used for obtaining metainformation about the entity implied by the
request without transferring the entity-body itself. This method is
often used for testing hypertext links for validity, accessibility,
and recent modification.
Read about head here
you can use this function
function UrlExists(url)
{
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
var http=new XMLHttpRequest();
}
else {
var http=new ActiveXObject("Microsoft.XMLHTTP");
}
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Reference
As we know that AJAX is used to request a web-part in HTML format from the server. Is it possible to request a script containing functions using AJAX?
Here's an example how to use eval() to accomplish what you need:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
eval(xmlhttp.responseText);
// you can use whatever functionw as returned from the server from this line on :)
}
}
xmlhttp.open("GET","your-server-page-url",true);
xmlhttp.send();
Yes you can load a javascript via ajax
http://api.jquery.com/jQuery.getScript/
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
Also you could try something like this as mentioned in(how to run javascript in html loaded via ajax):
require("extra.js", function () {
functionDefinedInExtraJS();
});
//Sample require function:
function require(file, callback) {
var script = document.getElementsByTagName('script')[0],
newjs = document.createElement('script');
// IE
newjs.onreadystatechange = function () {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
callback();
}
};
// others
newjs.onload = function () {
callback();
};
newjs.src = file;
script.parentNode.insertBefore(newjs, script);
}
One other way would be to use eval() function and convert a string reply into working javascript code.
Is it possible to request a script containing functions using AJAX?
Yes, it is possible. And those functions could be executed on the client. For example with jQuery you even have a function that allows you to perform such request: $.getScript.
Im trying to setup a redirect for a chat script. If the chat goes unanswered after x amount of time the page will redirect.
I posted a question here yesterday regarding the same thing, but at the time knowing little in regards to JS I was trying to mix php with js. I have changed tactics.
Here is what I got thus far:
function opCheck()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
opCheck();
// alert('working2');
}
}
opjoined = "newchattimer.php";
xmlhttp.open("GET",opjoined,true);
xmlhttp.send(null);
}
function opResult()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
//alert('state = 4');
var op = xmlhttp.responseText;
}
}
ajaxurl = "ajaxfiles/opAnswer_12.txt";
xmlhttp.open("GET",ajaxurl,true);
xmlhttp.send(null);
}
setTimeout(function() {
opCheck();
opResult();
//alert(op);
if (op == 'n') window.location.replace("chatnoop.php");
}, 3000);
It creates the text file properly but ultimately no redirect. I used the chrome deveolpers tool and no errors. I also tried to alert(op); to see if the result is being grabbed, but I get no alert.
What is wrong with this code?
Thanks.
If you had taken the time to indent your code, you'd see that var op is declared inside the scope of the onreadystatechange function, which is both out of scope and asynchronous.
function opResult() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var op = xmlhttp.responseText; //declared here
}
}
ajaxurl = "ajaxfiles/opAnswer_12.txt";
xmlhttp.open("GET", ajaxurl, true);
xmlhttp.send(null);
}
setTimeout(function () {
opCheck();
opResult();
// op is out of scope here
if (op == 'n') window.location.replace("chatnoop.php");
}, 3000);
Since timeouts aren't generally the way to handle async functions, and doing ajax request when all you intend to do when it finishes is to redirect anyway is'nt really neccessary, you could just do a regular form submit, which will redirect all by itself, or move the redirecting inside the right scope!
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if(xmlhttp.responseText == 'n') window.location.href = 'chatnoop.php';
}
}
You may find what you want here http://www.tizag.com/javascriptT/javascriptredirect.php but basically i don't think that window.location.replace("chatnoop.php"); is correct. You should consider using JQuery to manage all the Ajax stuff in addition, but it should work like you've done anyway