I am trying to implement an ajax with simple txt file but the file won't load any suggestion
the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
xhr.send();
}
}
and this is the sample.txt file
This massage form the text file just to ensure you have the ability to
access the text file. so if you do good for you otherwise just keep
trying
Note, I'm trying to achieve it using vanilla javascript without any frameworks or library
As an output I get nothing once I click the button and even in the network tab in the inspector the txt file never even load.
Note, I'm using live sever on vscode
xhr.send() should be outside xhr.onload()
xhr.onload() is the callback function to be executed when the request completes successfully.
refer the docs here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
}
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>
Related
I had similar code run before but now i've lost it. No matter what I do, it will never run the php code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}
I'm looking how to submit submit an input field made with JavaScript.
I want to submit the value of the input fields made with JavaScript with the POST method to a file called "home.php". But I didn't find any possible way to do that, I hope someone helps me. I've included the full source code. I'll be really thankful for any help.
Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
<base target="_parent">
<script>
if (window.parent !== window) {
try {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__;
} catch (error) {
// The above line can throw if we do not have access to the parent frame -- i.e. cross origin
}
}
</script>
<title>Storybook</title>
</head>
<body>
<div id="root"></div>
<div id="error-display"></div>
<script type="text/javascript" src="http://yourjavascript.com/2560291117/preview-0c18dfe69fe4ef4a04bd-bundle.js"></script></body>
</html>
Instead of messing up with POST or GET requests you can just use the built-in document.querySelector('#YourIdHere)
The # sign is important as it means that it's an id.
Also, you can add a submit button and fetch the website using the:
fetch('urlHere', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data)
)
Is that good?
With input fields it looks something like that:
<html>
<body>
<input id='input' type="text" value="">
<button onclick="submit()">Submit!</button>
<p id="title">Your text here!</p>
<script>
function submit() {
const query = document.querySelector('#input').value;
const title = document.getElementById('title');
console.log(query);
console.log(title.innerHTML = query);
}
</script>
</body>
</html>
And using requests:
<html>
<body>
<button onclick="submit()">Submit!</button>
<script>
function submit() {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.response);
};
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.send();
};
</script>
</body>
</html>
We have an Ember (3.5) application. For technical reasons we need environment variables to be set on page load, as opposed to build time. We're trying to set them in index.html the following way:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>App</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{content-for "head"}}
<script type="application/javascript">
// Object.assign polyfill
Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:function(e,r){"use strict";if(null==e)throw new TypeError("Cannot convert first argument to object");for(var t=Object(e),n=1;n<arguments.length;n++){var o=arguments[n];if(null!=o)for(var a=Object.keys(Object(o)),c=0,b=a.length;c<b;c++){var i=a[c],l=Object.getOwnPropertyDescriptor(o,i);void 0!==l&&l.enumerable&&(t[i]=o[i])}}return t}});
window.env = {};
var request = new XMLHttpRequest();
request.open('GET', '/api/frontend_settings', true);
request.send(null);
request.addEventListener('readystatechange', () => {
if (request.status === 200) {
if (request.readyState === 4) {
Object.assign(window.env, JSON.parse(request.response).settings);
}
}
}, false);
</script>
<link integrity="" rel="stylesheet" href="{{rootURL}}assets/vendor.css">
<link integrity="" rel="stylesheet" href="{{rootURL}}assets/app-frontend.css">
{{content-for "head-footer"}}
</head>
<body>
<script integrity="" src="{{rootURL}}assets/vendor.js"></script>
<script integrity="" src="{{rootURL}}assets/app-frontend.js"></script>
</body>
</html>
We added a script which makes a request to some endpoint (/api/frontend_env_vars) in the snippet. This endpoint responds with a JSON with the key-values of environment variables which we then assign to window.env.
The problem we have is that sometimes Ember scripts load before the variables have been assigned (since we do a request that takes some time to complete), which makes the application crash.
We tried the following alteration to the script, but it didn't work (the error was different, though):
<script type="application/javascript">
// Object.assign polyfill
Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:function(e,r){"use strict";if(null==e)throw new TypeError("Cannot convert first argument to object");for(var t=Object(e),n=1;n<arguments.length;n++){var o=arguments[n];if(null!=o)for(var a=Object.keys(Object(o)),c=0,b=a.length;c<b;c++){var i=a[c],l=Object.getOwnPropertyDescriptor(o,i);void 0!==l&&l.enumerable&&(t[i]=o[i])}}return t}});
window.env = {};
var request = new XMLHttpRequest();
request.open('GET', '/api/frontend_env_vars', true);
request.send(null);
function loadScript(src) {
const script = document.createElement('script');
script.src = src;
document.body.append(script);
}
request.addEventListener('readystatechange', () => {
if (request.status === 200) {
if (request.readyState === 4) {
Object.assign(window.env, JSON.parse(request.response).settings);
loadScript('assets/vendor.js');
loadScript('assets/app-frontend.js');
}
}
}, false);
</script>
We accomplish this using ember-cli-server-variables
Which allows you to define variables in index.html
<html>
<head>
<meta name='your-app-token' content='example:app:token'>
<meta name='your-app-user-location' content='Denver'>
<meta name='your-app-json-data' content='{"foo":"bar"}'>
</head>
</html>
and then access them from the application.
We build our index.html on the server with the needed variables to there is no async needed to fetch them.
In my express application my root file app.js rendering a.html in 'a' folder but a.html is not responding to any ajax code written in ajax.js. I've shown these files below-
app.js
var express = require('express');
var app = express();
app.set(express.static('./a'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/a/a.html');
});
app.listen(3000, '127.0.0.1');
a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="button"></button>
<script src="ajax.js"></script>
</body>
</html>
ajax.js
document.getElementById('button').addEventListener('click', trigger);
function trigger() {
var xhr = XMLHttpRequest();
xhr.open('GET', 'blah.txt', true);
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.send();
}
Here I'm providing some screenshots of directory and result
Directory
End Result
The file that you are trying to load by ajax is blah.txt, whereas the file in a directory is blah without extension, try to rename it to blah.txt or remove .txt extension from the ajax url:
xhr.open('GET', '/blah', true);
On iOS11 safari browser (iOS10 and below works), if I tab away and come back, sometimes audio file doesn't play. If I keep tabbing away and back, it eventually plays - but it batches all the play calls and attempts to play all at one.
I created a very simple testing page. Does anyone know why?
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,minimum-scale=1,maximum-scale=1"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no" />
<style>
button { font-size:2em; }
</style>
<script>
var g_context, g_buffer;
function play() {
if (g_buffer) {
var source = g_context.createBufferSource();
source.buffer = g_buffer;
source.connect(g_context.destination);
source.start(0);
}
}
function ready(){
g_context = new webkitAudioContext();
var req = new XMLHttpRequest();
req.open("GET", "<*** insert your sound file path here ***>", true);
req.responseType = "arraybuffer";
req.onload = function(){
g_context.decodeAudioData(req.response,function(buffer){
g_buffer = buffer;
}, function(e){});
};
req.onerror = function(e){
console.log("fail to load", e);
};
try{req.send()}
catch(e){}
}
</script>
</head>
<body onload="ready()">
<button onclick="play()">play</button>
</body>
</html>