My Ajax code isn't working. - ajax

"text.txt" is located in the same folder as the html file so that shouldn't be the problem. I want to change the h4 header to the text within the text file
function load_doc(){
var xhttp = new XMLHttpRequest();
xttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
document.getElementById("ajax_example").innerHTML = this.responseText;
}
};
xhttp.open("GET","text.txt",true);
xhttp.send();
}
<div id="ajax_example">
<h4>Request Object</h4>
<button type="button" onclick="load_doc()">Change Text</button>
</div>

have you tried with full path specification?
something like
xhttp.open('GET', 'file:///home/user/text.txt', true);

Related

How to make an id= from an XML call give a link to what its calling?

One of my API calls gives a youtube link and I want the link to be clickable and open on another tab, but nothing is working
this is mode code HTML:
//the id produces a youtube link that that can be clicked, but if I add the id to the href, then it wont work.
<a href="" target="_blank">
<p id="strYoutube2"></p>
</a>
my js code:
//this is my XML call, if theres another .link function other than .innerXML for the youtube link, maybe that can be the issue, but I cant find anything online.
function getPosts() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.themealdb.com/api/json/v1/1/random.php', true);
console.log(xhr.readyState);
xhr.send();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
let response = JSON.parse(xhr.responseText);
console.log('response below:')
console.log(response);
console.log(response.meals[0].strMealThumb);
document.getElementById('strMeal').innerText = response.meals[0].strMeal
document.getElementById('strCategory').innerText = response.meals[0].strCategory
document.getElementById('strArea').innerText = response.meals[0].strArea
document.getElementById('strTags').innerText = response.meals[0].strTags
document.getElementById('strYoutube').innerHTML = response.meals[0].strYoutube
document.getElementById('strMealThumb').src = response.meals[0].strMealThumb
}
}
}
The HTML element with id strYoutube does NOT exist in you provided code:
document.getElementById('strYoutube').innerHTML = response.meals[0].strYoutube
For achieve what you're triyng to do, you can change your code as follows:
Check that I set an img HTML element with a predefined width and height.
Check the working jsfiddle here too:
// This is your function for get the posts of the given API URL.
function getPosts() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.themealdb.com/api/json/v1/1/random.php', true);
console.log(xhr.readyState);
xhr.send();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
let response = JSON.parse(xhr.responseText);
console.log('response below:')
console.log(response);
console.log(response.meals[0].strMealThumb);
// Comented due these HTML elements aren't here.
//document.getElementById('strMeal').innerText = response.meals[0].strMeal
//document.getElementById('strCategory').innerText = response.meals[0].strCategory
//document.getElementById('strArea').innerText = response.meals[0].strArea
//document.getElementById('strTags').innerText = response.meals[0].strTags
//document.getElementById('strYoutube').innerHTML = response.meals[0].strYoutube
//document.getElementById('strMealThumb').src = response.meals[0].strMealThumb
// Here I set the values to your HTML elements:
// "strYoutube" is the HTML anchor element "<a href>".
document.getElementById('strYoutube').href = response.meals[0].strYoutube;
// "myImg" is the HTML image element "<img src>".
document.getElementById('myImg').src = "https://www.themealdb.com/images/media/meals/ysqupp1511640538.jpg";
document.getElementById('myImg').alt = response.meals[0].strMeal;
document.getElementById('myImg').title = response.meals[0].strMeal;
}
}
}
// Call your function and set the values ion the HTML elements:
getPosts();
<a href="" target="_blank" id="strYoutube">
<p id="strYoutube2">
<img src="#" id="myImg" alt="image" title="" style="width: 150px; height: 150px;" />
</p>
</a>

How to complete XMLHttpRequest

