AJAX .js file not firing in HTML code - javascript

I'm relatively new to JS, and I'm currently working on XMLHttpRequests and closures. My main goal is to (1) have all the xhr code on one .js file (2) pull it in to my index.html page via an src tag, and finally (3) call the xhr function on the index.html page.
The trouble comes when I try to do number 3... I'm able to call my function to trigger the xhr on its native .js file, but not in the index.html.
Here's what I've written so far:
var experiment = function(callback){
return function(destination){
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
var text = xhr.responseText;
callback(text);
}
else{
console.log(xhr.statusText);
}
}
}
xhr.open("get", destination, true);
xhr.send(null);
}
}
function closure(url){
return experiment(alert)(url);
}
And then, in my index.html page, pull in something like this:
<script type="text/javascript" src="exp.js">
closure("url.com/json");
</script>
But the XHR never fires. What am I doing wrong?

<script type="text/javascript" src="exp.js"/>
<script>
closure("url.com/json");
</script>

Related

Running a script added after the page has loaded

I need to add the pages later for my project, but after adding the script tag at the bottom is not executed.
Main
const fetch = (url, call) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
call(xhttp);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
const UpdatePage = page_name => {
fetch(`/app/${page_name}`, (data => {
App.innerHTML = data.responseText;
}))
}
Code of new page
<div>
<%= showId %>
</div>
<script>console.log("Welcome to somewhere")</script>
Page loads sucessfuly but the javascript not be executed. How i can execute the script tag on new page added?
I didn't really understand your question.
From what I did though you want to run the script after the page has loaded.
For that you can use the defer tag
<script src="script.js" defer></script>
Read this MDN article for more info.
You must call the function
fetch();
UpdatePage();
Before doing this, you must call your file js in the ejs file

I Need create an html page that reads a XML file in a CD-R. How I can do that?

I made an html website that will be running in a CD-R (this will be a manual).
I have the page created and everything is working good, but at this moment I'm having some problems for opening a XML file.
My question is, is this possible, since It will be running in a CD Drive?
Thank you
This is what I have:
function testing()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "teste.txt", true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
var allText = rawFile.responseText;
alert(allText);
}
else
alert("erro no xml");
}
rawFile.send();
}
This works fine in for example: localhost/path
But i want it to work in a path like c:\path\
If you don't mind modifying your source files a little bit by turning it into JSON, you could use JSONP. Here's a simple example:
<button onclick="go();">Click me</button>
<script type="text/javascript">
function go() {
var scriptTag = document.createElement("script");
scriptTag.src = "someText.js";
document.getElementsByTagName("body")[0].appendChild(scriptTag);
}
function jsonCallback(txt) {
console.log(txt);
}
</script>
File: someText.js:
jsonCallback("Hello World!");

What is wrong with this code using ajax?

I'm new to coding and now I'm trying to write a code that gets the text data form a file and replace the present text with the new one. I'm using AJAX to do the task but the problem is first I'm getting the error message and then expected answer The error message is what I have included in the code to display when there is error. Even though i'm getting the desired answer I want to know why the error message is displayed. Here is my code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script>
function loadXML() {
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("p1").innerHTML = xmlhttp.responseText;
}
else {
alert(" there is a error in your code");
}
}
xmlhttp.open("GET","robots.txt", true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<p id="p1">This is Text</p>
<button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>
The problem is your if-block in onreadystatechange. During the request and response, xmlhttp.readyState changes multiple times and onreadystatechange is called every time this happens.
If you do it like this, it may work:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
} else {
alert(" there is a error in your code");
}
}
It is simpler, however, to use the other event-methods like onload and onerror, as described here.
1- include 1 jQuery file jquery-1.9.0.js same as jquery-1.9.0.min.js but jquery-1.9.0.min.js is minified file
2- what is the Error message from javaconsole log ?
3- you are using jQuery so why you are working with XMLHttpRequest when jQuery $.get already using best of HttpRequest for all browsers
you can replace your JS code with this
<script type="text/javascript">
$( document ).ready(function() {
$.get('robots.txt',function(data){ $('#p1').html(data) });
});
<script>
Are you using a webserver ? Ajax doesn't work from local file url : 'file://...'
alert(" there is a error in your code");
Actually there is no error in your code. xmlhttp.onreadystatechange is called in different states of the request. Thats why you check for xmlhttp.readyState == 4. Learn more about the different stages here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
So your code is running fine, you just alert an error message, that is not an error at all.

Reading a txt file from Server, writing it to website

Here's my problem.
1) I'm wanting to create a txt file (or possibly a html file) to hold a paragraph of information to be written onto a when a user clicks a word. It's part of a game I am working on.
If you go to www.w3schools.com and go to their "try it" editor they have...
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp = XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
p = document.createElement("p");
p.innerHTML=xmlhttp.responseText;
document.getElementById("story").appendChild(p);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="story"><h2>Let AJAX <i onclick=loadXMLDoc()>change</i> this text</h2></div>
</body>
</html>
This is exactly what I want my program to do (not the actual words of course) but I'm running html with an external .js sheet. Should I store my ajax somewhere else? Or, should my .txt file look different than just a bunch of words in it? I'm completely confused.
The fun part will be once this actually starts working, I'm going to have to implement an "onclick" event with italics inside of the txt file.
If there is a better way to do this then appendChild(p.innerHTML("lfjhdfh")) and AJAX please let me know asap. I have a total of 11 weeks to get this thing working for a school project LOL.
Try this, it just appends the text to the HTML of the body element:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange();
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
function ajax() {
getFileFromServer("Test.txt", function (text) {
if (text === null) {
// An error occurred
} else {
document.body.innerHTML += test;
}
});
}

get full html source code of page through ajax request through javascript

The javascript code will be launched from www.example.com through the url bar in google chrome so i cannot make use of jquery. My goal is to pass the full html source code of www.example.com/page.html to a variable in javascript when i launch the code in www.example.com. Is this possible? If so how? I know to get the current page source it's just document.documentElement.outerHTML but i'm not sure how i'd do this. I think it's possible by using responseText somewhere in the following code:
http.send(params);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.example.com/page.html",true);
xmlhttp.send();
data = ""
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
data = xhr.responseText
}
}
xhr.send();
function process(){
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
}
xhr.send();
}
this is how i run script from the address bar.. I do it all the time..
i create a bookmark like this
javascript:script=document.createElement('script');script.src='http://10.0.0.11/clear.js';document.getElementsByTagName('head')[0].appendChild(script); void(sss=1);
then i host the js file on my computer.. i use analogx simpleserver... then you can use a full page for your script

Categories