Reading a txt file from Server, writing it to website - javascript

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

Related

How to create a Likes button that counts the number of clicks from each visitor

I saw the "likes" function in this demo blog and I'm trying to create a similar button. It seems that once hovering over this heart button, there will be a "finish" class added to the div containing it, so there must be a JavaScript that counts each like. I'd like to make it store each like per visitor (not more) on mouse click and remember it when reloading the page (so I guess there should be a cookie as well?).
It's done with ajax which store data to DB without page refresh and updates the value +1 at the same time
index.html (HTML File)
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<button id="btn">Like</button>
</body>
</html>
script.js (Javascript File)
window.onload = function(){
document.getElementById('btn').addEventListener("click",
function(){
sendLike();
document.getElementById("btn").disabled = true;
});
}
function sendLike(){
var xhr;
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else xhr = new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("GET","like_counter.php?like=1",true);
if (xhr.readyState == 4 && xhr.status == 200) {
//handle what you want to do after the operation is completed here
}
xhr.send();
}
like_counter.php (PHP File)
<?php
if(!(isset($_GET['like'])&&$_GET['like']==1)){
die("Access denied!");
}
//This is just a demo. On a more practical situation,
//you would want to store the likes in a database and verify the authenticity
//of the request to prevent Cross-Site-Request-Forgery
session_start();
if(!isset$_SESSION['likes']) $_SESSION['likes'] = 0;
$_SESSION['likes'] += 1;
echo "done";
?>

AJAX .js file not firing in HTML code

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>

How to load data from an XML file using php to show it in an html page with javascript

I'm doing an assigment for my programming class. I need to show a table with two columns (name and lastname) of a list of friends. This data is stored in a XML file like this:
<?xml version='1.0' standalone='yes'?>
<amigos>
<amigo>
<nombre>Alejandra</nombre>
<apellido>Ponce</apellido>
</amigo>
<amigo>
<nombre>Dalia</nombre>
<apellido>Gordon</apellido>
</amigo>
I retrieve this data with php, like this:
<table width="200" border="1">
<tr align="center">
<td>NOMBRE</td>
<td>APELLIDO</td>
</tr>
<?php
$amigos = simplexml_load_file('listaamigos.xml');
foreach ($amigos->amigo as $amigo) {
echo '<tr>';
echo '<td>',$amigo->nombre,'</td>';
echo '<td>',$amigo->apellido,'</td>';
echo '</tr>';
}
?>
I call this php file with a function written in javascript language. I'm using ajax for this homework. My javascript file is the one I'm showing below:
var xmlHttp;
function createXmlHttpRequestObject() {
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHttp=false;
}
}
else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e)
{
xmlHttp=false;
}
}
if(!xmlHttp)
alert('Can't connect to the host');
else
return xmlHttp;
}
function cargarAmigos(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function cargar(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function procesarEventos()
{
if(xmlHttp.readyState == 4)
{
document.getElementById("listaAmigos").innerHTML= xmlHttp.responseText;
}
}
I use this javascript file in a html file. I call the function cargar () in the button's onclick event, like this:
<body>
<div id="listaAmigos" >
Lista amigos
</div>
<button onclick="cargarAmigos('procedimiento.php');">Lista Amigos Ajax</button>
</body>
The problem is that the code is not working. I mean that the names are not displaying at all in the table. Actually the table does not appear.
I'm pretty sure that the error is not in the code because it was working last week and I haven't changed the code since then. But today I loaded the html page just for "fun" and it wasn't showing my list of friends.
So I decided to open another project with uses the same algorithm and this one is not working too. I've checked that all the files are in the same folder. I've checked my xammp server and it's apache and mysql services are on. I have no idea what "thing" I could have done to cause this problem.
Any help will be really appreciated.
It looks like you should escape the ' character in this line:
alert('Can't connect to the host');
i.e. rewrite it like
alert("Can't connect to the host");
You can see that there's an error even just by looking at the formatting on Stack Overflow :)
Please refer to this question for the details on why it's working like that: When to use double or single quotes in JavaScript?

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.

Popup preview of a textarea using a PHP function

I'd like to make a popup preview of a textarea, using a PHP function inside the popup.
Let's say you type "Hello world" in the textarea, then you click "preview" and you get your text converted to "Hey you" by a PHP function in a popup (of course the function is not that simple, that's the reason why I can't adapt this in pure javascript).
Is it possible to do so ?
I know it could easily send the form to an intermediate page, but I must keep the form in background... that's why I need a quick preview on fly.
I did the following:
function PreviewMe() {
var newWin = window.open("", "_blank");
newWin.document.write("<html><body>"+document.getElementById('myText').value+"</body></html>");
newWin.document.close();
}
and
<textarea id="myText" ... />
<input type="submit" ... onclick="PreviewMe();">
Obviously it works without reformatting anything, so how to reformat this result in the popup please ?
Would it be possible (and mayber a better option) to use XMLHttpRequest ?
Thx !
Yes , you should use an XHR request to send data to a script which will return you data to be manipulated on the client side.
Thanks, it was by far easier in the end.
In case it might help others, here is what I've done.
Js function became :
function PreviewMe() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("XMLHTTPRequest not supported...");
return;
}
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById('show').innerHTML = xhr.responseText;
}
};
xhr.send("var="+document.getElementById('myText').value+"");
return;
}
Of course page.php includes my PHP function, show is the id of the div where the result is printed.

Categories