<!DOCTYPE html>
<head>
<title>
Ajax Joke of the Dya application
</title>
<script>
var Request = false;
if (window.XMLHttpRequest) {
Request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
Request = new ActiveXObject("Microsoft.XMLHTTP");
}
function RetrieveJoke(url, elementID) {
console.log("Ret")
if (Request) {
var RequestObj = document.getElementById(elementID);
Request.open("GET", url);
Request.onreadystatechange = function() {
if (Request.readystate == 4 && Request.status == 200) {
RequestObj.innerHTML = Request.responseText;
}
}
}
}
</script>
</head>
<body>
<h1> Where do bees go when they get married?</h1>
<button type="button" value="Fetch Answer" onsubmit="RetrieveJoke('honeymoon.txt','Target')"> ANSWERRR</button>
<form>
<input type="button" value="Fetch Answer" onsubmit="retrieveJoke('honeymoon.txt', 'Target')" />
</form>
<div id="Target"> </div>
</body>
</html>
so it's a simple joke of the day application to learn ajax wherein the the button is supposed to fetch the answer and we deplo ajax for the same
here is the ajax code that's supposed to fetched "Honeymoon!" that's written in honeymoon.txt file when we click on the answer and fetch answer button but it isn't??? Please help
You could just use this function
async function fetchData(path) {
const data = await fetch(path); // Fetching file content
return await data.text(); // Converting it to text and return
}
Then call it like this
const data = fetchData("./myfile.txt"); // Pass your file path here
console.log(data); // This will return your file content
So final answer could be
const button = document.querySelector("button"); // Your button
const result = document.querySelector("#Target"); // Your result div
button.addEventListener("click", function() {
const data = fetchData("./honeymoon.txt");
result.textContent = data;
});
Related
This is my javascript function which is routing a csv file to /uploader.
function getData() {
var csv=document.getElementById('myFile').files[0];
var formData=new FormData();
formData.append("uploadCsv",csv);
var request = new XMLHttpRequest();
//Open first, before setting the request headers.
request.open("POST", "/uploader", true);
//here you can set the request header to set the content type, this can be avoided.
//The browser sets the setRequestHeader and other headers by default based on the formData that is being passed in the request.
request.setRequestHeader("Content-type", "multipart/form-data"); //----(*)
request.onreadystatechange = function (){
if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
console.log(request.response);
}
}
request.send(formData);
}
My python function does get invoked to the app routing part seems to correct. However the request.files length is 0.
This is the python code -
#app.route("/uploader", methods=["POST"])
def post_javascript_data():
f = request.files["uploadCsv"]
print(f)
return "OK"
In the picture below you can see the request.files length remains 0. What am I doing wrong here?
The solution is to not manually set the header for the content type. This is set automatically.
The following is an example with XMLHttpRequest and alternatively with fetch.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- Using XMLHttpRequest -->
<form name="upload-form-1">
<input type="file" name="upload-csv" accept="text/csv" />
<input type="submit" />
</form>
<script type="text/javascript">
(function() {
let form = document.querySelector("form[name='upload-form-1']");
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
let xhr = new XMLHttpRequest();
xhr.open("POST", "/uploader");
xhr.onload = function() {
if(this.status === 200) {
console.log(this.response);
} else {
console.error(`Error ${this.status} occurred.`)
}
}
xhr.send(new FormData(event.target));
},
false);
})();
</script>
<!-- Using Fetch -->
<form name="upload-form-2">
<input type="file" name="upload-csv" accept="text/csv" />
<input type="submit" />
</form>
<script type="text/javascript">
(function() {
let form = document.querySelector("form[name='upload-form-2']");
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
fetch("/uploader", {
method: "POST",
body: new FormData(event.target)
}).then(resp => {
console.log(resp);
}).catch(err => {
console.error(err);
});
},
false);
})();
</script>
</body>
</html>
from flask import abort, make_response, request
#app.route('/uploader', methods=['POST'])
def uploader():
if 'upload-csv' in request.files:
f = request.files['upload-csv']
# Use the object of the type werkzeug.FileStorage here.
return make_response('')
abort(400)
Have fun implementing your project.
I am very new to JS and I have a problem to create a searchable movie reviewer html page, it is very basic, I just want to know how to have the input box search the NYT API for the movie I am looking for, I wont have a problem putting the elements onto the page, I just want to know how to search properly. I expect I need a function that when the search button is clicked it requests from the site all movies with the words provided.
<div id="search">
<input type="text" id = "search">
<button onclick="search()">Search</button>
</div>
<textarea id="APIoutput" cols="90" rows="50"></textarea>
const ISFINISHED = 4;
const ISOK = 200;
var searchedMovie = document.getElementById("search").value;
function getJSONSync(url){
var response = "";
var xmlHttp = new XMLHttpRequest();
if(xmlHttp !== null){
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
response = xmlHttp.responseText;
}
return response;
}
function getJSONAsync(url, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === ISFINISHED && request.status === ISOK) {
callback(this);
}
};
request.open("GET", url);
request.send();
}
function search(searchedMovie){
var my_api_url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=" + searchedMovie + "&api-key=" + API;
return my_api_url;
}
function handleAPIresponse(response) {
var textArea = document.getElementById("APIoutput");
textArea.value = response.responseText;
}
getJSONAsync(my_api_url, handleAPIresponse);
ERRORS: Uncaught ReferenceError: my_api_url is not defined
Expected Results: (UNFORMATTED JSON THAT LOOKS LIKE THIS:)
{"status":"OK","copyright":"Copyright (c) 2021 The New York Times
Company. All Rights
Reserved.","has_more":false,"num_results":10,"results":[{"display_title":"The
Black Godfather","mpaa_rating":"TV-MA","critics_pick":0,"byline":"BEN
KENIGSBERG","headline":"‘The Black Godfather’ Review: The Music
Executive Who Made It All Happen"
I am creating a mini website that has one HTML snippet file to hold just the content that's desired for each internal link in the navigation bar. Each file shall contain the content that shall be inserted into the content placeholder of the template file (index.html).
I have to create a framework JS file with a "make framework" function that has an input parameter which is id of a content div that will be controlled by the framework.
The "make framework" function shall return an object that has a public method that accepts the name of an HTML snippet file and places the content of the snippet file into the content div.
The "make framework" function shall have a private ajax calling function that accepts callback functions as input parameters.
I do not get how to start my framework or how to do it. I have already created my mini website and each button click shows the content. I know that later on I would have to make it so that those button clicks will be moved inside my navigation bar as links instead of buttons.
index.html
<!DOCTYPE html>
<html>
<head>
<title>JS Framework</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="nav">
<div id="title">
<img src="pics/logo.png" width="160" height="39" alt="">
</div>
<div id="navLink">
Home
avdLayout
JS Framework
Labs
</div>
</div>
<br><br><br><br><br><br><br>
<button onclick="sendRequest('aboutUs.html')">cars</button>
<button onclick="sendRequest('aboutCoffee.html')">people</button>
<div id="bodyContent">
Content Area
</div>
<div id="footer">
Web footer
</div>
<script>
// Make a global XMLHttpRequest Object
var httpReq;
if (window.XMLHttpRequest) {
httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera
} else if (window.ActiveXObject) {
httpReq = new ActiveXObject("Microsoft.XMLHTTP"); //For IE 5+
} else {
alert('ajax not supported');
}
function sendRequest(url) {
httpReq.open("GET", url);
httpReq.onreadystatechange = handleResponse;
httpReq.send(null);
}
function handleResponse() {
if (httpReq.readyState === 4 && httpReq.status === 200) {
var response = httpReq.responseText;
document.getElementById("bodyContent").innerHTML = response;
}
}
sendRequest('aboutUs.html');
</script>
</body>
</html>
AJAX file:
function ajaxCall(url, successFn, errorFn) {
// variable/property that's private to fn ajaxCall
var httpReq;
if (window.XMLHttpRequest) {
httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera
} else if (window.ActiveXObject) {
httpReq = new ActiveXObject("Microsoft.XMLHTTP"); //For IE 5+
} else {
alert('ajax not supported');
}
// private function
function sendRequest() {
//alert ('sending request');
httpReq.open("GET", url);
httpReq.onreadystatechange = handleResponse;
httpReq.send(null);
}
// another private function
function handleResponse() {
//alert('handling response');
if (httpReq.readyState === 4) {
if (httpReq.status === 200) {
var response = httpReq.responseText;
//alert ("response text is " + response);
// wrap the json in parentheses to avoid tripping over javascript ambiguity...
response = "(" + response + ")";
var jsonObj = eval(response);
successFn(jsonObj); // we are passing BACK jsonObj to the HTML page
} else {
errorFn(httpReq); // we are passing BACK the whole httpReq object to the
// HTML page, they can extract error codes etc from there.
}
}
} // handleResponse
sendRequest();
} // ajaxCall
html snippet files:
click here
See the Pen jZKWPo by Sofia (#76342ck) on CodePen.
You can create a function that takes ID of the target object and url of the HTML snippet, then calls the url and appends the response to the target object:
function loadUrl(container,url) {
var httpReq;
var output;
if (window.XMLHttpRequest) {
httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera
} else if (window.ActiveXObject) {
httpReq = new ActiveXObject("Microsoft.XMLHTTP"); //For IE 5+
} else {
alert('ajax not supported');
}
function sendRequest(url) {
httpReq.open("GET", url);
httpReq.onreadystatechange = handleResponse;
httpReq.send(null);
}
function handleResponse() {
if (httpReq.readyState === 4) {
if (httpReq.status === 200) {
var response = httpReq.responseText;
output = response; // Result of a successful response
} else {
output = httpReq.response; // Result of a failed response
}
document.getElementById(container).innerHTML = output; // Append the response to the designated container
}
}
// Run the script
sendRequest(url);
}
Then you can use this function wherever you need to retrieve a snippet for your index.html, for example:
loadUrl('contentId','aboutUs.html');
You can see a working example here: https://codepen.io/aydin4ik/project/editor/XqBOqr
I am trying to input the value of the currency using the Value="AUD" as a starter. I am very new to JSON and AJAX. I cannot work out why there is an 404 error linked to JSON.parse and XMLHttpRequest, any advise of where I am going wrong would be much appreciated. Thanks in advance.
`enter code here`
<html lang="en">
<head>
</head>
<body>
<div id ="forex-info">
<p id="currencyList" class="currencyList" value ="AUD">Australia</p>
<p id="rateList" class="event"></p>
</div
<script type="text/javascript">
var tableContainer = document.getElementById("forex-info");
var ourRequest = new XMLHttpRequest();
var myData = "http://api.fixer.io/latest".rates;
ourRequest.open('GET', myData, true);
ourRequest.onload = function loading() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
function renderHTML(data) {
var output = "";
for (var key in data)
{
output += "<p>" + key + output + "</p>"
}
}
};
</script>
</body>
The main issue is how your calling the api "http://api.fixer.io/latest".rates
You call rest endpoints by there address params or with query params.
Please see example below calling your specified endpoint. That should get you started
var myData = 'https://api.fixer.io/latest'
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let res = JSON.parse(xhttp.responseText)
Object.keys(res.rates).forEach((e)=>{
console.log(`${e}: ${res.rates[e]}`)
//Add your stuff here
})
}
};
xhttp.open("GET", myData, true);
xhttp.send();
I have tried to pass on the text from a php page into my html page, as described by Chris Bakers answer (javascript, not jquery).
Call php function from javascript
The code works, if i use the normal text (id=output), but i would like to output the text to a textarea (id=text1) instead of a normal text, just changing the id does not work.
This is my code:
<html>
<head>
</head>
<body>
<textarea id="text1" style="background-color: #969696" cols="50" rows="10" readonly></textarea>
<div id="output">waiting for action</div>
</body>
<script>
function getOutput() {
var value = document.getElementById("artikelnr").value;
var file = selectedValue()+".csv";
getRequest(
"verarbeitung.php?eingabe="+value+"&eingabe2="+file, // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('text1');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('text1');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
</script>
</html>
Because you should use .value instead of .innerHTML.
Reference: JavaScript get TextArea input via .value or .innerHTML?
It is not setInnerHtml, textarea has a value attribute. Not really logical but well...
mad you a fiddle:
document.getElementById("bla").value = "test";
<textarea id="bla" readonly >Initial Value</textarea>