javascript - can ajax call triggering onload event on the targeted page? - javascript

i wanna know can ajax call triggering onload event on the targeted page?
so it's like this, i have one page (test.html) with simple function to change the content of a div that will run when the page load...
here is the code :
<body onLoad = "a()">
<div id="main">the result is here</div>
</body>
<script>
function a()
{
document.getElementById("main").innerHTML =
"Success";
}
</script>
and i have another page (call.html) with ajax call targeted test.html and show the result inside the div...
here is the code :
<body>
<button onclick="call()">Click</button>
<div id="box"></div>
</body>
<script>
function call()
{
var xmlhttp = new XMLHttpRequest();
var url = "test.html";
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("box").innerHTML =
xmlhttp.responseText;
alert("Success");
}
}
xmlhttp.send();
}
</script>
if i just simply load the test.html, the content inside div will change, but if i use call.html to call that page, the inside won't change...
is this because ajax doesn't trigger function inside onload event?

This is happening because you are trying to open a URL from local i.e. using file:// and not via HTTP or HTTPS.
This thread can give you a better insight on how to proceed further.

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 reloading incorrectly

I am making a little script to change website language using PHP and Ajax/jQuery. I want page content to refresh without reloading page. Until now i have made this
$( "a[data-request]" ).click(function() {
var xhr = new XMLHttpRequest();
var request = $(this).attr('data-request');
var what = $(this).attr('data-to');
xhr.open('GET', '{{ site_url }}' + what + '/' + request);
xhr.onload = function() {
if (xhr.status === 200) {
$("#body").load(location.href + " #body");
}
};
xhr.send();
});
When i click on link
<a data-request="english" data-to="home/language" href="#">
It succesfuly performs uri request in background and "reloads" #body element, which is whole body
<body id="body">
However instead of reloading whole page content just disappear and wont reappear again. What am i doing wrong?
Replace xhr.onload because it's not implemented in all browsers, use onreadystatechange instead
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200;
if (xhr.readyState === DONE) {
if (xhr.status === OK)
$("html").html(xhr.response);
}
};
xhr.open('GET', '{{ site_url }}' + what + '/' + request); //<-- note must come after above event handler
note : this would wipe your button too(one you clicked to fetch the page).so instead of body load that data in some div.
EDIT
I suppose your code is something like this
$(document).ready(function(){
$(langDropdown).change(function(){
//get selected language
//do ajax
});
});
Now suppose you change lang. to Spanish server sends you a Spanish version so what you get from server is bit like
<html>
<head> ....title.....
<script src=....></script> //common libs like jquery etc
<script src=my.js></script> //this would be js contaning above code
</head>
<body>
Esta es una pagina
</body>
</html>
Now when you use document.write to put the Italian page the document.ready won't get called(why? because it gets called only on actual page refresh) so change event handlers wont get bound on lang. selection dropdown
Solution:
code outside document.ready will definitely run even when fetched through ajax, but i won't advise that , rather what i would advise is whatever code you want to run on ajax completion (like event binding) write it after document.write is success callback/readyState
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200;
if (xhr.readyState === DONE && xhr.status === OK) {
$("html").html(xhr.response);
$(langDropdown).change(function(){
//binding code
});
}
};

onreadystatechange only called when blocked by alert()

I have a simple javascript html file that I am using to perform a function that is called from menu item that I added to the Internet Explorer default context menu (through windows registry). The menu click triggers the following javascript:
<script type="text/javascript">
var req = new ActiveXObject("Microsoft.XMLHTTP")
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var serverResponse = req.responseText;
alert(serverResponse); // Shows "15"
}
}
};
req.open("POST", "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey", true)
req.setRequestHeader("Content-Type","application/json")
req.send('{"longUrl": "https://bing.com"}')
</script>
If I run this by opening the html file in IE it works fine. I get the response text. However, if I load it through the Context Menu the "onreadystatechange" function is never called.
If I add "alert("test") to the end of my script the test alert pops up followed a fraction of a second later by the serverResponse alert. I assume it has something to do with the alert blocking or forcing the browser to do something but I can't figure out why it works when loaded as a page but not through the Context menu.
I should note that the rest of the script DOES get called, so I know the menu item is working.
EDIT:
The above code snippet runs and displays an alert dialog containing the text of the response from the server whenever it's executed as an html page. If executed through the context menu I never get the "alert(serverResponse)".
However the following version does work when called from the context menu:
<script type="text/javascript">
var req = new ActiveXObject("Microsoft.XMLHTTP")
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var serverResponse = req.responseText;
alert(serverResponse); // Shows "15"
}
}
};
req.open("POST", "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey", true)
req.setRequestHeader("Content-Type","application/json")
req.send('{"longUrl": "https://bing.com"}')
alert("test")
</script>
The only difference is the inclusion of the "alert("Test")" line at the end

Tips for webpage designing

I added a button to open respective information. Then I put all the information in another page. I want to open the selective information in the first of the page when button is clicked of that information.
Is it possible?
I don't want to use jquery.
Please help me to solve this problem.
<button onclick="loadInfo()">Get Information</button>
<div id="myDiv"></div>
so when the user click on that button it will fire the loadInfo()function
function loadInfo() {
var xmlhttp= new XMLHttpRequest();
xmlhttp.open("GET", '/path/to/your/respective/information.file',true); //modify this line to your information file path
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status==400){
document.getElementById("myDiv").innerHTML= xmlhttp.responseText; //your information will be loaded inside myDiv
}else{
console.log('error')}
}
}
xmlhttp.send();
}

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

Categories