Jquery plugin doesn't work when loading with AJAX? - javascript

I use jquery to auto scroll blog post.. They normally works fine but it doesn't scroll or work at all when I load that page via AJAX.. The problem could be how I'm calling ajax to load the page..may be callback function issue which I'm not getting right? here is the ajax code I'm using:
function loadme() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("loadcontent").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://xxxyyy.com/blogs/", true);
xhttp.send();
}
They all work but jquery post auto scroll will not work.. Is that due to callback function? I'm not sure.. Someone suggest or correct the code... Would appreciate volunteered help
Addition
I did alternative callback function but that too doesn't work either..
<div id="loadcontent"> Content to load/replace</div>
<button onclick="loadDoc('http://xxxyyy.com/blogs', myFunction)">Browse
Blogs</button>
//ajax with callback function
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("loadcontent").innerHTML =
xhttp.responseText;
}

Since you have tagged jquery and you also mentioned jquery in your anwser,
I am providing a jquery solution.
//bind click event to the button, set an id for the button to make it just for that particular button
$(button).click(function() {
ajaxRequest("url", loadcontent);
});
// this will be the function for ajax, with the callback as parameter
function ajaxRequest(url, callback) {
$.ajax({
url: url,
method: "get",
success: function (response) {
callback(response);
},
error: function (jqXHR, exception) {
// handle errors
}
});
}
// this will be passed as callback to the ajaxRequest function
//you just need to set the innerHTML and the use animate to scroll to the bottom or to whatever height you would like
function loadcontent(message) {
$("#loadcontent").html(message);
$("#loadcontent").animate ({ scrollTop: $("#container").prop("scrollHeight") }, 10);
}

Related

AJAX with better re-usability?

I have my AJAX split in two parts. The "AJHAX" function which has two values, the url of the file to load and then the function where I can specify where I want it to end up ("cFuntion" uses the function "loadToContent"):
First part:
function AJHAX(url, cFunction) {
var xhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
Second part:
function loadToContent(xhttp) {
document.getElementById('content').innerHTML =
xhttp.responseText;
}
So from the first part, I can call the functionality in my menu by adding the following to a link / an element:
onclick="AJHAX('page.php', loadToContent)"
However, with this I can only specify which page to load, not which element I want it loaded to. I tried to add it as a criteria for the second part of my code, like this. But to no avail:
function loadToContent(xhttp, targetElement) {
document.getElementById(targetElement).innerHTML =
xhttp.responseText;
}
Onclick:
onclick="AJHAX('menu.php', loadToContent(sidebar))"
Any suggestions?
Solution has been found (thanks to #schogges, please upvote!). Complete working example:
JS:
function AJHAX(url, targetElement, cFunction) {
var xhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this, targetElement);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function loadToContent(xhttp, targetElement) {
document.getElementById(targetElement).innerHTML =
xhttp.responseText;
}
HTML:
<div onclick="AJHAX('home.php', 'content', loadToContent);closeSidebar()">
Home</div>
So in the HTML, you just specify the page to load, the ID of the element to load the page into and then the "loadToContent" function that actually loads it into to element. As you can see, also have ";closeSidebar()" in there, and even if it does nothing for this example, I'll just leave it here to show anyone new that you can do it this way to add more than one function to an onclick-event. Mine simply just edits some CSS to hide the sidebar.
What about using a third parameter at AJHAX()?
Try this:
function AJHAX(url, target, cFunction) {
var xhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this, target);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function loadToContent(xhttp, targetElement) {
document.getElementById(targetElement).innerHTML =
xhttp.responseText;
}
and Onclick:
onclick="AJHAX('menu.php', 'sidebar', loadToContent)"
The line onclick="AJHAX('menu.php', loadToContent(sidebar))" doesn't work because it references an inert string.
Instead what you need to do is to reference a function, so it actually carries out the intended task: onclick = function () { AJHAX('https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', loadToContent);};
Here is a snippet showcasing my answer:
//First part:
function AJHAX(url, cFunction) {
var xhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
//Second part:
function loadToContent(xhttp) {
console.log(xhttp.responseText);
alert(xhttp.responseText);
}
//TEST
var button = document.body.appendChild(document.createElement("h1"));
button.textContent = "Click me!";
button.onclick = function () {
AJHAX('https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', loadToContent);
};

What causes a function to "freeze" in javascript?

Say in window.onload function i call a bunch of other methods:
function window.onload(){
method1();
alert("test1");
method2();
alert("test2");
}
So my test1 method is working fine, i get the alert "test1", but then it appears that my code is "freezing" on method2, so the alert "test2" is not being called.
Here is what my test2 method looks like
function method2(){
alert("testing");
var xhr = new XMLHttpRequest();
xhr.open("GET", "url that i want to call from", true);
xhr.onload = function() {
if (xhr.status==200) {
alert(xhr.responseText);
alert("yay");
}
else{
alert("Aww");
}
}
xhr.send();
}
what i dont understand is why i dont even get the alert "testing", if my code is freezing somewhere why doesnt it at least run the first line in the method?
Can anyone explain why this occurs in javascript?
thanks
I have always hooked into to the 'on ready state change' event.
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
$(document).ready(function () {
loadDoc();
});
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
alert("yay");
}
};
xhttp.open("GET", "demo", true);
xhttp.send();
}
</script>
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
From the information you provided, I am guessing that you are running into browser security issues ...
I would recommend using jquery to handle the job for you. the $(document).ready function in jquery has always worked awesomely for me in the years I have been using the framework.
If you can't use jquery, then you need to have the user click on a button in order to initiate the http request you desire.
Also, if you need to perform the 'Awww' action you can append it to the if statement but I would recommend using if else based on xhttp.readyState values or your 'Awww' will repeat often.

