Calling .js file from HTML using AJAX - javascript

this js is at index.html between "<script type="text/javascript">"
function callanular() {
peticion_http = new XMLHttpRequest();
peticion_http.onreadystatechange = showContent;
peticion_http.open('GET', 'anular.js', true);
peticion_http.send(null);
function showContent() {
if(peticion_http.readyState == 4) {
if(peticion_http.status == 200) {
document.getElementById("notice").innerHTML=peticion_http.responseText;
}
else
document.getElementById("notice").innerHTML="ERROR "+peticion_http.status;
}
}
}
index.html HTML code I have, looking to show box on div with id=notice
<div id="notice"></div>
<input type="submit" value="RESTRICTED ACCESS" onclick="callanular()">
At the same folder I have anular.js created, I want to show a simple box with a text, in this case I only have an alert to know it's working.
window.onload = function() {
return (alert("asdasdsa"));
}
Whatever I write I can only receive the literally code. e.g.
window.onload = function() {return (alert("asdasdsa")); }

You have to include the imported code in a script tag. Adding it to document body in a doc will not work. See answers here
Is it possible to load new Javascript files with AJAX?

So this is how I solved it by using Jquery in first case, AJAX in second case.
First Case
Javascript code on index.html
function callanular() {
$.getScript("anular.js", function(){
//You can write an alert or something
//In my case it wasn't necessary.
});
}
anular.js content
document.getElementById("notice").innerHTML = "<div id='nopul' onclick='getText()'>YOU SHOULDN`T PRESS THIS BUTTON</div><br>";
Back to index.html where I got:
<div id="notice"></div> //here anular.js is going to show the div box
<input type="submit" value="RESTRICTED ACCESS" onclick="callanular()">
At that point it was working fine as I wanted. So I added AJAX to get text from txt file simply doing a call to
XMLHTTPRequest();
peticion_http.open('GET', 'text.txt', true);
-
Second Case
anular.js file
<div id='nopulses' onclick='getTexto()'>YOU SHOULDN`T PRESS THIS BUTTON</div><br>
index.html javascript code
peticion_http = new XMLHttpRequest();
peticion_http.onreadystatechange = showContent;
peticion_http.open('GET', 'anular.js', true);
peticion_http.send(null);
function muestraContenido() {
if(peticion_http.readyState == 4) {
if(peticion_http.status == 200) {
document.getElementById("notice").innerHTML=peticion_http.responseText;
}
else
document.getElementById("notice").innerHTML="ERROR 404 Not Found "+peticion_http.status;
}
}

Related

Changing variable on button-click using JQuery / JavaScript

I am attempting to build a web feature that allows the user to select a window of time to see local Earthquake information, using information found here.
https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php
As you can see here, (https://codepen.io/JoshTheGray/pen/yPmJeR) I am having success parsing the information when I statically assign the url variable for whatever timeframe I want, however I am running into trouble trying to make that url variable change, based on a user button click.
My HTML
<div>Please select a window of time to see Earthquake information.</div>
<br>
<button id="1HourButton">Past Hour</button>
<button id="1DayButton">Past 24 Hours</button>
<br>
<br>
<div id="output1">Earthquakes Around the State<br><br></div>
<br>
My JavaScript / JQuery
;(function($){
$( document ).ready(function() {
// testing document load state
console.log( "document loaded" );
var output1 =document.getElementById('output1');
var hr = new XMLHttpRequest();
// Asigns url based on button choice from user.
var url = '';
$('#1HourButton').click(function () {
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson';
console.log(url);
});
$('#1DayButton').click(function () {
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';
console.log(url);
});
hr.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
var myObj = JSON.parse(hr.response);
for(i=0; i < myObj.features.length; i++) {
if (myObj.features[i].properties.title.includes("Alaska")) {
output1.innerHTML += myObj.features[i].properties.title + '<br>';
}
}
}
}
hr.open("GET", url, true);
hr.send();
});
})(jQuery);
=========================
Currently I am seeing the correct URL information passed to the console upon button click, but the json information is no longer coming through.
What am I missing?

Trying to get the element from a tag after its been updated

I am currently trying to get the values from a element tag after my html tag
"main" has been updated by my java script code to include the html values in another php file.
<main>
<?php include 'index.php'; ?>
</main>
<div id="footer">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="homepage_J.js"></script>
<!--<script type="text/javascript" src="homepage_A.js"></script>-->
</body>
</html>
Above is the relevant part of my php file that contain the html body. My java script code should change the current value of the tag then scan to get certain values of the the newly loaded file.
here is the javascript.
$(document).ready(function(){
$(window).on('hashchange', function(){
var pageHash = window.location.hash.substring(1);
console.log("page hash: "+pageHash);
if( pageHash.length==0){
pageHash = "index";
}
$('main').load(pageHash + ".php", pageFunctions() );
});
$("nav a").on('click', function(event){
event.preventDefault();
var page = $(this).attr("href");
console.log("Loading " + page);
window.location.hash = formatForHash(page);
$('main').load(page, pageFunctions());
});
$(window).trigger('hashchange',pageFunctions());
});
function pageFunctions() {
var current_page = $("#page").text(); //checks to see which file called the javascript
// Switch case that will load appropriate function based on the file loaded(homepage)
switch(current_page){
case "INDEX":
console.log("HOME loaded");
break;
case "INBOX":
console.log("INBOX loaded");
break;
case "REGISTRATION":
console.log("REGIS loaded");
break;
case "COMPOSE":
compose();
console.log("compose loaded");
break;
default:
console.log("ERROR IN :" + current_page );
break;
}
}
function formatForHash (page)
{
var hash = page.split('.');
return hash[0];
}
The console logs were used to help me debug he code. And what i am getting from it is that javascript is return the element form the previous load to main rather than the current values that is loaded to it(what im seeing is not what i am getting).
so the value in var current_page Isn't the page that i am currently on. Its not corresponding. so if i leave from index to compose the value in it is "index", and the reverese would give me a value of "compose".
so my question is how would i get the values of the elements that are currently on the page, after or before a load.
sorry for the lengthy post hopefully i gave it enough detail.
$('main').load(page, pageFunctions());
You are immediately executing pageFunctions rather than giving it as a callback. Take off the () so it will be used as a callback when the load finishes.

Read lines from a file and import as youtube embed to my site

I want to know how to read text file and get the information to a javascript code.
What I mean is,
If I have text file contained with youtube Video-ID and Title
ID:youtubeVideoID1 "Title1"
ID:youtubeVideoID2 "Title2"
ID:youtubeVideoID3 "Title3"
ID:youtubeVideoID4 "Title4"
for example:
ID:gsjtg7m1MMM "X-Man Trailer!"
I want that my web (Index.html) will read the text-file's lines 1 by 1 ,by order,
and show me on my web embed of youtube videos like this:
<img width="143" alt="(TITLE)" src="http://img.youtube.com/vi/(VIDEO_ID)/hqdefault.jpg" >
It need to read and show only the lines that start with "ID:" and the first word after ID is the VIDEO_ID (so it should be a VAR) and after "space" comes the "TITLE" (and it can be a few words in some language) should be a var also..
so If I have only 5 rows in the text file with ID + TITLE, it will show me on the page, only 5 embed videos...
and if there is more, then more...
and if its javascript, what code I need to write on the web so it will show?
Thank You!
hope someone will help me with that..
This seems relatively simple.
First off we need to read the txt file:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
return allText;
}
}
}
rawFile.send(null);
}
var txt = readTextFile("path/to/txt/file.txt");
Then we need to parse the file, so assuming the file looks like above we could do it like this:
var split_txt = txt.split("ID:");
for(var i=0;i<split_txt.length;i++){
var id = split_txt[i].split(" \"")[0];
var title = split_txt[i].split(" \"")[1].slice(0,-1);
$("body").append("<img width=\"143\" alt=\""+title+"\" src=\"http://img.youtube.com/vi/"+id+"/hqdefault.jpg\" >");
}
You will require jQuery to run it.

Insert javascript from an external script into javascript in the HTML

I have some JS from an external JS file that I want to insert inside of a JS function in the HTML file. I can not touch the JS script in the HTML file, so I am wondering if this method can be done.
Here is the JS I want to insert inside of the JS function in the HTML file.
// FIRST JS TO INSERT
if (OS == "mobile"){
killVideoPlayer();
}
// SECOND JS TO INSERT
if (OS == "mobile"){
loadHtmlFiveVideo();
if (!document.all){
flvPlayerLoaded = false;
}
}else {
loadVideoPlayer();
}
Then I want to insert it into here.
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
// INSERT FIRST JS HERE
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("frame_photo").style.display = "none";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "none";
// INSTER SECOND JS HERE
loadVideoPlayer();
}
if (bsiCompleteArray[arrayIndex].mediaType == "photo") {
killVideoPlayer();
document.getElementById("bsi-video-wrap").style.display = "none";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("frame_photo").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "block";
if (!document.all){
flvPlayerLoaded = false;
}
}
}
</script>
Thank you!
In JavaScript, you can overwrite variables with new values at any time, including functions.
By the looks of it, you could replace the mediaTypeCheck function with one of your own that does what you need and then calls the original function.
E.g.
(function(){
// keep track of the original mediaTypeCheck
var old_function = mediaTypeCheck;
// overwrite mediaTypeCheck with your wrapper function
mediaTypeCheck = function() {
if ( conditions ) {
// do whatever you need to, then ...
}
return old_function();
};
})();
The above can be loaded from any script, so long as it happens after the mediaTypeCheck function is defined.
The easiest way for me in the past has been using server-side includes. Depending on your back end, you can set up a PHP or ASP page or whatever to respond with a mime type that mimics ".js".
I'm not a PHP guy, but you'd do something like this: (if my syntax is incorrect, please someone else fix it)
<?php
//adding this header will make your browser think that this is a real .js page
header( 'Content-Type: application/javascript' );
?>
//your normal javascript here
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
//here is where you would 'include' your first javascript page
<?php
require_once(dirname(__FILE__) . "/file.php");
?>
//now continue on with your normal javascript code
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
.......
You cannot insert JS inside JS. What you can do is insert another tag into the DOM and specify the SRC for the external JS file.
You can directly insert js file using $.getScript(url);
if you have script as text then you can create script tag.
var script = docuent.createElement('script');
script.innerText = text;
document.getElementsByTagName('head')[0].appendChild(script);
The issue in your case is that you cannot touch the script in the html, so I'll say that it cannot be done on the client side.
If you could at least touch the script tag (not the script itself), then you could add a custom type to manipulate it before it executes, for example:
<script type="WaitForInsert">
Your question looks some strange, but seems to be possible. Try my quick/dirty working code and implement your own situation:
$(document.body).ready(function loadBody(){
var testStr = test.toString();
var indexAcc = testStr.indexOf("{");
var part1 = testStr.substr(0, indexAcc + 1);
var part2 = testStr.substr(indexAcc + 1, testStr.length - indexAcc - 2);
var split = part2.split(";");
split.pop();
split.splice(0,0, "alert('a')");
split.splice(split.length -1, 0, "alert('d')");
var newStr = part1 + split.join(";") + ";" + "}";
$.globalEval(newStr);
test();
}
function test(){
alert('b');
alert('c');
alert('e');
}

using the method onclick () to trigger a function that opens a window it grabs from the clicked button

<script language="JavaScript">
function goThere()
{
var the_url = window.document.form.button.value;
var good_url = fixURL(the_url);
var new_window = window.open(good_url,"new_window","menubar,resizeable");
}
function fixURL(the_url)
{
var the_first_seven = the_url.substring(0,7);
the_first_seven = the_first_seven.toLowerCase();
if (the_first_seven != 'http://')
{
the_url = "http://" + the_url;
}
return the_url;
}
</script>
</head>
<body>
<form name="the_form" onclick="goThere()"; return false;">
<input type="button" name="the_url" class="broadGroups" onClick="goThere()" value="http://en.wikipedia.org/wiki/Category:Sports"></input>
<input type="button" name="the_url" class="broadGroups" onclick="goThere()" value="http://en.wikipedia.org/wiki/Category:Film"></input>
</form>
</body>
</html>
So this code may be totally messed up, but here is what I am trying to do.
There are two buttons inside the tag. I want each to use the method onsubmit to trigger the function goThere(). How do I set it up so that the_url is set to a value that I pull from the button tag. I also want to be able to put non-url text on the button itself while allowing it to call goThere () through the method call onsubmit.
In the end it should just take the url, make sure it starts with http:// (in this case it doesnt matter because the user isn't inputting the url, but I'd like to keep it in for other purposes later on) and open it in a new window with a menubar and the resizable property.
Sorry for the long post. Any help would be greatly appreciated.
Pass in this in your goThere call. This will bring in the clicked element to your goThere function. Then you access the attributes for the clicked button.
http://jsfiddle.net/wJMgb/
onClick="goThere(this)"
function goThere(elem) {
var the_url = elem.value;
var good_url = fixURL(the_url);
var new_window = window.open(good_url, "new_window", "menubar,resizeable");
}
function fixURL(the_url) {
var the_first_seven = the_url.substring(0, 7);
the_first_seven = the_first_seven.toLowerCase();
if (the_first_seven != 'http://') {
the_url = "http://" + the_url;
}
return the_url;
}

Categories