I'm using Ajax to get POST values from a form. However, when I try to insert the form values in a database on submit, it doesn't get inserted. I still have no idea why it does not work.
Here is my HTML
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font><br>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
My JS (the console.log does go through and work):
if (validForm)
{
console.log("valid form");
$.ajax(
{
type:'POST',
url:'form-submit.php',
data:$('#home-sign-up-form').serialize(),
success:function(response)
{
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
$emailSentTextEmail.text($suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
}
And my PHP/MySQL:
if (isset($_POST['signUp']))
{
echo "<script type='text/javascript'>alert('got');</script>";
$suFirstName = mysqli_real_escape_string($_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($_POST['suLastName']);
$suEmail = mysqli_real_escape_string($_POST['suEmail']);
$suPassword = mysqli_real_escape_string($_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
}
The alert in the PHP code so I would assume that it isn't getting the 'signUp' POST variable. Thanks so much! Any help is appreciated! :D
You get the signUp post variable when you click on the button. If you are posting via ajax call the button variable will not be available as $_POST variable. Please check any other input value.
Another options is have and hidden input set it to some value. And check it on server side. But it is better to check any normal required input of form instead of having extra input control.
$mysqli = new mysqli("localhost", "root", "", "test");
if (isset($_POST['signUp'])){
echo "<script type='text/javascript'>alert('got');</script>";
echo $suFirstName = mysqli_real_escape_string($mysqli,$_POST['suFirstName']);
echo $suPassword = mysqli_real_escape_string($mysqli,$_POST['suPassword']);
$sql="INSERT INTO users (`username`, `password`) VALUES ('$suFirstName', '$suPassword')";
}
if (!mysqli_query($mysqli,$sql)) {
die('Error: ' . mysqli_error($mysqli ));
}
echo "1 record added";
mysqli_real_escape_string requires two arguments the connection and the string.
You can read more :https://www.w3schools.com/php/func_mysqli_real_escape_string.asp
Related
This is probably something basic but I'm strugle with it.
I construct a binary string for the 12 mounths of the year, using 12 checkboxes as:
const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
document.getElementById("season").textContent =
checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
}
and the html code for it:
<input type="checkbox" id="jan"><label>january</label><br>
<input type="checkbox" id="feb"><label>february</label><br>
<input type="checkbox" id="mar"><label>march</label><br>
...
<br>
<p id="season"></p>
<br>
<button type="button" onclick="RegMD()">Register My Data</button>
The above code generate for me the string and display it.
These checkboxes are inputs on a form where I have other input fields as well:
<form id="register_form" method="post" role="form" action="">
<input autofocus="" id="firstname" name"firstname" placeholder="First Name" type="text" required />
<textarea id="Address" name="Adress" placeholder="No Address" type="text" rows="3" cols="30"></textarea>
<select id="country" name="country" required>
<option selected>Choose</option>
<option value="10">Germany</option>
<option value="11">Poland</option>
<option value="12">United Kingdom</option>
</select>
<button type="submit">Submit My New Entry</button>
</form>
which I send through POST send to a database using:
<?php
if (isset($_POST["firstname"])){
try {
//open the database
$pdo = new PDO('sqlite:db/users.db');
$firstname = $_POST["firstname"];
$Address = $_POST["Address"];
$country = $_POST["country"];
$data = [
'firstname' => $firstname,
'Address' => $Address,
'country' => $country,
];
$sql="INSERT INTO details (firstname, Address, country) VALUES (:firstname, :Address, :country)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
$pdo = NULL;
} catch(PDOException $e) {
print 'Exception : ' .$e->getMessage();
}}
?>
My request is, how can I get the generated string
<p id="season"></p>
and include it in the POST method to be sent into the database?
The string now is generated on a separate button click and how I need to declare it to be picked up and sent together with the other information through POST method. Thank you.
###############################
Edit.
###############################
by changing the textContent into value in my script:
document.getElementById("season").textContent = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
into
document.getElementById("season").value = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
and putting a input field for the result:
<input type="text" id="season" name="season" value="" required >
I managed using the button onclick event to display my generated string into a input field and than using SUBMIT to be sent into my database.
BUT I receive another issue as you can see it in my printscreen:
all recorded value goes as "value" and the firts 0's are trimmed from my string. Initial textContent are not worked.
I found few solutions to do something before on submit as it is: here and here but i can't make it work.
my full code is:
<!doctype html>
<html>
<head>
<script type='text/javascript' src="js/jquery.min.js"></script>
</head>
<body>
<form id="register_form" method="post" role="form" action="#">
<table border=0>
<tr><td>First Name: <td><input autofocus="" id="firstname" name="firstname" placeholder="First Name" type="text" required />
<tr><td>Address: <td><textarea id="Address" name="Address" placeholder="No Address" type="text" rows="3" cols="30"></textarea>
<tr><td>Country: <td><select id="country" name="country" required>
<option value="" selected >Choose</option>
<option value="10">Germany</option>
<option value="11">Poland</option>
<option value="12">United Kingdom</option>
</select>
<tr><td>Season: <td>
<input type="checkbox" id="jan"><label>january</label><br>
<input type="checkbox" id="feb"><label>february</label><br>
<input type="checkbox" id="mar"><label>march</label><br>
<button type="button" onclick="RegMD()">Generate season string</button>
<tr><td>Season: <td><input type="text" id="season" name="season" value="" required >
<tr><td><input type="submit" value="Add New Record" >
</table>
<script>
const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
document.getElementById("season").value = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
}
</script>
</form>
<?php
IF (isset($_POST['firstname'], $_POST['country'], $_POST['season']) // checking texfield and combobox if are empty
AND !empty($_POST['Address'])) // checking textarea if is empty
{
try {
$firstname = $_POST["firstname"];
$Address = $_POST["Address"];
$country = $_POST["country"];
$season = $_POST["season"];
$data = ['firstname' => $firstname,
'Address' => $Address,
'country' => $country,
'season' => $season,
];
$pdo = new PDO('sqlite:db/users.db');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO details (firstname, Address, country, season)
VALUES (:firstname, :Address, :country, :season)";
$stmt = $pdo->prepare($sql);
$stmt -> execute($data);
$pdo = NULL;
} catch(PDOException $e) {print 'Exception : ' .$e->getMessage();}
}
?>
</body>
</html>
How can I make it work?
###########################
Second Edit.
###########################
the value from my database for the string insert was fixed by changing the column declararion of my database from INTEGER to VARCHAR as was proposed by ADyson.
How can i move the javascript to be generated and submited on SUBMIT?
Instead of having a p element <p id="season"></p>, you can use a readonly input field, inputs are picked up by the form and sent automatically: <input id="season" readonly>.
To have it calculated automatically you can instead of a click event handler add an submit event handler to the form element. Alternatively if you wish to display the the updates to the user you can use the change event on the checkboxes. And update the value of the input: document.getElementById("season").value = ...
P.S. It's better to register event handlers in JS rather than in the HTML: element.addEventListener('change', updateValue);
Thank you guys for all your advises, finally i solved it as you giuded me with: onsubmit="return RegMD();"
<form id="register_form" method="post" role="form" action="#" onsubmit="return RegMD();">
and
<input type="hidden" id="season" name="season" value="">
What I am trying here is when you click on submit button I am calling one javascript function which takes all the form element values and passes it to the php page without storing them inside the variable and then send those variables.
Example of my form:
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" onsubmit="sendvalues()" value="Stash the file!" />
</form>
Now on javascript, I want to send userid and email fields to directly go to php page without first retrieving them into a variable and then send that variable via ajax.
function sendValues() {
var formElement = document.querySelector("form");
console.log(formElement);
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "<?php echo VIEW_HOST_PATH;?>process_data.php");
formData.append("process_type", 'process_data');
request.send(formData); //want to send all form userid, email directly to php page
request.onreadystatechange = (e) => {
console.log(request.responseText)
}
}
Is this possible to send user_id and email values to php page directly? So, for example, form element which contains emailed and user info and any other forms element and they all send to php page via ajax but most important without storing this element values in javascript variables.
thanks
In your form you should specify property "action". That action would be your php file that will handle your submit action. Also you could add to this form id selector.
<form id="file-info" enctype="multipart/form-data" action="/process_data.php" method="post" name="fileinfo">
And now in your function sendValues() you could submit form like this:
function sendValues() {
document.getElementById("file-info").submit();
}
or you do not even need this function if you set your input button type to submit:
<input type="submit" name="submit" />
And then in your php file you can use your variables like:
if (isset( $_POST['submit']))
{
$userId = $_POST['userid'];
$email = $_POST['email'];
}
Try this one then
HTML CODE
<form enctype="multipart/form-data" method="post" class='submit_form' name="fileinfo">
<label>Your user name:</label>
<input type="text" name="name" id='name' placeholder="name" required /><br />
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" id='userid' placeholder="email" required size="32" maxlength="64" /><br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" /><br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" value="Stash the file!" class='submit' />
JQUERY CODE on the same page (include jquery)
$('body').on('click', '.submit', function(e) {
e.preventDefault();
$.ajax({
'url': 'mpay.php',
'type': 'POST',
'data': $('.submit_form').serialize(),
success: function(response) {
console.log(response);
}
});
});
PHP CODE The file name is mpay.php
$arr = [
'name' => $_POST['name'],
'email' => $_POST['email'],
];
echo "<pre>;
print_r($arr);
echo "</pre>";
Hope this helps.
I want to know if i can set a variable when the player finish the him form.
E.g:
<form>
First name:<br>
<input type="text" name="firstname" value="Pedro">
<br>
Last name:<br>
<input type="text" name="lastname" value="Pinto">
<br><br>
<input type="submit" value="Submit">
</form>
And when he submit, execute a function on JS, what saves the firstname and lastname to a variable.
And i want know in PhP, if it's possible too thanks.
JS solution:
In this solution, the data is processed client side. Be careful though if you are saving any of this to your server since users can use their browser to manipulate the data in unintended ways.
HTML:
<form>
First name:<br>
<input type="text" id="firstname" value="Pedro">
<br>
Last name:<br>
<input type="text" id="lastname" value="Pinto">
<br><br>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
JS:
function myFunction() {
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
}
PHP solution:
In this solution, the data is processed server side. Here, you will clear out any JS variables because this causes a new page to load when you do this. So, generally, do not do this if you need to continue working on page after saving your variables. Also, note that the HTML forms use "name" instead of "id" when passing a post.
HTML:
<form action="MYPAGE.php" method="post">
First name:<br>
<input type="text" name="firstname" value="Pedro">
<br>
Last name:<br>
<input type="text" name="lastname" value="Pinto">
<br><br>
<input type="submit" value="Submit">
</form>
PHP:
<?php
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
?>
AJAX Solution: The third way to do it which is sort of a hybrid is to use AJAX. In this solution you use JavaScript to collect the variables, then you POST the data to another .php file without navigating away. This way you don't clear out any of your JavaScript variables, and you can write the data to the server. Then whatever content is generated by your targeted PHP page can be loaded into the page you are already on by inserting it into the element you target with your result.
NOTE: This sample code uses jQuery.
HTML:
<form>
First name:<br>
<input type="text" id="firstname" value="Pedro">
<br>
Last name:<br>
<input type="text" id="lastname" value="Pinto">
<br><br>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
<div id="MYTARGETELEMENT"></div>
JS:
function myFunction() {
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type:"POST",
url: "MYPAGE.php",
data: {
firstname:firstname,
lastname:lastname
},
success: function(result){
$("#MYTARGETELEMENT").html(result);
}
});
}
PHP:
<?php
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
echo("Post Received By Server");
?>
var username = $("input[name=firstname]").val();
var lastname = $("input[name=lastname]").val();
This is how you get the value of both input field with Jquery. The first part gets your input by it's name, .val() gets the value from that input.
How to get it in PHP:
Add a name to the submit button:
<input type="submit" name="submit" value="Submit">
Then use this code:
<?php
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
}
?>
I have created a basic registration form that works with full functionality. The only problem is that errors that appear is quite far on top left of the screen and it looks quite awkward. Along with it looks like it has no relation with the textbox displaying error. i want the error message to be displayed in the tooltip in a way like particular message in a particular textbox.
along with if the user makes a successful login I want him to redirect it to the login page but in my webpage it dies because of this statement.
die ("<h2> Welcome</h2>Login to get started...");
Please provide an alternative for this too. any help would definitely be appreciated.
if ($reg) {
if ($em==$em2) {
$e_check = mysql_query("SELECT email FROM users WHERE email='$em'");
$checke = mysql_num_rows($e_check);
$u_check = mysql_query("SELECT username FROM users WHERE username='$un'");
$check = mysql_num_rows($u_check);
if ($check == 0 && $checke == 0) {
if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
if ($pswd==$pswd2) {
if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
echo "Username/ First Name/ Last Name cannot exceeds 25 characters!";
}
if (strpos($un, " ") !== false){
echo "Your username cannot have a space character.";
}
if (strpos($em, "#") == false){
echo "Invalid Email";
}
else {
if(strlen($pswd)>30||strlen($pswd)<5) {
echo "Your password must be between 5 and 30 characters long!";
}
else{
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = mysql_query("INSERT INTO users VALUES ('', '$un','$fn','$ln','$em','$pswd','$d','0','Write something about yourself.','','')");
die ("<h2> Welcome</h2>Login to get started...");
}
}
}
else{
echo "Your passwords doesn't match!";
}
}
else{
echo "Please fill in all the fields";
}
}
else{
echo Username already taken or Email already registered
}
}
else{
echo "Your E-mails doesn't match";
}
}
HTML:
<form action="#" method="POST">
<input type="text" name="fname" size="25" placeholder="First Name" />
<input type="text" name="lname" size="25" placeholder="Last Name" /><br><br>
<div data-tip="Make Sure you remember your username. You'll need it at the time of login. Your username should not have space in between.">
<input type="text" name="username" size="56" placeholder="User Name" /></div><br><br>
<input type="text" name="email" size="56" placeholder="Email Address" />
<input type="text" name="email2" size="56" placeholder="Please re-enter your Email Address" /><br><br>
<input type="password" name="password" size="47" height="30" padding="30" placeholder="Password" /><br><br>
<input type="password" name="password2" size="47" height="30" placeholder="Please re-enter your Password" /><br><br>
<input type="submit" name="reg" value="Sign Up and learn!" />
</form>
If you want to Customise the error message,Say giving it A red colour
or anything. you can add a class to all span blocks. and you can
specify attributes of that class . like below
<style>
.help-block
{
color: red;
}
</style>
You can Add some span blocks below each input .give it each a unique id, and make it Hidden by
Default. Like Below
<input type="text" name="fname" size="25" placeholder="First Name" />
<span class="help-block" id="fname_block" style="display:none;"></span><br>
<input type="text" name="lname" size="25" placeholder="Last Name" />
<span class="help-block" id="lname_block" style="display:none;"></span><br>
In PHP :
if error is in the first input. ie, fname
echo"<script>document.getElementById('fname_block').innerHTML = 'error in first name';
document.getElementById('fname_block').style.display = 'inline'; </script>";
or if error is the second input(ie, lname). then specify the id of span block of that input in the getelementById part of the code
don't forget to hide span block if there is not error.
document.getElementById('fname_block').style.display = 'none';
IF you use jquery(you just need to add jquery library),the codings
will be much simple.
jquery code for the same js code above
$('#fname_block').html('error in first name').show();
you can hide an element in jquery like below.
$('#fname_block').hide();
I am making a admin panel. When users input data into a text field i want to copy the data in the text field to another text field.
My problem is the code works until i added a insert into database function to the same button.
How do i get the button to perform both functions. is there a better way to do the onclick function. As i am using two text fields but i really want one to be the product title. Like in the image below:
Code is
<?php
$add_product_errors = array();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// price validate - must be decimal(float)
if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) {
$add_product_errors['price'] = "Please enter a product price";
}
// item name validate
if (empty($_POST['item_name'])) {
$add_product_errors['item_name'] = "Please enter a name";
}
// item name description
if (empty($_POST['desc'])) {
$add_product_errors['desc'] = "Please enter a product description";
}
//add to database
//if (empty($add_product_errors)) {
$q = 'INSERT INTO Product (Product_Name,Product_Desc,Product_Price) VALUES (?,?,?)';
$stmt = mysqli_prepare($dbc, $q);
//debugging
$stmt = mysqli_prepare($dbc, $q) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $item_name, $desc, $price);
$item_name = strip_tags($_POST['item_name']);
$desc = strip_tags($_POST['desc']);
//100 - changes the way the decimal displays in database
$price = strip_tags($_POST['price'] * 100);
//execute the query
mysqli_stmt_execute($stmt);
printf("%d Item Added.\ ", mysqli_stmt_affected_rows($stmt) === 1); {
mysqli_stmt_close($stmt);
}
}
?>
HTML
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" >
<input type="textfield" id="title" name="title" value="">
<input type="textfield" id="item_name" name="item_name" placeholder="item name" value="" <?php $add_product_errors ?>/><br>
<textarea id="desc" name="desc" value="" placeholder="Item description" rows="3" maxlength="200" required ><?php $add_product_errors ?></textarea><br>
<input type="textfield" id="price" name="price" value="" placeholder="£" maxlength="30" required <?php $add_product_errors ?>/><br>
<input type="submit" name="add" value="add" value="add" class="btn" onclick="myFunction()">
<!-- copy item_name to page title -->
<script>
function myFunction() {
document.getElementById("title").value = document.getElementById("item_name").value;
}
</script>
Consider changing the submit input to a regular button so that you can control the control flow entirely. It might also make the control flow clearer for you to understand.
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" onsubmit="myFunction()">
... your HTML here ...
<input type="button" name="add" value="add" value="add" class="btn" onclick="myFunction()">
</form>
<script>
function myFunction() {
// Update your field value
document.getElementById("title").value = document.getElementById("item_name").value;
// Submit your form.
document.forms["product_form"].submit();
}
</script>
You can bind the copying of the text on the onsubmit event like this:
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" onsubmit="myFunction()">