Javascript onclick function being called on page load - javascript

I have a simple Javascript function to be called when a button on the page is clicked. But it is getting called as soon as the page loads. Can anyone please tell me what the problem here is?
The HTML is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn">ClicMe!</button>
<div id="demo"></div>
<script src="script.js"></script>
</body>
</html>
While the 'script.js' file is as follows.
var url = "example.txt";
function loadDoc(url, cFunction) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
var btn = document.getElementById("btn");
btn.onclick = loadDoc(url, myFunction);

You must attach an event listener that invoke the function when a user clicks a button:
btn.addEventListener('click', () => {
loadDoc(url);
});

The last line of your script is calling the function instead of assigning the handler to it. Since you have arguments that you want to call it with, you need to use something to bundle the arguments and function together for when it is called. If you replace the last line with the following, it should work:
btn.onclick = loadDoc.bind(undefined, url, myFunction) // "this" value is not needed, so it is left undefined

use an arrow function like this:
btn.onclick = () => loadDoc(url, myFunction);

You are explicitly calling loadDoc() function in your JS file.
You should try this -
var url = "https://jsonplaceholder.typicode.com/posts";
function loadDoc() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn" onclick='loadDoc()'>ClicMe!</button>
<div id="demo"></div>
<script src="script.js"></script>
</body>
</html>

Related

how to show youtube video in an html page with value received via json

I would like your help.
I have to insert a youtube video whose url is received via json; in particular with
document.getElementById("idframe").innerHTML=myJson.Items[4].value;
I get https://youtu.be/ILmvKC-H1l0
So far everything ok. To insert the youtube video in an html page I was following this tutorial.
I just can't get what I want. I get a gray box with the words: It may have been moved, changed, or deleted.
Can you kindly help me?
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style></style>
</head>
<body>
<div>
<div class="video"> <iframe id="idframe" width="420" height="345" src="myFunction()"> </iframe> </div> <br>
<br>
<script>
function myFunction() {
var xmlhttp = new XMLHttpRequest();
var url = "https://vnwcn9gt89.execute-api.us-east-2.amazonaws.com/book";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myJson = JSON.parse(this.responseText);
document.getElementById("idframe").innerHTML = myJson.Items[4].value;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</body>
</html>
Couple of changes required in your code:
You cannot use shortened URL services like https://youtu.be/. Your url should be https://youtube.com/embed/ILmvKC-H1l0
innerHTML won't work for iframe. Try below solution
(function() {
//var xmlhttp = new XMLHttpRequest();
var url = "https://vnwcn9gt89.execute-api.us-east-2.amazonaws.com/book";
/*xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myJson = JSON.parse(this.responseText);
//Your response for myJson.Items[4].value, should be equal to "https://youtube.com/embed/ILmvKC-H1l0"
let youtubeUrl = myJson.Items[4].value;
document.getElementById("idframe").src = youtubeUrl;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();*/
//consider incase you have youtubeUrl as " youtu.be/ILmvKC-H1l0";
//Extract the id and append it like below
let returnedYoutubeUrl = "https://youtu.be/ILmvKC-H1l0";
let id = returnedYoutubeUrl.split("/")[3];
console.log(id);
document.getElementById("idframe").src = "https://youtube.com/embed/"+id;
})();
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style></style>
</head>
<body>
<div>
<div class="video">
<iframe id="idframe" width="420" height="345"> </iframe>
</div>
</div>
</body>
</html>

How to call a function from html button

I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?
Thank you
This is the code,
<html>
<head>
<title>Carrental</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
function delete(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var available = this.responseText;
}
};
xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="delete(9)">Erase</button>
</body>
</html>
delete is an operator. You cannot use it as the name of a variable.
Rename the function.
You need to change the delete to another name function , delete is an operator , you can see the list of operators here : Expressions and operators
function ajaxCall(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var available = this.responseText;
}
};
xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="ajaxCall(9)">Erase</button>
</body>
You cant call the function delete. Just Rename it :)
The problem is delete is operator in JavaScript
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
So your code try to delete the object or element mentioned after it and is not calling method you wrote.
As per example in #Pluto https://stackoverflow.com/a/62086635/124891
You have to rename the method and call it.

How to correctly call variables from within an AJAX function

