Send html form data to database through php without switching page - php

Hey guys so i have a form:
<form action="signup.php" method="post" class="cd-form">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" name="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" name="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" name="o_email">
</p>
<p class="fieldset">
<input class="full-width" type="submit" value="Sign Up!">
</p>
</form>
And you may notice that the action is calling "signup.php" :
<?php
$con=new mysqli ("localhost","root","","chroniclemark");
mysqli_set_charset($con, 'utf8mb4');
if($con->connect_error)
{
echo $con->connect_errno;
die("Database Connection Failed");
}
if(($_POST['primeiro_nome']) != ""){
$sql = "INSERT INTO users (nome, sobrenome, email)
VALUES('{$con->real_escape_string($_POST['primeiro_nome'])}', '{$con->real_escape_string($_POST['segundo_nome'])}', '{$con->real_escape_string($_POST['o_email'])}')";
$insert = $con->query($sql);
}
?>
And this is working. The data from the form is getting inserted into my database. The problem i have is that the main page closes when the form is submitted and the "signup.php" page opens instead of it.
How do i fix this? I would very much like to have a "Thank you for signing up" popping up on the same page instead of it switching to another one.

You can use AJAX to save data to database and show user a message in same page. Clicking on button a request is sent to server, data is saved into database, on success or failure a response is returned then show a message to user.
Form
First Give ids to input types in you form and add a message div.
<form method="post" class="cd-form">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" id="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" id="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" id="o_email">
</p>
<p class="fieldset">
<input class="full-width" id='saverecords' type="button" value="Sign Up!">
</p>
jQuery Code to send AJAX request to server
Add a script tag include jQuery and inside click event get values of fields and then post to php page:
<script src=”http://code.jquery.com/jquery-3.1.1.min.js”></script>
<script type=”text/javascript”>
$(function(){
$("#saverecords").on('click', function(){
var pnome = $("#primeiro_nome").val();
var sname = $("#segundo_nome").val();
var email = $("#o_email").val();
$.ajax({
method: "POST",
url: "saverecords.php",
data: {"pname": pname, "sname": sname, "email": email},
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
if(result == 1) {
str = 'Signup successfull.';
}else{
str = 'Data could not be saved. Please try again';
}
$("#message").html(str);
});
});
</script>
php server side code:
Please change it according to your requirement
Create a php page: saverecords.php
In saverecords.php you can insert data into database.
$conn = new mysqli($host, $username, $password, $dbname);
$pname = $_POST['pname'];
$sname = $_POST['sname'];
$email = $_POST['email'];
$sql = "insert into tablename (pname, sname, email) values (?, ?, ?) ";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $pname, $sname, $email);
if($stmt->execute()){
$result = 1;
}
}
echo $result;
$conn->close();
If you still face issue please visit this link you can find a detailed tutorial on how to use jQuery Ajax with php mysqli

You have to use AJAX instead of directly submitting the form
You send POST request with JS XMLHttpRequest or Fetch_API to signup.php, get the response and show the "Thank you for signing up" popup

