Jquery .get not retrieving file - javascript

i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help

Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>

Related

How do I include jQuery in my js file without html

I made a chrome extension where my popup button calls a script. The other script uses jQuery but I get an error saying jQuery is not defined.
My popup.html:
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
My popup.js:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('record');
login.addEventListener('click', function() {
chrome.tabs.executeScript({file: 'markStudents.js'});
});
});
myScript.js:
var arrays = []
$.get('Attendance.txt', function(data){
var splitted = data.split("\n"); // --> should return an array for each line
// Loop through all lines
for(var i = 0; i < splitted.length; i++)
{
var line = splitted[i];
// Now you could remove [ and ] from string
var removed = line.replace('[','').replace(']','');
var refined = removed.replace(' ', '');
// Now you can split all values by using , delimiter
var values = refined.split(',');
var array = [];
// Now you can iterate through all values and add them to your array
for(var c = 0; c < values.length; c++)
{
var value = values[c];
array.push(value);
}
arrays.push(array);
}
});
var present = arrays[0];
console.log(present);
var absent = arrays[1];
console.log(absent);
var user = present[0];
var pass = absent[0];
var loginField = document.getElementById('fieldAccount');
var passwordField = document.getElementById('fieldPassword');
loginField.value = user;
passwordField.value = pass;
var loginForm = document.getElementById('btn-enter-sign-in');
Is there any way to include my jquery.js in myScript.js?
Console Error
Just import jquery before you import popup.js
Like this
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
Inside Your popup.js, when you load markStudents.js which uses jQuery, you'd again have to load jQuery before same
Like this
document.addEventListener('DOMContentLoaded', function () {
var login = document.getElementById('record');
login.addEventListener('click', function () {
chrome.tabs.executeScript(null, { file: "jquery-3.4.1.min.js" }, function () {
chrome.tabs.executeScript(null, { file: "markStudents.js" });
});
});
});
Just reorder your script tags and put jQuery before your popup.js. That way it will be loaded when you try to call it.
yo can use this code to include another jquery file in your jquery:
$.getScript("file address");
like this:
$.getScript("/assets/pages/scripts/ui-blockui.min.js");

Navigating to specific URL only IF specified ID withing that URL exists

So I have this HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Background</title>
</head>
<body>
<button id="btn" target="_blank" >CLICK ME</button>
</body>
<script src="js/script.js"></script>
</html>
and this JS code
document.getElementById("btn").onclick = function () {
var test=makeid();
window.open("http://www."+test,'_blank');
};
function makeid()
{
var url = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for( var i=0; i < 5; i++ )
url += possible.charAt(Math.floor(Math.random() * possible.length));
return url;
}
How to make client jump to this randomly generated URL only if a div(on the page with generated URL) with id="hehe" exists?If it doesn't exist generate URL again.Is it done using AJAX or something else?

How to add script code using javascript?

I want to add script tag using javascript, but I am not able to get it work. Below is code. I want to add this code in bigcommerce cart page.
var duration = document.getElementsByName("cartdata");
var cartstr = '<!-- MyBuys Page Parameters – Place in <body> element -->';
cartstr += '<script type="text/javascript">';
cartstr += 'mybuys.setPageType("SHOPPING_CART");';
cartstr += 'mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->';
cartstr += 'mybuys.set("amount","99.34");';
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
cartstr += 'mybuys.addCartItemQtySubtotal("'+n[0]+'","'+n[1]+'","'+n[2]+'");'+'<br>';
}
cartstr += '</script>';
cartstr += '<!-- End MyBuys Page Parameters -->';
//alert(cartstr);
var script = document.createElement("script");
script.type = "text/javascript";
script.text = cartstr; // use this for inline script
document.body.appendChild(script);
I want below code added to page:
<!-- MyBuys Page Parameters – Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
This demonstrates how to dynamically add JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var optionalFunctionLoaded = false;
var commonFunction = function() {
console.log("test button clicked " + (new Date()).toLocaleString());
if (!optionalFunctionLoaded) {
// get optionalSrc e.g. via AJAX, eventually providing actual input values
var optionalSrc = 'function optFun(){console.log("optional function");}';
// if optionalSrc is not empty
var script = document.createElement("script");
script.innerHTML = optionalSrc;
document.head.appendChild(script);
optionalFunctionLoaded = true;
}
if(optionalFunctionLoaded) optFun();
}
</script>
</head>
<body>
<button id ="testButton">test</button>
<script type="text/javascript">
document.getElementById("testButton").onclick = commonFunction;
</script>
</body>
</html>
Tested with Firefox 24.0 / Linux.
The solution is to just add the code to the page:
<!-- MyBuys Page Parameters – Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
Why use JavaScript to put it there? Just add it to the page. You might have to adjust it a bit with your loop:
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
You should just be executing the code, there is no need to build the string. In the end, what you are trying to do is the same thing as running the code! Just execute it.
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com");
mybuys.set("amount","99.34");
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
I don't know why would you want to do that. But if you really want to, here is a way you could try.
$('body').append("console.log('blah');")
OR
$('body').html($('body').html()+"console.log('blah');")
Replace console.log('blah') with your code
Note this is assuming you are using JQuery.
If not, you can still use Native Javascript to do something similar. Just search for creating an element and adding it to another using vanila javascript and you'll get lots of information on google.
Although, as epascarello says, its not a good idea to do this. Its basically a code smell and you can improve your code.
Hope this helps.

