Change inner HTML based on PHP return - javascript

I have a simple web page with a form consisting of a text entry box and a button. The onclick event of the button fires a script in the head. The script calls a separate PHP page, and checks the submitted text. If the value is "foo" it should say correct, if it's anything else it should say incorrect.
No matter how I tweak it, I can't get anything to show up in the inner HTML of the div with the id of response_one. I'm working off of the W3Schools tutorial found here but just can't seem to make this work. I've included the html / PHP below, any pointers would be greatly appreciated.
The HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>See</title>
<script>
function show(str) {
if (str.length == 0) {
document.getElementById("response_one").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response_one").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "check_one.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="mainbody">
<form>
Answer: <input type="text" name="answers">
<input type="submit" onclick="show(this.value)">
</form>
<div id="response_one"></div>
</div>
</body>
</html>
and check_one.php:
<?php
$q = $_REQUEST["q"];
$q = strtolower($q)
$result = ""
if ($q === "foo") {
$result = "Correct";
} else {
$result = "Incorrect";
}
echo $result
?>

Problems
Multiple problems here:
Your button is a submit input. On click, your browser will submit the form. None of your AJAX would matter because the page will refresh before you see any result.
Your button does not hold the value. The input field <input type="text" name="answers"> does. It is a mistake to run show(this.value) because you don't really plan to check the submit button's value.
There are multiple syntax error in your check_one.php file. Please run command line php -l check_one.php or use browser to browse check_one.php?q=foo to check it.
Quick Fix
I'll leave the php syntax error to you and focus on your form. Here is how I'm going to fix it:
Change the submit button from <input type="submit"> to <button type="button">. This will prevent form submission on click.
Alter the onClick function to access the value of your text input answers instead of this.value.
The Code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>See</title>
<script>
function show(str) {
if (str.length == 0) {
document.getElementById("response_one").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response_one").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "check_one.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="mainbody">
<form>
Answer:
<input type="text" name="answers">
<button type="button" onClick="show(this.form['answers'].value)">Check</button><!-- only this line is changed -->
</form>
<div id="response_one"></div>
</div>
</body>
</html>
Once you fixed your check_one.php, you'll get your desired result.
Room for Improvement
There can still be problem with your form. If the user press "Enter" instead of clicking the button, your form will be submitted. So instead of just intercepting the click event of the button, you'd be better off capturing the form's submit event.
So here are the improvements:
Add an id attribute to your form.
Use document.getElementById to find the form and intercept the submit event.
Use event.preventDefault() to prevent form submission.
Find the answers value and do the XMLHttpRequest.
The Code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>See</title>
</head>
<body>
<div id="mainbody">
<form id="check-form"><!-- added id="check-form" -->
Answer: <input type="text" name="answers">
<input type="submit"><!-- removed onClick attribute -->
</form>
<div id="response_one"></div>
</div>
</body>
<script>
// Moved script after body so the form element would exist before
// this script is run.
document.getElementById('check-form').addEventListener('submit', function (evt) {
evt.preventDefault(); // prevent form submission
var str = evt.target["answers"].value; // get the answers field value
// The logics previously in your `show()` function
if (str.length == 0) {
document.getElementById("response_one").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response_one").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "check_one.php?q=" + str, true);
xmlhttp.send();
}
});
</script>
</html>

It seems you have forgot some of the ";" at the end of the code. How about
<?php
$q = $_REQUEST["q"];
$q = strtolower($q)
$result = ""
if ($q === "foo") {
$result = "Correct";
} else {
$result = "Incorrect";
}
echo $result
?>
To
<?php
$q = $_REQUEST["q"];
$q = strtolower($q);
$result = "";
if ($q === "foo") {
$result = "Correct";
} else {
$result = "Incorrect";
}
echo $result;
?>

Related

$_POST not returning a value

I've been searching for an answer to this for several days now, but if I missed the answer in another post, let me know.
I'm trying to get into Ajax, so I have a very simple form in my index.php, with separate php and javascript files:
index.php
<div id="ajax-test">
<form action="ajax/ajax.php" method="POST">
<textarea name="someText" id="some-text" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
main.js:
function getXMLHttpRequestObject() {
var temp = null;
if(window.XMLHttpRequest)
temp = new XMLHttpRequest();
else if(window.ActiveXObject) // used for older versions of IE
temp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
return temp;
}// end getXMLHttpRequestObject()
function loadDoc() {
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
};
ajax.open("POST", "ajax/ajax.php", true);
ajax.send();
}
ajax.php:
<?php
print_r('\'' . $_POST['someText'] . '\' is what you wrote');
?>
Whenever I try to print, it prints: " '' is what you wrote " - what am I missing/not doing/doing incorrectly that isn't allowing me to access the content of someText? I've changed my naming convention, swapped from single quote to double quote, tried GET instead of POST, but nothing worked.
You can try to set a header request and also put the data inside the send. Here an example as like as-
ajax.open("POST", "ajax/ajax.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send("someText="+document.getElementById('some-text').value);
This is probably beacuse of the error
Undefined index: someText in C:\xampp\htdocs\ssms\sandbox\ajax\ajax.php on line 3
You had a couple of issues with your code which i don't have time to list out now. This should work fine, plus i used the onkeyup() function to display the text live without even clicking on the submit button.
The Index File
<div id="ajax-test">
<form method="POST" onsubmit="return false;">
<textarea onkeyup="loadDoc()" name="someText" id="someText" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
<script type="text/javascript" src="main.js"></script>
The Main Javascript file
function _(x) {
return document.getElementById(x);
}
function ajaxObj ( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function loadDoc() {
var someText = _("someText").value;
var ajax = ajaxObj("POST", "ajax/ajax.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
}
ajax.send("someText="+someText);
}
The PHP AJAX File
if(isset($_POST['someText'])){
$someText = $_POST['someText'];
echo "\"$someText\"" . ' is what you wrote';
exit();
} else {
echo "An error occured";
exit();
}

Ajax GET Request is duplicating page

I have been reading up on Ajax and am following along on W3Schools.com. I am using Ajax/PHP/MySQL. So far I've gotten the request to successfully query my database based on a button selection, however it's reprinting my entire page when I click on one of the buttons.
Here is the Ajax code:
<script>
function statusShow(status) {
if(status == "") {
document.getElementById("exams").innerHTML = "";
return;
} else {
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("exams").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "rspamanager.php?st="+status, true);
xmlhttp.send();
}
}
</script>
And this is part of the PHP that is printing a table
if(isset($_GET["st"])) {
$st = mysqli_real_escape_string($connection, $_GET["st"]);
} else {
// default status
$st = "open";
}
if($connection) {
$query = "SELECT * FROM exams WHERE status = '{$st}'";
$sth = mysqli_query($connection, $query);
while ($result = mysqli_fetch_assoc($sth)) {
etc ...
This is all in the same php file "rspamanager.php".
EDIT: Button code:
<button onclick="statusShow(this.value)" value="open" class="status_open">Open</button>
<button onclick="statusShow(this.value)" value="closed" class="status_closed">Complete</button>
My test document seems to work just fine, added no-cache options, otherwise seems ok.
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<script>
function statusShow(status) {
if(status == "") {
document.getElementById("exams").innerHTML = "";
return;
} else {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "test.txt", true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Pragma", "no-cache");
xmlhttp.setRequestHeader("Cache-Control", "must-revalidate");
xmlhttp.setRequestHeader("Cache-Control", "no-cache");
xmlhttp.setRequestHeader("Cache-Control", "no-store");
xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xhttp.send();
}
}
</script>
</head>
<body>
<div id="exams">test</div>
<button onclick="statusShow(this.value)" value="open" class="status_open">Open</button>
<button onclick="statusShow(this.value)" value="closed" class="status_closed">Complete</button>
<div id="demo"></div>
</body>
</html>
Try changing
xmlhttp.open("GET", "rspamanager.php?st="+status, true);
to
`xmlhttp.open("GET", "rspamanager.php?st="+status+"&" + Math.random() + '=' + Math.random() * Math.random(), true);`
and see if that makes a difference.
If that works, you can leave it like that but should consider adding headers to prevent caching.
Thank you for everyone's help, it was a silly mistake. I ended up putting all of the code to generate the table in a separate file to call and it worked. Not because of the separate file, it just made me understand the request a bit better.
xmlhttp.open("GET", "ajax.php?st="+st, true);
My problem was that I had my PHP script that was being called hard-coded into the page, so it was written, and then written again when called. Copy/pasting all the hard-coded PHP script into a separate file fixed this and made it easier to understand.
Julie mentioned that the script was simply giving me a full page instead of just the section I needed which made the solution click with me.
Also, thank you Bryan for the suggestion to use no-cache options.

Chat system using Mysqli, PHP and AJAX is inserting blank message into Database

I've hit a brick wall in my chat system project and I have tried all day to find a solution. So here I am.
In the file insert.php I am trying to use $_REQUEST to get the value of the textarea from chat.php.
When I type something in and click send, a blank message is sent to the database.
After playing around with it, sometimes the webpage displays a "1" in the div element im trying to display the message in.
Any help would be very much appreciated thank you.
chat.php
<!DOCTYPE html>
<html>
<head>
<title>{ Chat App }</title>
<link rel = "stylesheet" href = "styles/style.css" media = "all" />
<script src="insert.js"></script>
<link href='https://fonts.googleapis.com/css?family=Rokkitt' rel='stylesheet' type='text/css'>
</head>
<body>
<form name = "form1">
<textarea name = "message"></textarea>
<br>
Send
<br>
<div id = "msg"></div>
</form>
</body>
</html>
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
insert.php
<?php
include("connection/connection.php");
global $con;
$msg = isset($_REQUEST['msg']);
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
$get_msg = "SELECT * FROM msg ORDER by id DESC";
$run_msg = mysqli_query($con, $get_msg);
while($row = mysqli_fetch_array($run_msg)){
echo $row['message'];
}
?>
The first problem is when you check for the null value, the function continues and submits the form if it is null or not.
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
// stop the submit action
return;
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
The next problem is in the form handler, you are saving a boolean value isset($_REQUEST['msg']). Try this
insert.php
...
$msg = (isset($_REQUEST['msg']) && !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : false;
if($msg){
// save data to database
...
}
or
...
if((isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
// message was submitted and it is not an empty string
$msg = $_REQUEST['msg'];
// save data to database
...
}else{
// do nothing
}
xmlhttp.open('GET', 'insert.php', true); try changing to xmlhttp.open('GET', 'insert.php?msg='+msg, true);
Hope it helps !
better to add "return" on error when you check if message is empty
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
so it could be
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
return;
}
in submit() function
so the rest of function will not execute and empty message won't be sent.
and assign to variable message not the validation ))
if(isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
$msg = $_REQUEST['msg']; //addiotionally this need escape
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
}

Javascript validate username on PHP with realtime output

I want to use Javascript to validate my input username if it is correct or not showing result on realtime.
Here is index.html code:
<html>
<head>
<script>
function showHint(str){
if(str.length == 0){
document.getElementById("hint").innerHTML = "";
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo3.php?input=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
Type a username: <br>
<input id="hint" type="text" name="username" oninput="showHint(this.value)"><p id="hint"></p>
</body>
</html>
Here is the demo3.php code:
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost","root","123456","mini");
$username = $mysqli->real_escape_string($_REQUEST['input']);
$sql = "SELECT username FROM `users` WHERE username='$username'";
$result = $mysqli->query($sql);
if($result->num_rows){
echo "Valid username";
}else{
echo "Invalid username";
}
?>
</body>
</html>
I use the oninput event example from w3cschools, and I am wondering why my result do not show what I expect?
And if I assign $username with static variable, demo3.php result seems to be correct feedback, not from index.html.
Plus, I am wondering how to validate multiple forms, such as password and email within the same validation php file.
Ex:
input1 -> check username ->output check result
input2-> check password ->output check result
input3-> check email->output check result
New to javascript.All the tutorial seems to provide only one demo, not multiple examples.
Since your input is being placed in the URL, you will need to use the GET parameter other than POST (which does not use the URL):
xmlhttp.open("GET", "demo3.php?input=" + str, true);
Now it should be able to pickup your input for $_REQUEST['input'] or $_GET['input']
The problem is that you are using the ID "hint" twice. ID is a unique identifier, so you NEVER should use it more than once in the same page. And you should avoid using inline handlers. You need to change your javascript to:
<script>
window.onload = function() {
function showHint(str){
if(str.length == 0){
document.getElementById("hint").innerHTML = "";
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo3.php?input=" + str, true);
xmlhttp.send();
}
}
document.getElementById("hintInput").onkeyup = function() {
showHint(this.value)
}
}
</script>
and your HTML:
<input id="hintInput" type="text" name="username"><p id="hint"></p>
You can get rid of window.onload if you place your script tag before closing the body tag.

javascript with XMLHttpRequest not working

I have tried everything suggested in questions of similar nature but this very basic code is just not working. I just want to receive the message from the php code in the same file using XMLHttpRequest.
<!DOCTYPE html>
<head></head>
<body>
<div id="qwer" style="height:50px;width:40px"></div>
<script type="text/javascript">
function check() {
var ualias=document.getElementById('ualias').value;
var resu=document.getElementById("qwer");
var params="username="+ualias;
var hm = new XMLHttpRequest();
var url = "http://'my-domain-name'/try.php";
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
hm.send(null);
resu.innerHTML="CHECKING...";
}
}
</script>
<?php if(isset($_GET['username'])) {
$u=$_GET['username'];
echo $u;
exit();
} ?>
<input id='ualias' type='text' onblur=''>
<button type='button' onclick="check()">Go!</button>
</body>
</html>
The browser (Google Chrome) isn't showing anything for the onclick event.
It finally worked. I made the following edits.
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function check()
{
var ualias=document.getElementById('ualias').value;
var resu=document.getElementById("qwer");
var params="username="+ualias;
var hm = new XMLHttpRequest();
var url = "http://www.websamaj.in/try.php";
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200)
{
var return_data = hm.responseText;
resu.innerHTML=return_data;
}
}
hm.send(null);
resu.innerHTML="wait...";
}
</script>
<?php
if(isset($_GET['username']))
{
$u=$_GET['username'];
echo $u.",you are finally here!:)";
exit();
}
?>
<input id='ualias' type='text' onblur=''>
<button type='button' onclick="check()">Go!</button>
<div id="qwer" style="height:50px;width:100px;background-color:#CCC;"></div>
</body>
</html>
Apparently, the else condition there in onreadystatechange function was causing a problem. I would love it if anybody could tell me why exactly was that creating a problem. As far as i know, onreadystatechange event is called each time the state changes. So in my previous code, "error" should be overwritten thrice on the div and then, when the state changes to 4 and 200, the responseText should be overwritten, since i didnt use append. So, an explanation would be highly acknowledged. Thank you!
In your original code, hm.send(null) and resu.innerHTML="CHECKING" lines are actually INSIDE the onreadystatechange callback:
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
hm.send(null); // <-- wrong place!
resu.innerHTML="CHECKING...";
}
In your edited version, you moved them out of there (fixed indention):
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
}
hm.send(null);
resu.innerHTML="wait...";
The reason you didn't notice this is because in your edited version, you didn't indent your blocks correctly. Recommend always keeping your code formatted consistently, even when hacking around, so you can see the code blocks.

Categories

Resources