There are mainly two ways you can do this.
1. You can use Jquery $.ajax method to send data, get a response and display your message.
2. Or you can simply let the php page it self do the processing. Add a submit button.
Change your <form action="signup.php" method="post" class="cd-form">to
<form action="" method="post" class="cd-form">
Add below after the form.
<?php
if (isset($_POST["submit"]){
//do your processing here
//at the end of processing you can use echo or HTML to display a thank you message
}
?>

You can make action page run inside an iframe so your form page remains on top
just like that:
<form action="signup.php" method="post" class="cd-form" target="my_iframe">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" name="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" name="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" name="o_email">
</p>
<p class="fieldset">
<input class="full-width" type="submit" value="Sign Up!">
</p>
</form>
<iframe id="my_iframe" name="my_iframe" style="display:none"></iframe>
Also you can send form data to your PHP page by using jquery:
$(document).on('submit','.cd-form',function(e){
e.preventDefault();
$.ajax( {
url: "signup.php",
type: 'POST',
data: new FormData( this ),
cache: false,
dataType: "json",
success: function(r){
alert("data sent successfully");
}
} );
} );

Related

POST Request doesnt get received

So I have this form to add a person to a database:
<div id="formDiv">
<form id="form1" method="post" action="#">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br>
<button type="submit" id="insert" name="insert">Insert</button>
</form>
</div>
And a php File that handles inserting the data into the database:
<?php
include($_SERVER['DOCUMENT_ROOT'].'/website/dbConnection.php');
include($_SERVER['DOCUMENT_ROOT'].'/website/administrator/components/com_backend/backend.php');
if(isset($_POST['insert'])){
$title = $_POST['title'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$group = $_POST['group'];
$company = $_POST['company'];
$sex = $_POST['sex'];
if ($sex == "male"){
$sex = 0;
}
else{
$sex = 1;
}
$query = "INSERT INTO members (Title, Firstname, Lastname, Group, Company, Sex)
VALUES('$title', '$firstname', '$lastname', '$group', '$company', '$sex')";
mysqli_query($GLOBALS['connect'], $query);
}
I know that theres a problem between the 2 files communicating. Because the 2nd File does not receive the POST from the 1st file.
When I use the first file and press the submit Button, it reloads the page and enters nothing into the database.
When I navigate directly to the 2nd file, I can use the form since I include the first file. So I fill out the form, press the submit button and like magic, it works there!
I have checked the path, when including the 1st file 100 times. Its correct. I have checked the path when including the databse connection 100 times. Its correct. I have run the query directly in my database. Its correct.
I am assuming that I made a small mistake, that I cant spot, but the code is so small and simple thats just impossible.
<form id="form1" method="post" action="your_php_file.php">
This will point to your php file and proceed the POST request from your front-end to the back-end. According to your code you don't send anything to your php file. So the code you have there may work but your request is never made to your php file, so nothing is put inside the database.
Edit
In order not to reload the page as you requested then you shouldn't submit the form but you must make an ajax call to the backend side.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div id="formDiv">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br>
<button type="button" id="insert" name="insert">Insert</button>
</div>
<script>
$( "#insert" ).click(function() {
let title = $("input[name=title]").val();
let firstname = $("input[name=firstname]").val();
let lastname = $("input[name=lastname]").val();
let group = $("input[name=group]").val();
let company = $("input[name=company]").val();
let sex = $("input[name=sex] option:selected").text();
$.ajax({
method: 'POST',
url: 'your_php_file.php',
data: {'title': title, 'firstname': firstname, 'lastname': lastname, 'group': group, 'company': company, 'sex': sex},
success: function (response) {
console.log(works)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
})
</script>
That way the data will be send to your backend and you can handle it the same like you did. It's in json format so don't forget to decode if needed.
<div id="formDiv">
<form id="form1" method="post" action="#">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="0">male</option>
<option value="1">female</option>
</select>
<br>
<button type="submit" id="insert" name="insert">Insert</button>
</form>
</div>
<script>
$('#form1').submit(function (e) {
e.preventDefault();
var senddata = $(this).serializeArray();
var sendto = $(this).attr("action");
$.ajax({
url: sendto,
type: 'POST',
data: senddata,
success: function (data) {
$('.messages').html(data);
},
error: function (error) {
$('.messages').html(error);
}
});
});
</script>

Add form ID to JQuery form function

Im in need to create to separate e-mail forms based on AJAX and JQuery.
I need one form to be Standart and other VIP, when getting email from website - i need to indicate from which form customer has send inquiry.
I have sample form for Standard, and need to create VIP form. Imagine it is needed to create forms ID and insert it to JQuery.
Please help
Here is sample form code:
<form id="vip" class="pop_form" action="mail-vip.php">
<h4>ОPlease leave your contacs, we will come back soon!</h4>
<input type="text" name="name" placeholder="Name" required />
<input type="text" name="phone" placeholder="Telephone" required />
<input type="text" name="email" placeholder="E-mail" required />
<input type="text" name="time" placeholder="Callback time" />
<div align="center"><button type="submit">Send</button></div>
</form>
Jquery:
$("form").submit(function() {
$.ajax({
type: "GET",
url: "mail.php",
data: $("form").serialize()
}).done(function() {
alert("Спасибо за заявку!");
setTimeout(function() {
$.fancybox.close();
}, 1000);
});
return false;
});
PHP:
<?php
$recepient = "email;
$sitename = "Website";
$name = trim($_GET["name"]);
$phone = trim($_GET["phone"]);
$email = trim($_GET["email"]);
$email = trim($_GET["time"]);
$pagetitle = "New inquiry for \"$sitename\"";
$message = "Имя: $name \nTelephone: $phone \nE-mail: $email \nTime: $time";
mail($recepient, $pagetitle, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: $recepient");
?>
Thanks!!!
There are various way you can do that.
One of the way could be (minimal change to your code)
Add an hidden field in your form which will be automatically sent to your php and extract it to see it's type.
e.g. <input type="hidden" name="type" value="vip">
So it should look like,
<form id="vip" class="pop_form" action="mail-vip.php">
<h4>ОPlease leave your contacs, we will come back soon!</h4>
<input type="text" name="name" placeholder="Name" required />
<input type="text" name="phone" placeholder="Telephone" required />
<input type="text" name="email" placeholder="E-mail" required />
<input type="text" name="time" placeholder="Callback time" />
<input type="hidden" name="type" value="vip">
<div align="center"><button type="submit">Send</button></div>
</form>
form id is vip i think you need write $("#vip").submit
In the other word,the button where the type "submit " will also submit your form data ,so you don't need write the Ajax
query

AJAX code not updating table

Here is my form, from which i want to update the values. When i try this with simple php+html it works perfectly!! But when i try to post values through ajax call it doesn't work.Any suggestions please.
HTML
<form class="form-block" role="form" action="" method="post">
<div class="form-group">
<?php
$email=$_SESSION["login_email"];
$query=mysqli_query($con,"select * from customers where email='$email'");
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
?>
<label for="name">Full Name</label>
<input type="text" name="name" class="form-control" id="name" value="<?= $row["name"]; ?>" placeholder="Full Name">
<label for="comment">Address</label>
<textarea class="form-control" name="address" id="address" rows="5" id="comment" ></textarea>
<label for="telephone">Telephone</label>
<input type="tel" class="form-control" name="phone" id="phone" placeholder="Enter Mobile Number" value="" >
<label for="city">City</label>
<input type="text" class="form-control" name="city" id="city" placeholder="Enter City" value="<?= $row["city"]; ?>" >
</div>
<?php
}?>
<input type="submit" class="btn btn-default" name="add" id="add" value="Update"/>
<span class='msg'></span>
<div id="error"></div>
</form>
AJAX
$(document).ready(function() {
$('#add').click(function()
{
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name:$("#name").val(),Address:$("#address").val(), Phone:$("#phone").val(), City:$("#city").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
if(data)
{
//$('#output').html(data);
$("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}}});
});});
PHP
<?php
include ("db/db.php");
session_start();
$name=$_POST['Name'];
$address=$_POST['Address'];
$phone=$_POST['Phone'];
$city=$_POST['City'];
$email=$_SESSION['login_email'];
$sql=mysqli_query($con,"Update customers set name='$name',address='$address',phone='$phone',city='$city' where email='$email'");
if($sql)
{
echo "updated";
}
This selector:
$('#add')
doesn't find anything. Because there is no HTML element in your markup with id="add".
You do have an element with name="add". So either add an id to that element:
<input id="add" type="submit" class="btn btn-default" name="add" value="Update"/>
or change your selector to target the existing element:
$('input[name="add"]')
Note: The same is also true of $('#address') and $('#phone'). No such elements exist in your markup. Take a look at the jQuery documentation for selectors.
Remove the IF loop mentioned under
if(isset($_SESSION["login_email"]))
Additionally, you nee to change the button type from submit to button
<input type="submit" class="btn btn-default" name="add" value="Update"/>
Above sends the form, whatever you add to the click event is done in parralel.
<input type="button" class="btn btn-default" name="add" value="Update"/>
only executes your JavaScript, when using:
$('input [name="add"]').click(function(){
// your improved ajax call here
}
Try this:
$.ajax({
.
.
data: {
'Name': $name,
'address': $address,
.
.
}
});

Textarea not sending on submit

Arg, this is so annoying!
I've got a form with a textarea. On submit I use a piece of php to send the data of the form to my email adress. The other data is sending fine (input) but it doesn't send the textarea along!
This is de PHP:
parse_str($_POST['stuff']);
mail("name#myemailadress.nl", "Website formulier", $name, $email, $comments);
This is the code:
<form class="form" id="form" action="" method="POST" >
<p class="name">
<input type="text" name="name" id="name" placeholder="NAAM" >
</p>
<p class="email">
<input type="text" name="email" id="email" placeholder="E-MAILADRES" >
</p>
<p class="text">
<textarea name="comments" id="bericht" placeholder="BERICHT" ></textarea>
</p>
<p class="submit">
<input type="submit" id="versturen_knop" class="submitBtn" value="VERSTUREN" >
</p>
</form>
This is the code that changes the state of the submit button for 3 seconds (message send confirmation) and triggers the PHP
$(document).ready(function(){
$('#form').submit(function(event){
$('.submitBtn').attr('value','BERICHT VERSTUURD!');
setTimeout(function(){
$('.submitBtn').attr('value','VERSTUREN');
}, 2000);
var stuff = $('#form').serialize();
jQuery.ajax({
type: 'POST',
url: 'mail.php',
data:{ 'stuff':stuff, }
});
//Prevents form submission
return false;
});
});
I hope you can help!
Try this instead
<?php
mail("name#myemailadress.nl", "Website formulier", $_POST['name'], $_POST['email'], $_POST['comments']);
?>
Try this code it works,
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form class="form" id="form" action="" method="POST" >
<p class="name">
<input type="text" name="name" id="name" placeholder="NAAM" >
</p>
<p class="email">
<input type="text" name="email" id="email" placeholder="E-MAILADRES" >
</p>
<p class="text">
<textarea name="comments" id="comments" placeholder="BERICHT" ></textarea>
</p>
<p class="submit">
<input type="submit" id="versturen_knop" class="submitBtn" value="VERSTUREN" >
</p>
</form>
<script>
$(document).ready(function(){
$('#form').submit(function(event){
$('.submitBtn').attr('value','BERICHT VERSTUURD!');
setTimeout(function(){
$('.submitBtn').attr('value','VERSTUREN');
}, 2000);
//var stuff = $('#form').serialize();
jQuery.ajax({
type: 'POST',
url: 'mail.php',
data : $('#form').serialize(),
dataType: "json"
});
//Prevents form submission
return false;
});
});
</script>
<?php
parse_str($_POST['stuff']);
mail("aa#ss.com", "Website formulier", "$name, $email, $comments");
?>
You need to add entire contents in double quotes. I have tested it, it works fine.
Based on the circumstances, I suspect you are using a rich text editor like CKEdit or TinyMCE on your textarea.
If such is the case, you should know that these editors do not directly influence the textarea's text, and you must call a special editor-specific method to update it's contents. This method is called automatically on form submit, but for serializing and submitting forms via ajax it is not as straightforward.
If this is the case, please let me know which editor you are using and I can tell you how to correctly prepare the textarea for serialization.
Change following line
data : { 'stuff':stuff, }
to
data : stuff
or you can use
data : $('#form').serialize();
or you may try
data : {
'name' : $('#name').val(),
'email' : $('#email').val(),
'comments' : $('#bericht').val()
}
and retrieve using
$_POST['name']
$_POST['email']
$_POST['comments']

data not being displayed correctly

When I submit a form using the attached code, instead of the message appearing in the div, the screen is refreshing itself and it is holding the completed form in the browser cache. I have obviously got it wrong somewhere and would be grateful if someone could point out my error. I have posted the relevant code, but if there is something I have missed, then please let me know.
In firebug, I can see the correct data that is being returned in the post tab.
I wasn't sure of the best place to post, so if this is incorrect, admin, please amend as you see fit. many thanks.
jquery code
//Begin function to submit report form
$(function(){
$(".frmreport").submit(function(){
var formdata = $(this).serialize();
$ajax({
type: "POST",
url: "../frm10010.php",
data: formdata,
dataType: "json",
success: function(msg){
$("#report_result").html("You have succesfully submitted your report. Thank you.");
}
});
return false;
});
});
// End function to submit report form
frm10010.php
<?php
$dept = mysql_real_escape_string($_POST['dept']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$position = mysql_real_escape_string($_POST['position']);
$feedback = mysql_real_escape_string($_POST['feedback']);
$form = array('dept'=>$dept, 'name'=>$name, 'email'=>$email, 'position'=>$position, 'feedback'=>$feedback);
$result = json_encode($form);
echo $result;
?>
html
<div id="report_result"></div>
<div id="formShow">
<form class=frmreport" method="post" class="webform">
<fieldset>
<legend><span class="subtitle">Submit Technical Report</span></legend>
<label for="dept">Department</label>
<input id="dept" name="dept" class="text" type="text" />
<label for="name">Full Name:</label>
<input id="name" name="name" class="text" type="text" />
<label for="email">Email address:</label>
<input id="email" name="email" class="text" type="text" />
<label for="position">Position:</label>
<input id="position" name="Position" class="text" type="text" />
<label for="feedback">Problem:</label>
<textarea name="feedback" cols="22" rows="5"></textarea>
</fieldset>
<input class="submit" type="submit" name="submit" value="Submit Report" />
<input class="cancel" type="reset" name="cancel" value="Clear Report" />
</form>
</div>
You have couple of errors here
$ajax({ should be $.ajax({
Second you have an error in the form class
<form class=frmreport" method="post" class="webform">
should be
<form class="frmreport" method="post" class="webform">
Don't use
$(".frmreport").submit(function(){
Instead use
$("#sub_btn").click(function(){
And in html
<input class="submit" type="submit" name="submit" value="Submit Report" />
Change it to
<input class="submit" id="sub_btn" type="button" name="submit" value="Submit Report" />
Another way to do it making submit handler false. But above solution will work here. There is also . is missing in ajax call.

Categories