How to handle AJAX errors uniformly in jQuery?

I'd like to detect 401 errors in AJAX calls and redirect to login.html. But I ended up writing many duplicate of code like
if (xhr.status === 401) {
location.assign('/login.html');
}
in the error callback.
My question is, is there a way (the best way?) to handle them uniformly? Could I could inject some code into all of those Ajax calls?
You can use ajaxError() for this. This event triggers when an ajax completed with error. Then you can check the status like this,
$(document).ajaxError(function (event, jqxhr, settings, exception) {
if (jqxhr.status == 401) {
location.assign('/login.html');
}
});
function myAJax(sURL,fnSuccess,fnError) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
if(xhttp.status == 200){
fnSuccess(xhttp.responseText);
}else{
fnError('Http Error',xhttp)
}
}
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
myAJax('server/url',function(data){
//success code here
},function(){
//error code here
});

innerHTML works in IE and Firefox, but not Chrome

The data will not display in Chrome, unless i open an IE tab in Chrome go to the site then close it back to Chrome (sorry, if that doesn't make much sense).
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
Im just starting to learn JavaScript so I really don't know much about it.
You should use some modern Javascript library. It guards you from many of those small differences between browsers. I like jQuery.
So, with jquery your code
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
becomes
$(document).load(function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
$.get(url, {}, function(data) {
$('#sales').html(data);
});
});
Shorter, cleaner and works in all browsers!
I think you want to use:
request.onreadystatechange = function() {
instead of:
request.onload = function() {
And change the way you check the return value.
See the asynchronous request code example here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Using_XMLHttpRequest for more details.
Just find that only the first form tag is removed so you can put an empty form () and the next one is keep in the code.

Javascript Not Executing In Dynamically Loading Content (AHAH)

I'm dynamically loading content into a div when the user clicks a link using this code:
function ahah(url, target) {
document.getElementById(target).innerHTML = 'Opening form...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
This works fine, however I can't get any javascript to work in this new content, such as a jquery datapicker, or even just a document.write hello world. The js in there in the code, just not working. I've loaded the content directly in a browser and it works fine.
I'm at loss, any ideas greatly appreciated!
If you are using jquery anyways, might as well try using jquery.ajax().
You could include whatever scripts you need in the <head> and then call your datepicker or w/e in the callback function of your jquery ajax call.

Categories