HTML disappearing after PHP function called - javascript

This displays the result of a button press. The idea is that it reads and writes from a file so that users in different browsers can see the same result.
I had some issues accessing the DOM originally but then discovered that after the first button press, everything below my php script is wiped This area doesn't get shown after button click
The easy workaround is to simply move the DOM element higher up but... I want to know...
Why is this area getting deleted? It's as if it's being treated like PHP.
//Background Loop
function updateChat(){
var file = 'word.txt?v=' + Date.now() ;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
console.log(allText);
document.getElementById("shownword").innerHTML = allText;
}
}
}
rawFile.send(null);
setTimeout(updateChat, 500);
}
<!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>Random Word Generator</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script language="javascript" src="update.js" type="text/javascript"></script>
</head>
<body onload="updateChat();">
<p id=shownword></p>
<form action="" method="post">
<input type="submit" name="word"
class="button" value="Button1" id="button1"/>
<input type="submit" name="word"
class="button" value="Button2" id="button2"/>
</form>
<?php
//This function gets called when button is pushed
function postword(){
$fp = fopen('word.txt', 'w');
fwrite($fp, $_POST['word']);
fclose($fp);
}
//When the button is pushed, the function will be called
if (isset($_POST['word'])) {
postword();
return;
}
?>
This area doesn't get shown after button click
</body>
</html>

Just remove the "return;"
if(isset($_POST['word'])) {
postword();
// return;
}

Related

sending commands/values between pages

im working on a website with 2 pages 1 is the receiver and 2 is the remote basicly you can enter a text on page 2 and once you hit submit page1 starts playing a text to speatch message with the text inut from page2
index.html (aka : page1)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<h1 id="header"></h1>
<script src="src/script.js"></script>
</body>
</html>
control.html (aka : page2)
<body>
<center>
<form>
<h1 style="color:green">Javatpoint</h1>
<h3> Confirm password Validation Example </h3>
<!-- Enter Password -->
<td> Enter Password </td>
<input type = "password" name = "pswd1"> <br><br>
<button type = "submit" onclick="matchPassword()">Submit</button>
<script>
var pw1 = document.getElementById("pswd1");
function matchPassword() {
<script src="script.js"><script> var x1
}
</script>
script.js of page1
const message = 'Hello world' // Try edit me
// Update header text
document.querySelector('#header').innerHTML = message
// Log to console
console.log(message)
var audio = new Audio('notif.mp3');
audio.play();
var msg = new SpeechSynthesisUtterance();
msg.text = "hallo jeremy";
window.speechSynthesis.speak(msg);
i cant find a way to send the text inside page2 to page 1
There are many ways that you could achieve this, but I'll show you just one. You can easily pass data between pages using query parameters, which are essentially pieces of data appended to the end of a URL.
In order to utilize these, you would need to redirect to your index.html page whenever the user presses the button in the control.html page. Fortunately, this can be done by adding an event listener to your Submit button.
Here is the code below:
control.html
<!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" />
</head>
<body>
<form>
<p>Enter stuff here:</p>
<input type="text" id="text-input" name="text" />
<input type="submit" id="submit-button"></input>
</form>
<!-- continue document... -->
<script src="src/control.js"></script>
</body>
</html>
src/script.js
const queryString = window.location.search;
const queryParams = new URLSearchParams(queryString);
const message = queryParams.get("text");
console.log(message);
// continue file...
src/control.js
const button = document.getElementById("submit-button");
button.addEventListener("click", handleText);
function handleText(event) {
event.preventDefault();
const text = document.getElementById("text-input").value;
const currentURL = window.location.pathname;
const currentDir = currentURL.substring(0, currentURL.lastIndexOf("/"));
window.location.replace(currentDir + "/index.html?text=" + text);
}
Hope this helps!

A text is displayed only right after my javascript is triggered

I wrote javascript codes.
By clicking the button, the child window pops up and displays a text sent from the parent window using a postMessage function.
My code could sent a text to the child window, but there's no text displayed.
The text is displayed only when I keep clicking the button. I don't want the text to disappear.
I think my code is overridden by a blank script or something, though I don't write any other codes except for below.
Do you have any solution for this?
the parent window html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Parent Window</title>
</head>
<body>
<input type="button" value="TEST_BUTTON" id="testButton">
<script>
var testButton = document.getElementById('testButton');
testButton.addEventListener('click', function(event) {
event.preventDefault();
var newWindow = window.open('./child_window.html', 'popupWindow', 'width=400,height=300');
newWindow.postMessage('this is a content from the parent window.', '*');
return false;
},false);
</script>
</body>
</html>
the child window html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Pop Up Window</title>
</head>
<body>
<h1 id="mainText"></h1>
<script type="text/javascript">
var mainText = document.getElementById('mainText');
window.addEventListener('message', function(event) {
console.log(event.data);
this.mainText.innerText = event.data;
}, false)
</script>
</body>
</html>
I ended this up using localStorage instead.

How do I let onClick() read from my javascript file?

