What causes a function to "freeze" in javascript? - 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.

Related

XMLHttpRequest Preemptively loads json before eventListener click

Currently learning AJAX.
I was testing out XMLHttpRequest to load json when a button is clicked, but it seems to preemptively load the json before any click has happen.
I've also tried using append(this.responseText) to see whether it'll append the json every time i click on the button, but that wouldn't work either.
function loadDoc(str) {
let xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.querySelector("#container").innerHTML = this.responseText;
}
};
xhttp.open('GET', "https://jsonplaceholder.typicode.com/posts/" + str, true);
xhttp.send();
}
let run = document.querySelector('#clickme');
run.addEventListener('click', loadDoc(2));
<html>
<head>
<meta charset="UTF-8">
<title>posts</title>
</head>
<body>
<div id="container">
</div>
<button id="clickme"> click me</button>
</body>
</html>
i have the example on jsfiddle
You're using event listeners wrong. By writing run.addEventListener('click', loadDoc(2)) you are immediately calling loadDoc and then setting its return value as the listener. What you want is to set a function as the listener that will run loadDoc with a value of 2. So you can do this with anonymous functions, by making an anonymous function that calls loadDoc and setting that function as the listener:
run.addEventListener('click', () => loadDoc(2));

Jquery plugin doesn't work when loading with AJAX?

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

How to stream new data to clients browser when index.html change, without the need of refreshing or reloading the web page

I am new on Html. What i need is this.
I have an index.html file on a server which is blank.
I open it and write some text inside the body all the time.
What i want is that when i save the html,
the new data to appear on my clients browser
without the need to refresh or reload the page.
I have no idea on how to do it,so i haven't try anything.
Is it possible? Is it simple?
This is a sample javascript code to read an online url and update the content container with the result.
I couldn't find a simple live update page so used my own website readme in github...
var timeout = 2000,
index = 1,
cancel = false,
url = 'https://raw.githubusercontent.com/petjofi/krivoshiev.com/master/README.md';
function update() {
updateIndex();
load(url, done);
if (!cancel) setTimeout(update, timeout);
}
function updateIndex() {
document.getElementById("index").innerHTML = index++;
}
function done(result) {
document.getElementById("content").innerHTML = result;
}
function load(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
}
<button onclick="update()">start</button>
<button onclick="cancel=true">stop</button>
<span>updating: <span id="index">0</span></span>
<div style="margin-top: 20px" id="content"></div>

How to implement jQuery's load() function in Javascript?

I am making an async call from a webpage to another resource at a url like /example/url/here.html which contains a partial view and inserting the response into the innerHTML of a div on the first page. However, the partial view here.html might contain <script> references and some inline script that doesn't get loaded/run when inserting to innerHTML.
I'm wondering if jQuery's load() function would solve this, and if so how to implement a similar function in javascript, as I cannot use jQuery.
Here's the code I'm using that isn't working:
function (elemId, url) {
var successCallback = function (responseText) {
var elem = document.getElementById(elemId);
elem.innerHTML(responseText);
};
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
successCallback(xmlhttp.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
I think what you want to do is load the html partial via jquery like this:
<div id="partial" ></div>
$('#partial').load('somefile.html');

Turning an OnClick Event Into A Timed Event with JavaScript & AJAX

Im currently in the learning process with AJAX & JavaScript..
I have a quick question to the wise..
How can i turn the code below into a timed event instead of an OnClick event.
**For Example i would like to refresh the "showlist" DIV every 5 seconds...
I understand that this is working code and goes against the rules of the site but if i were to post my non working code it would just confuse things as it has me..
I am trying to slowly understand the basics :)
Any guidance would be greatly appreciated
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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("showlist").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>
</html>
You can change loadXMLDoc function to make use of setTimeout. Consider this example:
function loadXMLDoc() {
var xmlhttp,
timer;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("showlist").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.onerror = function() {
clearTimeout(timer);
};
xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
xmlhttp.send();
timer = setTimeout(loadXMLDoc, 5000);
}
Function issues AJAX request and set up a 5s timeout. I also added basic onerror callback to clear timer just in case.
I once made a kind of tv, which automatically changed the 'screen' after 3 seconds.
Maybe you can re-use my code?
// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array, which is holding the names of the pictures
var myPics = ['img-screen1.png','img-screen2.png'];
// This is looking at how many things the array holds
var totalPics = myPics.length;
// Now this is where the magic begins, this keeps looping around and around, and
// makes sure all the pictures are being showed, one by one.
var i = 0
function loop() {
if(i > (totalPics - 1)){
i = 0;
}
myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
i++;
loopTimer = setTimeout('loop()',3000);
}
loop();
I hope you can re-use this for your project, and I hope you kind of understand what I mean, if I need to clarify, just ask me :).
So what you need to do, is refresh the array when you got new item in your showlist.
This function (if placed inside the same script tag after your loadXMLDoc fn) will execute and call your function and then itself again every 5 seconds (recursively). You could call setInterval instead, but that runs the risk of occasionally missing a cycle if the js engine is busy:
(function doMeSelf(){
setTimeout(function(){
loadXMLDoc();
doMeSelf();
},5000);
})();
Enclosing the function def inside parens, and then followed by () is called an immediately invoked function expression.
See this question for some background: What do parentheses surrounding a object/function/class declaration mean?

Categories