Form data sent via POST method gets empty - javascript

I am posting the "user" variable to another page i.e. Survey.php as follows:
index.html
<form action="Survey.php" method="post" name="frm">
<div><input type="text" name="user"></div>
<div><input type="submit" value="Start" class="btn btn-primary btn-sm"></div>
</form>
I can access the "user" variable on Survey.php page on its first load.
Now, because I have another form on this page as well, which posts data to itself.
Survey.php
$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$user', '$email');";
echo $sql;
}
<form action="survey.php" method="post">
<div><input type="text" name="email"></div>
<div><input type="submit" value="submit" class="btn btn-primary btn-sm"></div>
</form>
I am trying to send "user" and "email" together to the database now. What happens actually is that everytime I click on submit button of the survey.php page, the "user" variable gets empty.

You have to test your posts DATA and user Sesssion.
In your PHP code, you can have something like that
<?php
session_start();
if(isset($_POST['user']))
$_SESSION['user'] = $_POST['user'];
if(isset($_POST['email']))
$_SESSION['email'] = $_POST['email'];
if(isset($_SESSION['user']) AND isset($_SESSION['email'])){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$_SESSION['user']', '$_SESSION['email']');";
echo $sql;
}
If you don't want to use sessions, you can play with your form like this :
$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$user', '$email');";
echo $sql;
}
<form action="survey.php" method="post">
<div><input type="text" name="email"></div>
<div><input type="submit" value="submit" class="btn btn-primary btn-sm"></div>
<input type="hidden" name="user" value="<?php echo $user; ?>">
</form>

You have $user and $email as variable then why are you putting them as strings? The below code should work -
$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '" . $user . "', '" . $email . "');";
echo $sql;
}
<form action="survey.php" method="post">
<div><input type="text" name="email"></div>
<div><input type="submit" value="submit" class="btn btn-primary btn-sm"></div>
</form>

Related

How could I replace a form with already inserted text after unsuccesfull finding in database?