Can't Append strings from txt file

I am trying to read a local file called start.txt
If I reach a point where the first line is nextpage, it'll do something but if isn't it will append to a textarea. However it gives me an error:
Uncaught TypeError: Cannot read property 'inputtext' of undefined (23:44:44:520 | error, javascript)
at (public_html/index.html:12:50)
The file that I am trying to read is in the same folder as the index.html file. I am fairly new to HTML, AJAX and JavaScript so I might possibly just not know what the frak I am doing!
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js"></script>
<script type="text/javascript">
var txtFile = new XMLHttpRequest();
var inputarea = document.textareaform.inputtext.value;
txtFile.open("GET", "http://localhost/start.txt", true);
txtFile.onreadystatechange = function() {
// Makes sure the document is ready to parse.
if(txtFile.readyState === 4) {
// Makes sure it's found the file.
if(txtFile.status === 200) {
allText = txtFile.responseText;
// Will separate each line into an array
lines = txtFile.responseText.split("\n");
for(i = 0; i < lines.length; i++) {
var s = lines[i];
if(s.indexOf("nextpage") > -1) {
// Line is there
} else {
// Line is not there
inputarea += s;
}
}
}
}
};
txtfile.send(null);
</script>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form name="textareaform">
<textarea name="fileoutput" rows="4" cols="20" readonly="readonly">
</textarea>
</form>
<div>TODO write content</div>
</body>
</html>
It's looking for a textarea named "inputtext", and you've named it "fileoutput".
Try renaming your textarea to "inputtext":
<textarea name="inputtext" rows="4" cols="20" readonly="readonly"></textarea>
or
define your variable differently:
var inputarea = document.textareaform.fileoutput.value;
change the var inputarea declartion to this.
var inputArea = document.getElementsByName('fileoutput');
Hope this helps.

how to generate words onclick?

I am trying to create an html page that contains a title, and when we click on the title it generates words underneath it. But the code I have is only working for the first click, and it's also deleting the title. So my question is, how can I make it generate words under the title without deleting it?
<!DOCTYPE html>
<html>
<head>
<title>function JavaScript</title>
<script>
var k = 0;
function bla(){
var ph = ["red ","blue","black","green","yellow"];
if(k <= ph.length ){
document.write(ph[k]);
k++;
}
}
</script>
</head>
<body>
<h1 onclick="bla();">Click here</h1>
</body>
</html>
Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. This is almost certainly not what you intend to have happen. You should therefore avoid using document.write in situations such as this
so try add a element and then write into them like this
<h1 onclick="bla();">Click here</h1>
<span id="test"></span>
JS:
if(k <= ph.length ){
//document.write(ph[k]);
document.getElementById("test").innerText+=" "+ ph[k];;
k++;
}
JS Fiddle Example
This may be what you need:
var k = 0;
function bla() {
var ph = ["red", "blue", "black", "green", "yellow"];
if (k < ph.length) {
var p = document.createElement('p');
p.innerHTML = ph[k];
document.body.appendChild(p);
k++;
}
}
http://jsfiddle.net/p5rLX/
It will write each word into its own paragraph.

Categories

Resources