I have two files index.html and index.js. When I fill the text fields in the form and click the button, it should redirect to index.js. How do I achieve that?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="head">Hello</h1>
<input type="email" id="email"></input>
<br><br>
<input type="password" id="pass"></input>
<br><br>
<button>Click</button>
<script src="index.js"></script>
</body>
</html>
index.js
if (document.getElementById("email").nodeValue==document.getElementById("pass").nodeValue){
alert("You are allowed");
}
EDIT: I can do this simply by creating the function inside the <script> tag itself and then calling the function inside onClick in the <button> tag. But instead, I want the onClick to call my index.js script which will perform the backend stuff
declare this function in index.js
function handleClick() {
if (
document.getElementById('email').nodeValue ===
document.getElementById('pass').nodeValue
) {
alert('You are allowed');
}
}
call it on button click
<button onclick="handleClick()">Click</button>
you should link the html file to the javascript file using
<script type="text/javascript" src="(your file location)"></script>
then add event listeners to listen to the button click using
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("button-id").addEventListener('click', yourFunction)
});
function yourFunction(){
//your code here
}
also add an id to the button so you can add the event listener to it
<button id="button-id">Click</button>
You need to use EventListener to bind button click event to a function.
document.getElementsByTagName('button')[0].addEventListener('click',function(){
if (document.getElementById("email").value==document.getElementById("pass").value){
alert("You are allowed");
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="head">Hello</h1>
<input type="email" id="email"></input>
<br><br>
<input type="password" id="pass"></input>
<br><br>
<button>Click</button>
</body>
</html>
you should add the js file in your index.html
<script type="text/javascript" src="index.js"></script>
then you should add onclick event on your button
<button onclick="myFunction()">Click</button>
then in index.js you should add the function
function myFunction(){
//your logic goes here
}
Always call your script inside js only. It is bad practice to call scripts in the html structure. I gave you an example of calling script logic and accessing a component using querySelector().
var form_button = document.querySelector('.thisisbutton');
var email_input = document.querySelector("#email");
var pass_input = document.querySelector("#pass");
form_button.onclick = function() {
if (email_input.value == pass_input.value){
alert("You are allowed");
}
}
<body>
<h1 id="head">Hello</h1>
<input type="email" id="email">
<br><br>
<input type="password" id="pass">
<br><br>
<button class="thisisbutton">Click</button>
</body>

What element to use onkeydown attribute on?

I want to get run a function when I press the w key, I found some solutions but was not able to figure our where to place that code. Also I want it to be executed no matter when I press w as long as I'm on the same web page.
Here is my code:
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<input type="text" onkeydown="keyPressed()">
</head>
<body>
<div id="screen">
</div>
</body>
<script src="main.js"></script>
</html>
Javascript
function keyPressed() {
// this doesn't run.
}
If I made a mistake then please tell me it and if I didn't make a mistake why doesn't it work?
If I understand correctly you want to "listen" for a keydown event and specifically listen for w.
Below is code that does this without an input.
You will have to click in the window to make it work (on a web page it should work without needing to click in the window.)
function ready(callbackFunction){
if(document.readyState != 'loading')
callbackFunction(ev)
else
document.addEventListener("DOMContentLoaded", callbackFunction)
}
ready(ev => {
console.log('DOM is ready.');
// code above checks that the DOM is loaded and ready
// addEventListener on the window and listen for keydown
window.addEventListener("keydown", function(e) {
// Next 4 lines listen for the key and print it to the screen, not really needed.
let str = "KeyboardEvent: key='" + event.key + "' | code='" + event.code + "'";
let el = document.createElement("span");
el.innerHTML = str + "<br/>";
document.getElementById("screen").appendChild(el);
// this listens for w, add your function in here.
if (event.key == "w") {
alert('You pressed lowercase w');
}
}, true);
})
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Project</title>
</head>
<body>
<main>
Click in this window to make active. <br>
Then keydown and the key & keycode will show. <br>
keydown lowercase w and it will alert.
<div id="screen"> </div>
</main>
</body>
</html>

Checkbox state from HTML (JS) to PHP

I'm new to JS and i want to receive the value from a variable in JS, send it by post (or ajax) to a PHP file, and see the text display. The thing is i've been trying different ways to do it but i always get a undefined index in php.
My code is below
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PRUEBA AJAX JS PHP HTML</title>
</head>
<body>
<H1>prueba</H1>
<input type="checkbox" name="switch" id="switch" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#switch").change(function ()
{
var checked=$("#switch").attr("checked");
if(checked)
{
$("switch").removeAttr("checked");
console.log("estado apagado switch 1");
var estados="1";
$.post("accion.php", {estado: "david"});
}else
{
$("#switch").attr("checked","checked");
console.log("estado encendido switch 1");
var estados="2";
$.post("accion.php", {estado: "david 2"});
}
});
</script>
</body>
</html>
accion.php
<?php
$est = $_POST['estado'];
echo $est;
if ($est=="david") {
echo "no mameees";
}else{
echo "no mameees no se puso ";
}
?>
Someone has any idea ?
$("#switch").change(function () {
var checked=$("#switch").prop("checked");
if(checked)
{
console.log(checked);
}else{
console.log(checked);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Switch <input type="checkbox" name="switch" id="switch" >
Use prop instead of attr to find checkbox is checked or not.
You can let php check if the checkbox was checked or not in a success callback from $.post:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PRUEBA AJAX JS PHP HTML</title>
</head>
<body>
<H1>prueba</H1>
<input type="checkbox" name="switch" id="switch" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#switch").change(function ()
{
var checkbox = $("#switch");
$.post("accion.php", {estado: checkbox.val()}, function(data){
$("h1").html(data);
});
});
</script>
</body>
</html>
accion.php
<?php
$checkbox = isset($_POST['estado']) && $_POST['estado'] == 'on'; // 'on' is the default checkbox value when you don't specify it in html
if ($checkbox) {
echo "it's been checked";
}else{
echo "it wasn't checked";
}
?>
PS: when working with ajax ( check out $.post options) i recommend using dataType: 'json' and your php should respond with a valid JSON, you have json_encode for that.
use
var checked = $('#switch').is(':checked');
instead of
var checked=$("#switch").attr("checked");

Categories

Resources