I have the code in Participate.php file which has a form:
<form method="post" action="input.php" id="Form">
<input type="text" class="form-control" name="txtName" maxlength="20" required style="margin-bottom:20px">
<input type="email" class="form-control" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
<input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
</form>
After unsucessful submit (I check if inserted mail already exist in database) and if no exist I want to refill value for form. This is the input.php code:
<?php
$name = $_POST['txtName'];
$mail = $_POST['txtEmail'];
$description = $_POST['txtDescription'];
$connect = new PDO("mysql:host=4*****3;dbname=3*****b", "3***b", "****");
$connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$q=$connect->prepare("SELECT mail FROM konkurs WHERE mail LIKE (?)");
$q->bindValue(1, $mail);
$q->execute();
$row_cnt = $q->rowCount();
if($row_cnt == 0){
$query = $connect->prepare("insert into konkurs(name,mail,description)
values(?, ?, ?)");
$query->bindValue(1, $name);
$query->bindValue(2, $mail);
$query->bindValue(3, $description);
try {
$query->execute();
echo ("<script LANGUAGE='JavaScript'>
window.alert('Sent.');
window.location.href='index.html';
</script>");
exit;
} catch (PDOException $e) {
die($e->getMessage());
}
} else {
echo ("<script LANGUAGE='JavaScript'>
window.alert('This mail already exist.');
window.location.href='Participate.php';
document.getElementById('txtName').value = 'nothing';
</script>");
}
?>
The thing is it's redirecting to Participate.php after unsuccesfull sumbition. But it doesn't refill the form.
First of all, you must change your HTML to include the id attribute, for example:
<form method="post" action="input.php" id="Form">
<input type="text" class="form-control" id="txtName" name="txtName" maxlength="20" required style="margin-bottom:20px">
<input type="email" class="form-control" id="txtEmail" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
<input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
</form>
Then, you must move your logic to the same file as the form container (here Participate.php), and remove the redirection for failures. Otherwise, you'll get no visible results, as the redirection would prevent further JavaScript code from running.
// Updated to prevent syntax errors with multiline strings
echo "<script>"
. "window.alert('This mail already exist.');"
. "document.getElementById('txtName').value = 'nothing';"
. "</script>";

PHP MYSQL Upload Image With other data

This is what it looks like.
But when i press the submit button it wont upload the image.
Is it possible to have 2 functions in one SUBMIT?
It saves the other data in my database but the image is not uploaded nor it is in my database.
<?php
$con=mysqli_connect("localhost","root","","presyohan");
// Check connection
if (mysqli_connect_error())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
$prod_name = $_POST['prod_name'];
$prod_price = $_POST['prod_price'];
$prod_category = $_POST['prod_category'];
$sql="INSERT INTO products (prod_name, prod_price, prod_category)
VALUES('$prod_name','$prod_price','$prod_category')";
$result=mysql_query($sql);
if ($con->query($sql) === TRUE) {
session_start();
$_SESSION['users'] = $rows['prod_name'];
$_SESSION['id'] = $rows['user_id'];
header("Location: store-index.php");
die();
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
//imageupload
$filename = $_FILES['uploadfile']['name'];
$filetmpname = $_FILES['uploadfile']['tmp_name'];
$folder = 'images/products/';
move_uploaded_file($filetmpname, $folder.$filename);
$sqls = "INSERT INTO 'products' ('prod_img') VALUES ('$filename')";
$qry = mysqli_query($con, $sqls);
if ($qry) {
echo 'header("Location: store-index.php")';
}
$con->close();
}
?>
<form class="form" action="add-prod.php" method="post" enctype="multipart/form-data">
<div class="upload-btn-wrapper">
<label for="file-upload" class="custom-file-upload">
Product Image <i class="fas fa-cloud-upload-alt"></i>
</label>
<input id="file-upload" type="file" name="uploadfile" />
</div>
<div class="form__group">
<button class="btn" type="submit" name="submit">ADD</button>
</div>
</form>
enter image description here

Php javascript conflict in wordpress template file

I have built a contact form for my wordpress site. Four fields are there - name, email, subject, message. For logged in users I want their name and email to be auto-filled in their respective fields in the form and those name, email fields will be disabled for them to edit. And for non-logged in users they will put name, email fields manually. I have put this code in the page template file -
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
if ( 0 != $current_user->ID ) {
echo '<script type="text/javascript">
document.getElementById("curUserName").value = "'.$user_name.'";
document.getElementById("curUserName").disabled = "disabled";
document.getElementById("curUserEmail").value = "'.$user_email.'";
document.getElementById("curUserEmail").disabled = "disabled";
</script>';
}
?>
But this code is disabling name, email fields for both users (logged in and non-logged in). I have controlled the script through if condition. Still the javascript is applying for both users. Please advise where I have gone wrong.
Here is the form html -
<form action="/success.php" method="post">
<label>Name :</label><br>
<input type="text" id="curUserName" name="sender_name" required><br>
<label>Email :</label><br>
<input type="text" id="curUserEmail" name="sender_email" required><br>
<label>Subject :</label><br>
<input type="text" name="sender_sub"><br>
<label>Message</label><br>
<textarea name="sender_msg" rows="4" cols="60" required></textarea><br>
<input type="submit" name="submit" value="Send">
</form>
The source you are going to change has disabled option already.. so just remove it if the user is not logged in :)
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
echo '<script type="text/javascript">';
if ( 0 != $current_user->ID )
{
echo 'document.getElementById("curUserName").value = "'.$user_name.'"
document.getElementById("curUserName").disabled = "disabled"
document.getElementById("curUserEmail").value = "'.$user_email.'"
document.getElementById("curUserEmail").disabled = "disabled"';
}
else
{
echo 'document.getElementById("curUserName").disabled = false;
document.getElementById("curUserEmail").disabled = false;';
}
echo '</script>';
?>
Don't echo javascript with php. It's bad practice.
Try using value tags in your inputs, check if user logged in with a ternary operator, and if so, echo to value tag their credentials.
<?php (is_user_logged_in()) ? $current_user = wp_get_current_user() : $current_user = false; ?>
<label>Name</label>
<input type="text" id="curUserName" name="sender_name" value="<?php ($current_user) ? echo $current_user->user_name : '' ?>" required>
<label>Email</label>
<input type="text" id="curUserEmail" name="sender_email" value="<?php ($current_user) ? echo $current_user->user_email : '' ?>" required>

Javascript popup confirmation for two submit buttons

I am new to php, mysql, and javascript. Recently I have been working on creating a popups for each button. When I put the code in the form tag, the code works, however it is a general popup for both add and delete. I would like a confirm popup for adding and deleting. I tried putting the code on the input tags but the code did not run. What am I doing wrong?
HTML
<form action="da.php" method="post">
name:<input type="text" name="input1">
<br/>
<input onSubmit="if(!confirm('Submit?')){return false;}" name="add1" type="submit" value="Submit" />
<input onSubmit="if(!confirm('Delete?')){return false;}" name="del1" type="submit" value="Delete" />
</form>
</body>
PHP
define('db_name', 'demo');
define('db_user', 'root');
define('db_password', 'pw');
define('db_host', 'localhost');
$link = mysql_connect (db_host, db_user, db_password);
if (!$link) {
die('could not connect: '. mysql_error());
}
$db_selected = mysql_select_db(db_name, $link);
if (!$db_selected) {
die('can\'t use' . db_name . ': ' . mysql_error());
}
$value = $_POST['input1'];
if (isset($_POST['add1'])) {
$sql = "insert into demo (name) values ('$value')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
}
elseif (isset($_POST['del1'])) {
$sql = "delete from demo where name = ('$value')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
}
mysql_close();
header( 'Location: localhost://da-form.html') ;
?>
try onclick instead of onSubmit
onSubmit is usually used on the form tag
You can use window.confirm in javascript to get confirmation from user.
http://www.w3schools.com/jsref/met_win_confirm.asp
Try this
<form action="da.php" method="post">
name:<input type="text" name="input1">
<br/>
<input onClick="return confirm('Submit?');" name="add1" type="submit" value="Submit" />
<input onClick="return confirm('Delete?');" name="del1" type="submit" value="Delete" />
</form>

Cheking if form of submited email is correct

I've created this script to check form of email user will enter into textbox
function checkEmail() {
var mail = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; /* regex koda najdena na codeproject.com*/
if (!filter.test(mail.value))
{
alert('enter valid email');
mail.focus;
return false;
}
It's used to check form in this script and suposed to show you alert, before you are able to continue
<?php
$flag = 0;
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","root","");
if (!$con){
die("cannot connect: " . mysql_error());
}
mysql_select_db("strek", $con);
$nar_db="SELECT * FROM narocniki;";
$result = mysql_query($nar_db, $con);
while($row=mysql_fetch_array($result))
{
if($_POST['mail']==$row['mail'])
$flag = 1;
}
if($flag==0)
{
$sql = "INSERT INTO narocniki (mail) VALUE ('$_POST[mail]')";
mysql_query($sql, $con);
mysql_close($con);
?>
<p align="center" class="vsebina" >
Tvoj mail je bil uspešno sprejet!</p>
<p align="center"><input type="button" name="return" value="nazaj"></p>
<?php
}
else
{
echo '<p align="center" class="vsebina">Naveden mail je že v bazi naročnikov!</p>';
?>
<p align="center"><input type="button" name="return" value="nazaj"></p>
<?php
}
}
else
{
include("vsebina/tabdog.html");
?>
<p align="center" class="vsebina" id="mail">
naroči se na najnovejše novice</p>
<form action="dogodki.php" method="post">
<p align="center" class="vsebina">vnesi svoj e-naslov: <input type="text" name="mail" id="mail" required>
<input type="submit" name="submit" value="potrdi" onClick="return checkEmail()">
</p>
</form>
<?php
}
?>
It's probably just something missing
Should I rather just include script inside the code, and where would be the best to place it-weather directly in head or rather somewhere in between
Is this even possible in my code, because it already checks if mail exists in database, and would then also need to check the form of email
Instead of doing it in the onclick attribute of the submit button, try doing it in the onsubmit attribute of the form:
<form action="dogodki.php" method="post" onsubmit="return checkEmail()">

Categories