PHP How to update text if a user submits a form - javascript

I am trying to make it so a user enters something into a textarea, and once the user submits it, the content will immediately display inside of a div above whose id is "currentMessage". Here is the php file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Message Page</title>
<link rel="stylesheet" href="styles.css" type="text/css"/>
<script type="text/javascript">
function loadMessage(){
document.getElementById("currentMessage").innerHTML = "<?php
$my_file = "msg.txt";
$handle = fopen($my_file, "r");
$data = fread($handle, filesize($my_file));
fclose($handle);
echo $data;
?>";
}
</script>
</head>
<body onload="loadMessage();">
<?php include "header.html";?>
<div>
<div class="PageTitle">Messaging</div>
<p class="Paragraph">
Here you can send a message to the LCD display so that it may be shown when the display
cycles through its time, temperature and status.
</p>
<div class="Paragraph">
Current Message:<br>
<p id="currentMessage" class="CodeBlock"></p>
</div>
<div class="SubTitle">Enter Your Message:</div>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" style="clear: left;">
<textarea cols="32" rows="3" name="msg" maxlength="96" id="msg"></textarea><br>
<input type="submit" value="Submit Message" name="submit">
</form>
<?php
if (isset($_POST['submit'])){
$msg = $_POST["msg"];
$my_file = "msg.txt";
$handle = fopen($my_file, "w") or die("Cannot open file: " . $my_file);
fwrite($handle, $msg);
fclose($handle);
echo "<script>
loadMessage();
</script>";
}
?>
</div>
</body>
</html>
Currently, I attempt to save the user's submission to a file on the server, and then run loadMessage() and echo the result in the currentMessage div. However, this obviously isn't working. I'm also new to php and I am not sure how to direct the output of echo, or if there is no way to be more specific as to where to place output text.

So the problem with this is, you are loading the contents of the file before you've saved anything to it. The php code in loadMessage gets executed immediately on page load, and you'd like to execute it after your msg.txt file has been saved.
You can see that this is kind of working if you submit some text once, then try to submit some text again. it'll display what you submitted last time.
Although this overall approach shouldn't be used on an actual website to save info and then load it back to display, if you're just learning there shouldn't be anything wrong with this.
So, to use Javascript to load your data, you need to make an AJAX request.
Typically, most people use jQuery to perform an AJAX request to load data after the page has loaded.
However, to prevent you from including the whole jQuery library, you can use vanilla Javascript to load the msg.txt file asynchronously. This site, http://youmightnotneedjquery.com/#request, has many useful snippets on how to achieve the same effect without the jQuery library.
So, here'd be your code if you loaded the data via Javascript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Message Page</title>
<link rel="stylesheet" href="styles.css" type="text/css"/>
<script type="text/javascript">
function loadMessage(){
console.log("Performing AJAX request!");
var message_element = document.getElementById("currentMessage");
var request = new XMLHttpRequest();
// Load our msg.txt file
request.open('GET', 'msg.txt', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
// Display the text we loaded.
resp = request.responseText;
message_element.innerHTML = resp;
} else {
// We reached our target server, but it returned an error
message_element.innerHTML = "An error occurred.";
}
};
request.onerror = function() {
// There was a connection error of some sort
message_element.innerHTML = "An error occurred.";
};
// Send the AJAX request (which displays the data after it has been loaded)
request.send();
}
</script>
</head>
<body onload="loadMessage();">
<?php include "header.html";?>
<div>
<div class="PageTitle">Messaging</div>
<p class="Paragraph">
Here you can send a message to the LCD display so that it may be shown when the display
cycles through its time, temperature and status.
</p>
<div class="Paragraph">
Current Message:<br>
<p id="currentMessage" class="CodeBlock"></p>
</div>
<div class="SubTitle">Enter Your Message:</div>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" style="clear: left;">
<textarea cols="32" rows="3" name="msg" maxlength="96" id="msg"></textarea><br>
<input type="submit" value="Submit Message" name="submit">
</form>
<?php
if (isset($_POST['submit'])){
$msg = $_POST["msg"];
$my_file = "msg.txt";
$handle = fopen($my_file, "w") or die("Cannot open file: " . $my_file);
fwrite($handle, $msg);
fclose($handle);
}
?>
</div>
</body>
</html>