I am attempting to make a reusable AJAX base to be used in other function within same file. The main purpose with the reusable AJAX base is to minimize the AJAX code, thus reuse the base in other functions.
It works fine when having lines without calling variables. (see lines marked with "these lines works". When attempting to call the AJAX base function from the other function, thus including a variable to pass to AJAX base, it does not work.
Question: Specific to AJAX, how is the correct way of calling external variables from within the AJAX function?
Index.json -file content:
{
"firstName": "John",
"lastName": "Doe"
}
Index.js -file content:
/************************************/
/* Ajax base to fetch external json */
/************************************/
function ajaxBase() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = JSON.parse(xhttp.responseText);
//document.getElementById("boxOne").innerHTML = response.firstName; // This line works.
//document.getElementById("boxTwo").innerHTML = response.lastName; // This line works.
document.getElementById("boxOne").innerHTML = response.[fname];
document.getElementById("boxTwo").innerHTML = response.[flname];
}
};
xhttp.open("GET", "index.json", true); // Define source json data file.
xhttp.send();
}
function changeFirstName() {
ajaxBase(fname = "firstName"); // Passing in variable into function.
}
function changeLastName() {
ajaxBase(lname = "lastName"); // Passing in variable into function.
}
Index.html code:
<!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">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body>
<button type="button" name="button" onclick="changeFirstName()">Change first-Name</button>
<button type="button" name="button" onclick="changeLasttName()">Change last-Name</button>
<div id="boxOne" class="boxOne">First-Name[placeholder]</div>
<div id="boxTwo" class="boxTwo">Last-Name[placeholder]</div>
<script src="index.js"></script>
</body>
</html>
You could try defining two parameters on ajaxBase and checking them inside the function's body. When you call it, assign one of them to null to indicate which value does not need to change.
/************************************/
/* Ajax base to fetch external json */
/************************************/
function ajaxBase(fname, lname) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = JSON.parse(xhttp.responseText);
//document.getElementById("boxOne").innerHTML = response.firstName; // This line works.
//document.getElementById("boxTwo").innerHTML = response.lastName; // This line works.
if (fname !== null)
document.getElementById("boxOne").innerHTML = response.[fname];
if (lname !== null)
document.getElementById("boxTwo").innerHTML = response.[flname];
}
};
xhttp.open("GET", "index.json", true); // Define source json data file.
xhttp.send();
}
function changeFirstName() {
ajaxBase("firstName", null);
}
function changeLastName() {
ajaxBase(null, "lastName");
}

Can't get response using JSON API

I was wondering what I was doing wrong with this code? I'm trying to get the response for PC players from the API to be set to a tag in the html, but this isn't working.
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">
<title>Battlefield 4 Tracker</title>
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<script src="js/jquery-3.1.1.min.js"></script>
</head>
<body>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
var request = new XMLHttpRequest();
var jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
var obj = JSON.parse(jsonResponse);
document.getElementById("response").innerHTML = obj.pc[1].count + "";
</script>
</body>
</html>
Since you are using JQuery as suggested by the html you provided , you can use $.get method of it. This method is a simple wrapper to work with the xmlHTTP asynchronous calls. The success call back of this method is where you should populate the obj with response.
And obj.pc is also an object, so you should access it like obj.pc.count
<!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">
<title>Battlefield 4 Tracker</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>
</head>
<body>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
var request = new XMLHttpRequest();
var obj = null;
var jsonResponse = $.get("http://api.bf4stats.com/api/onlinePlayers", function(response){
obj = response;
document.getElementById("response").innerHTML = obj.pc.count + "";
})
</script>
</body>
</html>
you forgot to send the XMLHttpRequest and what you get back is a object of object so you can call directly obj.pc.count. Try this one:
var json = new XMLHttpRequest();
json.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
json.send(null)
var obj = JSON.parse(json.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
You never sent the request. You're missing request.send(). You then listen for the load event, when you've gotten a response.
Here's an edited version of your code. I assumed that you want to loop through all the types of devices and count them.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
function reqListener () {
//THIS HAPPENS AFTER THE REQUEST HAS BEEN LOADED.
var obj = JSON.parse(this.responseText);
var counter = 0;
for(var k in obj) {
var o = obj[k];
counter += o.count;
}
document.getElementById("response").innerHTML = counter;
}
var request = new XMLHttpRequest();
request.addEventListener("load", reqListener);
request.open("GET", "http://api.bf4stats.com/api/onlinePlayers");
request.send();
</script>
</body>
</html>
You may want to consider other events such as a failed attempt to load the request, etc. Here's more info: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The request is never send send();
The correct way to do this is to handle it in the onreadystatechange event.
Try this (together with a proper check):
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
myFunction(obj);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj) {
document.getElementById("response").innerHTML = obj.pc.count;
}
or directly without extra function:
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
Demo
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
<div id="response"></div>
Try this one :-
<script>
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count + "";
}
};
jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", true);
request.send();
</script>

Ajax Post versus GET

I am trying to implement an AJAX Example which perfectly works with the GET request, but I am not able to transmit via POST. What am I doing wrong ? The POST object received by PHP is always empty. Thanks for any advice!
HTML & JavaScript:
<html>
<head>
<title> Create a new user</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function checkUser(){
xhttp = new XMLHttpRequest();
xhttp.open("POST","usercheck.php",true);
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = xhttp.responseText;
alert("Benutzer" + data);
}
}
xhttp.send("username=" + encodeURIComponent(document.getElementById("username").value));
}
</script>
</head>
<body>
<p>User:</p><br>
<input type="text" id="username" name="username">
<button onclick="checkUser();"> Check </button>
</body>
</html>
PHP Code:
<?php
$usernames = array("admin", "gast", "paul");
$validate_pattern = "/^[a-z0-9]{4,20}$/";
if (!isset($_POST["username"])) {
die("{valid:false,message:false}");
}
if (in_array($_POST["username"], $usernames)) {
die("{valid:false,message:'Username is used!'}");
}
if (!preg_match($validate_pattern, $_POST["username"])) {
die("{valid:false,message:'Username wrong.'}");
}
echo "{valid:true,message:false}";
?>
I found the bug in the code. I missed to set the request header, which was not part of the tutorial unfortunately:
xhttp.setRequestHeader('Content-Type','x-www-form-urlencoded');

Categories

Resources