I'm making a type of dictionary webpage and I cannot figure out how to get the XMLHttpRequest working. I need to transfer XML information to a specific place in the html, id="data". I'm trying to do it this way so that the page won't have to refresh. The code is very messy I apologize.
<p> <!-- This is the button that will trigger the data appearing -->
<div id="div1" id="buttons" >
<ul class="actions">
<li><input type="button" id="ajaxButton" value="Traditional" class="special"/></li>
</ul>
</div>
<script type="text/javascript">
(function () {
var httpRequest;
document.getElementById("ajaxButton").onclick = function() {
var title = document.getElementById("data").value;
makeRequest('data.xml', word)
}
};
function makeRequest(url, word) {
httpRequest = new XMLRequst();
if (!httpRequest) {
alert('Giving up. Cannot create an XMLHTTP instance');
return false;
}
xmlhttp.onreadystatechange = contents;
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//contents(xmlhttp);
httpRequst.open("GET", url);
httpRequest.send();
}
function contents() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if(xmlhttp.status == 200) {
//This is where the XML should be sent to the HTML
}
</script>
<div id="data">
<!-- XML DATA WILL GO HERE POTENTIALLY -->
</div>
And here is the XML file 'data.xml'
<dictionary>
<word>
<title>Ubiquitous</title>
<trad>This is the traditional defintion ubiquitous</trad>
<simp>This is the simplified defintion hopefully ubiquitous</simp>
</word>
<word>
<title>Lithe</title>
<trad>This is the traditional defintion of lithe</trad>
<simp>This is the simplified defintion of lithe hopefully</simp>
</word>
</dictionary>
May be of your interest to include an asynchronous function between httpRequest.open(...) and httpRequest.send() like this:
//f is your xml file
var fileURL = URL.createObjectURL(f);
httpRequest.open("GET", fileURL);
httpRequest.onload = function(){
URL.revokeObjectURL(fileURL);
populateHTML(this.responseXML);
};
httpRequest.send();
Then create outside a method populateHTML to manipulate what is obtained:
function populateHTML(xmlDoc){
var accessAtr = xmlDoc.getElementsByTagName("trad")[0].childNodes[0].nodeValue;//gets the content of first trad tag.
//use accessAtr to continue writing your "data" id HTML content from here.
}

First AJAX project...(wont load text file inline)

This is my first time working with AJAX, and I cant seem to figure out WHY the .txt file will NOT load? but instead goes to a new page with just that text displayed) ie: not loading in the same page:
my index.html page:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<script src="js/main.js"></script>
</body>
</html>
here is my main.js script:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onClick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.readystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
};
};
})();
alert(message);
in my ajax.txt file.. I just have some random plain text: This is Ajax text to be loaded.
I am NOT running this locally, but through localhost using WAMP web server..
What am I missing? or overlooking here?
Tutorial link: tutsplus.com/lesson/the-simplest-ajax-script
to solve your problem:
Make this replacement to your code:
onClick -> onclick (js is case sensitive)
readystatechange -> onreadystatechange
then put this piece of code out of the onreadystatechange function:
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
This is the new main.js:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onclick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.onreadystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
return false;
};
//open the request
xhr.open("GET", "files/ajax.txt?aiai", true);
//send the request
xhr.send(null);
return false;
};
})();
alert(message);
I think its easier to do it like that:
first, HTML:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<div id="textFiles"><!-- files display here --></div>
</body>
</html>
JS:
<script>
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function loadText() {
var message = "Test";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("textFiles").innerHTML = xmlhttp.responseText;
alert(message);
}
else{
document.getElementById("textFiles").innerHTML = "Loading Files...";
}
};
xmlhttp.open("POST",'files/ajax.txt',true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>

Preview Image before uploading Angularjs

Hi I was wondering if there was a way to preview images before I upload them using angularjs? I am using the this library. https://github.com/danialfarid/angular-file-upload
Thanks. Here is my code:
template.html
<div ng-controller="picUploadCtr">
<form>
<input type="text" ng-model="myModelObj">
<input type="file" ng-file-select="onFileSelect($files)" >
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</form>
</div>
controller.js
.controller('picUploadCtr', function($scope, $http,$location, userSettingsService) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$http.uploadFile({
url: 'server/upload/url', //upload.php script, node.js route, or servlet uplaod url)
data: {myObj: $scope.myModelObj},
file: $file
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
OdeToCode posted great service for this stuff. So with this simple directive you can easily preview and even see the progress bar:
.directive("ngFileSelect",function(){
return {
link: function($scope,el){
el.bind("change", function(e){
$scope.file = (e.srcElement || e.target).files[0];
$scope.getFile();
});
}
}
It is working in all modern browsers!
Example: http://plnkr.co/edit/y5n16v?p=preview
JavaScript
$scope.setFile = function(element) {
$scope.currentFile = element.files[0];
var reader = new FileReader();
reader.onload = function(event) {
$scope.image_source = event.target.result
$scope.$apply()
}
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
}
Html
<img ng-src="{{image_source}}">
<input type="file" id="trigger" class="ng-hide" onchange="angular.element(this).scope().setFile(this)" accept="image/*">
This worked for me.
See the Image Upload Widget from the Jasney extension of Bootstrap v3
// start Picture Preview
$scope.imageUpload = function (event) {
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(file);
}
}
$scope.imageIsLoaded = function (e) {
$scope.$apply(function () {
$scope.img = e.target.result;
});
}
<input type='file' ng-model-instant onchange="angular.element(this).scope().imageUpload(event)" />
<img class="thumb" ng-src="{{img}}" />

Change content of div onclick with Ajax

I want to change the content the div named john to the output from the php file when an image is clicked. I'm sure it's simple but I can't find an example that fits. Here's my code:
function ajaxFunction(){
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send(null);
}
html
<img class='cross' src='images/cross.png' onclick="ajaxFunction();">
<div id='john'>john</div>
test.php
<?php echo "hello"; ?>
Looks to me like you've got a syntax error with your javascript. Your trying to get the responseText from xmlhttp but your XMLHttpRequest is stored in ajaxRequest
Try this
function ajaxFunction(){
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
document.getElementById("john").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send();
}
may I suggest for cross browser/version, use:
var ajaxRequest = getXMLHttpRequest();
and then,
function getXMLHttpRequest() {
var re = "nothing";
try {re = new window.XMLHttpRequest();} catch(e1) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.4.0");} catch(e) {};
try {re = new ActiveXObject("Msxml2.XMLHTTP");} catch(e2) {};
try {re = new ActiveXObject("Microsoft.XMLHTTP");} catch(e3) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.3.0");} catch(ex) {};
if (re != "nothing") {return re;}
else {return null;};
};
as well as changing it to
ajaxRequest.responseText();
I've managed to solve it with the code below. This code also returns the ID of the element after getting "hello" from the php file.
<script language="javascript">
function calldislike(str){
if (str==""){
document.getElementById("john").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true);
xmlhttp.send();
}
</script>
<img src='images/cross.png' onclick="calldislike(this.id);" id='3'>
<div id='john'>john</div>
test.php
<?php echo "hello".$_GET["q"]; ?>

Resources