The problem I think you're having is that you're echo'ing javascript that is not getting evaluated.
Try echoing:
<script>
(function(){
loadMessage();
})();
</script>
instead of just
<script>
loadMessage();
</script>
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Related

Using javascript/jQuery to populate a form field with database value

I have a PHP form used to submit data. This form auto-populates fields based on a case number or "id" by querying a SQL database and retrieving more data to populate other fields based on the ID. I am tasked with adding a field, but I cannot get it to auto-populate. I tried reverse-engineering the other fields, but this thing is like a spider web.
The goal is to query for a date field in the SQL DB, pull that date, and input it into the text field in the main form's #3. "PMV to MVA" input/text field.
I have redacted irrelevant code for simplicity's sake:
recoveryForm.php (the main form): User enters case number, and using the onblur="loadCase()" function, the fun begins..
<html>
<head>
<meta charset="UTF-8">
<title>Recovery Form</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="jquery-3.3.1.min.js"></script>
<script src="recoveryForm.js"></script>
</head>
<body>
<div class="borderdiv"><div class="innerdiv">
<h1>Recovery Template:</h1>
<p>Date: <?php echo date("Y-m-d H:i:s"); ?></p>
<form action="submit_1.php" id="mainForm" method="post">
<p>
<span class="qText" name="casenum"><b>Case Number: </b></span>
<input type="number" name="casenum_a" onblur="loadCase();" required>
</p>
<table class="mainTable" name="mainTable">
<tr>
<td><span class="qText" name="pmv_to_mva">3. PMV to MVA:</span></td>
<td><span class="qAns" name="pmv_to_mva_a">No</span></td>
</tr>
</table>
<div class="submitDiv"><input type="submit" value="Submit Form"></div>
</body>
</html>
recoveryForm.js: which contains all of the JS functions
function loadCase(){
getPMV();
document.getElementsByName("casenum1_s")[0].innerHTML=document.getElementsByName("casenum_a")[0].value;
function getPMV(){
var myCasenum=document.getElementsByName("casenum_a")[0].value;
window.alert(casenum_a);
$.post(
"getPMV.php",
{casenum: myCasenum},
function(data, status){ setPMV(data);}
);
}
function setPMV(data){
var jdata=JSON.parse(data);
document.getElementsByName("pmv_to_mva_a")[0].value=jdata.ptm;
document.getElementsByName("pmv_to_mva_a")[0].innerHTML=jdata.ptm;
}
And the getPMV.php file that's called from within the JS function:
<?php
$success=FALSE;
$postCasenum = getPostCasenum();
#header('Content-Type: application/json');
$sql = "select user_case_data.PMV_to_MVA from user_case_data WHERE casenum=?";
$conn = odbc_connect( "needles","dba","sql" );
if( $conn ) {
echo $sql;
$stmt=odbc_prepare($conn, $sql);
$queryResult=odbc_execute($stmt);
if (odbc_fetch_row($stmt)) {
$data = [
'ptm' => odbc_result($stmt,1) ? "No" : "Yes"
];
echo json_encode($data);
odbc_close( $conn );
} else {
echo "{}";
}
?>
<?php
function getPostCasenum(){
return $_POST["casenum"];
}
?>
I know the SQL query is good and returns the date value I want to update onto the form. I put the javascript inline in the last code example on this page that can be used as an example (along with jquery file and getPMV.php). No matter what I try, the json response shows blank/empty for the pmv_to_mva field, when I know that field does indeed contain data.
Anybody might be able to point me in the right direction here? Thank you.
========================== EDIT =================================
I continued to get "loadCase is not defined at HTMLInputElement.onblur", so I reasoned that there still must be some syntax error with my javascript. I decided to move the script inline to see if I could make any progress.
"Uncaught reference error: casenum_a is not defined at getPMV"...
recoveryform.php (line 16):
<input type="number" name="casenum_a" onblur="loadCase();" required>
recoveryForm.php in it's entirety:
<html>
<head>
<meta charset="UTF-8">
<title>Recovery Form</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="jquery-3.3.1.min.js"></script>
<!--<script src="recoveryForm.js"></script>-->
<script type="text/javascript">
function loadCase(){
getPMV();
function getPMV(){
var myCasenum=document.getElementsByName("casenum_a")[0].value;
console.log(casenum_a);
$.post(
"getPMV.php",
{casenum: myCasenum},
function(data){ setPMV(data);}
);}
function setPMV(data){
console.log(data);
var jdata=JSON.parse(data);
document.getElementsByName("pmv_to_mva_a")[0].innerHTML=jdata.ptm;
}
}
</script>
</head>
<body>
<div class="borderdiv"><div class="innerdiv">
<h1>Recovery Template:</h1>
<p>Date: <?php echo date("Y-m-d H:i:s"); ?></p>
<form action="submit_1.php" id="mainForm" method="post">
<p>
<span class="qText" name="casenum"><b>Case Number: </b></span>
<input type="number" name="casenum_a" onblur="loadCase();" required>
</p>
<table class="mainTable" name="mainTable">
<tr>
<td><span class="qText" name="pmv_to_mva">3. PMV to MVA:</span></td>
<td><span class="qAns" name="pmv_to_mva_a">No</span></td>
</tr>
</table>
<div class="submitDiv"><input type="submit" value="Submit Form"></div>
</body>
</html>
Thank you everybody for all of your help and suggestions. I was able to accomplish what I was after. My problem was somewhere in my getPMV.php file. I found success in simplifying the file. This worked:
<?php
$success=FALSE;
$postCasenum = getPostCasenum();
header('Content-Type: application/json');
$sql = "select user_case_data.PMV_to_MVA from user_case_data WHERE casenum=?";
$conn = odbc_connect( "needles","dba","sql" );
if( $conn ) {
#echo $sql;
$stmt=odbc_prepare($conn, $sql);
$queryResult=odbc_execute($stmt, array($postCasenum));
$json='{';
while(odbc_fetch_row($stmt)){
$json=$json.'"ptm":"'.odbc_result($stmt,1).'"';
}
$json=$json.'}';
echo $json;
odbc_close( $conn );
} else {
echo "{}";
}
?>
<?php
function getPostCasenum(){
return $_POST["casenum"];
}
?>

how to send single form value to multiple pages in php using jquery

In PHP I am Working on when form has been submitted the values should send to different files Using jquery. example if demo.php form has been submitted data should sent to both process1.php as well as process2.php simultaneously but Its not showing any error and not able to get output.
please help me through this code I have tried so far
Demo.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>main form</title>
</head>
<body>
<form action="multi.php" method="post">
Name:<input id ='myname'>
<input type="button" id="btn" value="send to all">
</form>
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function(){
$('#btn').click(function(){
var username = $('#myname').val();
/*first post*/
$.post('multi1.php',{name:username},function(result){
$('#display').append("<br>"+result);
});
$.post('multi2.php',{name:username},function(result){
$('#display').append("<br>"+result);
});
});
});
</script>
</body>
multi1.php
<?php
echo "this is process1";
echo"and you have posted:".$_POST['name'];
?>
multi2.php
<?php
echo "this is process1";
echo"and you have posted:".$_POST['name'];
?>
Something like this:
let formID = $("uFormId");
formID.submit(function(event) {
event.preventDefault(); // Stop to call URL
$.ajax({url: "multi1.php", data: formID.serialize() ,type: 'POST', success: function(data) {
console.log("Response from multi1 PHP: " + data);
//OR
$('#display').innerText = data;
}
$.ajax({url: "multi2.php", data: formID.serialize(),type: 'POST', success: function(data) {
console.log("Response from multi2 PHP: " + data);
}
}
But, there are several art to make this event with javascript and you can finde a lot of them hier jQuery AJAX submit form
The below code is working fine for me:
<!DOCTYPE html>
<html>
<head>
<title>main form</title>
</head>
<body>
<form>
Name:<input id ='myname'>
<input type="button" id="btn" value="send to all">
</form>
<div id="display"></div>
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('#btn').click(function(){
var username = $('#myname').val();
/*first post*/
$.post('multi1.php',{name:username},function(result){
$('#display').append("<br>"+result);
});
/*second post*/
$.post('multi2.php',{name:username},function(result){
$('#display').append("<br>"+result);
});
});
});
</script>
</body>
</html>
multi1.php:
<?php
echo 'Posted on multi1.php - '.$_POST['name'];
?>
multi2.php:
<?php
echo 'Posted on multi2.php - '.$_POST['name'];
?>
When I put 'test' in the textbox and hit 'send to all' button, the output I'm getting is:
Posted on multi1.php - test
Posted on multi2.php - test
Check the file names you are posting to and I assume that you are trying to access the posted variable from other php page without storing it.
In general, if you make an HTTP request (in your case, it is POST), the browser will send that value to the other page and will forget it and when you try to access the value from other pages (like, process1.php) it will return an empty string as it didn't store the variable.
So, a solution is to store the value in localstorage using javaScript and try accessing the variable from the other page.
here is the updated code
$(function(){
$('#btn').click(function(){
var $username = $('#myname').val();
window.localStorage.setItem('username', $username);
});
});
and get the stored value with
var $userName = window.localStorage.getItem('username')
you can know about it here and here

How to capture what a php function returned and change html elements css

I've made a fairly simple login page, but now I want to test if the login information is correct by submitting the information to a php function.
If that function returns false I need to change some css properties of some elements.
So far I've tried to assign an "onclick" event to the submit button, in the php I assign false to a variable and I return it, later in js script I try to echo de variable to a JS variable so I can check it's value.
This is what I have:
<head>
<meta charset="utf-8">
<title>IPS Connected - Login</title>
<link rel="stylesheet" href="assets\CSS\main.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<?php
if($_POST)
{
$result = false;
return $result;
}
?>
</head>
<body>
<div class="wrapper">
<img src="assets/icons/user.png" id="userLogo" alt="user-icon">
<form method="post">
<div class="form-div">
<input type="text" name="username" placeholder="Username">
</div>
<div class="form-div">
<input type="password" name="password" placeholder="Password">
</div>
<input type="submit" name="submit" value="login" onclick="checkLogin();" class="btn-login">
</form>
<br>
Forgot password?
</div>
</body>
<script type="text/javascript">
function checkLogin()
{
var result = "<?php echo $result?>";
if(!result)
{
var edit_save = document.getElementById("userLogo");
edit_save.src = "assets/icons/error.png";
}
}
</script>
EDIT: I've tried to change the php script to
<?php
if($_POST)
{
$result = test();
function test()
{
return false;
}
}
?>
in the script I've changed it to
<script type="text/javascript">
function checkLogin()
{
var test = <?php echo $result?>;
if(!test)
{
document.getElementById('userLogo').src="assets/icons/error.png";
}
else
document.getElementById('userLogo').src="assets/icons/user.png";
}
</script>
That's not how PHP works. It's a preprocessing language.
More over its a server side language and is compiled on the server, whereas JS is a client side language and is copiled on the client's machine.
You can do something like this:
<script type="text/javascript">
<?php
if($result){
echo "document.getElementById('userLogo').src='assets/icons/error.png';";
}else{
echo "document.getElementById('userLogo').src='assets/icons/user.png';";
}
?>
</script>
It would send the JS code according to the value of $result and the JS would be compiled on the client.

jquery + ajax + php (loading jquery library)

So im learning about jquery and ajax. Originally i did an old school php page, where when i submit the form, the data gets stored in a database, and then the webpage loads a new page and tells me i've successfully added a student... I'm not trying to implement ajax and jquery to my code, but i my js script isn't working. I'm trying to call an Alert() just to test if jquery is working, but no alert popup appears when i click the submit button.
This is what i have so far:
addStudent2.php code:
<!DOCTYPE html>
<html>
<head>
<title>Adding Student With AJAX</title>
</head>
<body>
<form action = "userInfo.php" id="myForm" method="post">
<p>Name:
<input type="text" name="name" value=""/>
</p>
<p>Age:
<input type="text" name="age" value=""/>
</p>
<input type="submit" id="submit" value="Add"/>
<div id="result"></div>
<script src="http://code.jquery.com/jquery-3.2.0.min.js" type = "text/javascript"></script>
<script src="my_script.js" type = "text/javascript"></script>
</form>
</body>
</html>
userInfo.php code:
<?php
include('connection.php');
$name = $_POST['name'];
$age = $_POST['age'];
$query = "INSERT INTO student2 (first_name, age) VALUES(?, ?)";
$var = array($name,$age);
$response = sqlsrv_query($conn, $query, $var);
if($response == true){
echo "Student has been added";
}
else{
echo nl2br("Insertion failed\n");
die( print_r( sqlsrv_errors(), true));
}
?>
my_script.js code:
$('input#submit').on('click', function(){
alart(1);
});
i know my javascript or jquery library isn't working, because i'm not getting an alert popup when i click on the submit button.
Could someone please help?
The problem was the js script was not updating on the browser, i had to force refresh the page by pressing "Ctrl + F5" here.
Also I changed input#submit to #submit:
$('#submit').on('click', function(){
alert(1);
});
...and of course changed "alart(1)" to "alert(1)" lol.

ajax response contains the html for the whole page instead of the content of text editor

i am working with ckeditor.I used ajax to send the content of the ckeditor using post method.My plan is to show the response in a div .But in response i get the html for the whole page enclodes by html tag instead of only the editor's content.What is going on here? How can i get only the editor's content
<?php
if(isset($_POST) && !empty($_POST)){
echo $_POST['content'];
}
?>
<html>
<head>
<script src='ckeditor/ckeditor.js'></script>
</head>
<body>
<form action='test.php' method='post'>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<input type='button' value='submit' onClick='lol(event);'>
</form>
<div id='content' style='border:2px solid black;'>
</div>
<script>
CKEDITOR.replace( 'editor1');
function lol(event){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
//document.getElementById('content').innerHTML=xhr.response;
alert(xhr.responseText);
}
}
var value=CKEDITOR.instances.editor1.getData();
var params = "content="+value;
xhr.open('POST','test.php',true);
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
//alert(value);
}
</script>
</body>
</html>
When You use echo, the response is sent and then the html is sent. If you want to stop after echo, use die();:
<?php
if(isset($_POST) && !empty($_POST)) {
die($_POST['content']);
}
?>
Also, you should check that content is set:
<?php
if(isset($_POST) && !empty($_POST) && isset($_POST['content'])) {
die($_POST['content']);
}
?>
Try this solution by adding variable to Javascript variable which called params and this variable to check if already these items opened or not and prevent main items to not open more than 1 time even if u called your page by ajax , to be clear try like that
var params = "content="+value+"isopened=1";
then use php if statement like if there is no required variable then print your main items and this will only happen one time when u will visit the page directly with no ajax request
<?PHP
if(!$_POST['isopened'])
{
echo "home elements";
}
?>

Categories