Create a form and insert the data into database using $wpdb - php

I have a custom WordPress page template where I wrote a basic form structure like this:
<div class="my-form">
<h2>WILL YOU ATTEND?</h2>
<form action="#" autocomplete="off" method="POST">
<input class="input" type="text" spellcheck="false" name="name" placeholder="Name" required>
<input class="input" type="email" spellcheck="false" name="email" placeholder="E-mail" required>
<label class="ans">Yes
<input type="radio" name="radio">
<span class="checkmark"></span>
</label>
<label class="ans">No
<input type="radio" name="radio">
<span class="checkmark"></span>
</label>
<button> SUBMIT </button>
</form>
</div>
Now once the submit button is clicked, I'm trying to figure out how to create a table in WordPress database, and insert the form data into it using $wpdb.
PS: I left the action attribute empty because I don't know how to go about this exactly.

There are several ways to do that. Below I just showed you one way:
I Assume your table name is wp_customform which has id, name, email, and radio columns.
Now you've to modify your HTML code like the below. I added some JS too.
<div class="my-form">
<h2>WILL YOU ATTEND?</h2>
<form class="custom-form-class" action="#" autocomplete="off" method="POST">
<!-- Action is here but hidden. This will be use in php side -->
<input type="hidden" name="action" value="sample_custom_form_action">
<input class="input" type="text" spellcheck="false" name="name" placeholder="Name" required>
<input class="input" type="email" spellcheck="false" name="email" placeholder="E-mail" required>
<label class="ans">Yes
<input type="radio" name="radio">
<span class="checkmark"></span>
</label>
<label class="ans">No
<input type="radio" name="radio">
<span class="checkmark"></span>
</label>
<button> SUBMIT </button>
</form>
</div>
<script>
// Javascript to send ajax request
jQuery(document).on('submit', '.custom-form-class', function(e){
let formData = jQuery(this).serialize();
// Change ajax url value to your domain
let ajaxurl = 'http://YOURSITE.COM/wp-admin/admin-ajax.php';
// Send ajax
jQuery.post(ajaxurl, formData, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
That pieces of code will send your form data to the PHP side. You have to use the below code to process the form data in your function.php file.
add_action( 'wp_ajax_sample_custom_form_action', 'prefix_save_custom_form_data' );
add_action( 'wp_ajax_nopriv_sample_custom_form_action', 'prefix_save_custom_form_data' );
function prefix_save_custom_form_data(){
global $wpdb;
// Get the values
$name = isset( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : ''; // Empty value if data not set
$email = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : ''; // Empty value if data not set
$radio = isset( $_POST['radio'] ) ? sanitize_text_field( $_POST['radio'] ) : ''; // Empty value if data not set
// Assume your table name is wp_customform
$your_table_name = $wpdb->prefix . 'customform';
// Insert into database
$wpdb->insert(
$your_table_name,
array(
'name' => $name,
'email' => $email,
'radio' => $radio,
)
);
// Send insert id as ajax response
echo $wpdb->insert_id;
// Use die to stop the ajax action
wp_die();
}
The codes are not tested but they should work. I am attaching some reference links below:
Ajax overview: https://codex.wordpress.org/AJAX_in_Plugins
For Insert: https://developer.wordpress.org/reference/classes/wpdb/insert/
For create table: https://developer.wordpress.org/reference/functions/dbdelta/

Related

Form Issue on cloning value of one input to other input with same name

I have two inputs with same name in my form ( I use css to display one or the other depending of the screen size ), but on the form submition, is only gets the last one's value, which is a problem to me because is can be empty if I display:none it. I figured out a trick which consists of cloning the input value which is not empty to the other, so that when I send my POST variable to PHP, any one can return the value entered.
Here's my HTML code :
<form id="form" class="form" name="postuler" method="post" action="receive-post.php" enctype="multipart/form-data" novalidate>
<div class="not-hidden">
<label for="mail">Email address <span class="required">*</span></label>
<input type="email" class="email" placeholder="ex: jdoe#exelcia-it.com" name="email" id="email" maxlength="40" />
</div>
<div class="hidden-fields">
<label for="mail">Email address <span class="required">*</span></label>
<input type="email" class="email" placeholder="ex: jdoe#exelcia-it.com" name="email" id="email" maxlength="40"/>
</div>
<input type="submit" name="upload" id="send" value="Submit" class="postu"/>
</form>
And here's my jQuery code :
$(document).ready(function(){
$('#envoyez').on('click', function () {
if($.trim($('.hidden-fields #email').val())==0){
$('.hidden-fields #email').val()==$.trim($('.not-hidden #email').val())
} else if ($.trim($('.not-hidden #email').val())==0){
$('.not-hidden #email').val()==$.trim($('.hidden-fields #email').val())
}
})
})
Here's my php code :
if(!empty($_POST['email'])){
var_dump($_POST['email']);
} else {
echo "Theres a problem somewhere" ;
}
The problem that I get is that if I fill the not-hidden field, on the php side I get an empty string because it always retrieve the hidden-fields value.
Hello you can try like this
<input type="email" class="email" placeholder="ex: jdoe#exelcia-it.com" name="email[]" id="email" maxlength="40" />
<input type="email" class="email" placeholder="ex: jdoe#exelcia-it.com" name="email[]" id="email" maxlength="40"/>
Then you can loop in the php script to check if the array is empty and get the populated key.
UPDATE
Here's how you can check the array and get the populated key
if (isset($_POST['email'])) {
$emails = $_POST['email'];
foreach ($emails as $key => $email) {
if (!is_null($email)) {
echo $email;
break;
}
}
}
This is basic check you can save the email in variable or perform additional checks but this is the basic to get the value
There are couple of things wrong in your jQuery code, such as:
After triming the input text field's value, you're directly comparing it with 0, which is wrong. Instead you should compare it's length with 0.
$('... #email').val()==$.trim($...), == is for comparison and = is for assignment.
So your jQuery code should be like this:
$(document).ready(function(){
$('#envoyez').on('click', function () {
if($.trim($('.hidden-fields #email').val()).length == 0){
$('.hidden-fields #email').val($.trim($('.not-hidden #email').val()));
} else if ($.trim($('.not-hidden #email').val()).length == 0){
$('.not-hidden #email').val($.trim($('.hidden-fields #email').val()));
}
})
});
With the above snippet, it doesn't matter which input text field gets filled, the other field will also get updated with the same value automatically. And once you hit the submit button, you would get just one email id with the POST request.
Another approach would be to use name attribute as name='email[]' for both of your email input fields. There's no need to use any jQuery here.
<input type="email" class="email" placeholder="ex: jdoe#exelcia-it.com" name="email[]" id="email" maxlength="40" />
<input type="email" class="email" placeholder="ex: jdoe#exelcia-it.com" name="email[]" id="email" maxlength="40"/>
This way, you can access the submitted email id(doesn't matter which input text field gets filled) in the following way,
if(isset($_POST['email'])){
$email = array_values(array_filter($_POST['email']));
if(count($email))
echo $email[0];
else
echo "Theres a problem somewhere";
}

Send html form data to database through php without switching page

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");
}
} );
} );

How to retrieve the dynamically generated or repeated field values in a php file?

I have a form as follow.
<form action="action.php" method="post">
<div class="add_another">
<label for="BrotherAdmissionNumber" class="p-label-required">Admission Number</label>
<input type="text" name="BrotherAdmissionNumber[]" placeholder="Admission Number" />
<label for="varName" class="p-label-required">Name</label>
<input type="text" name="BrotherName[]" placeholder="Name" class="form-control" />
<label for="BrotherGrade" class="p-label-required">Grade</label>
<input type="text" id="varGrade" name="BrotherGrade[]" placeholder="Grade" class="form-control" />
<label for="BrotherClassTr" class="p-label-required">Class Teacher</label>
<input type="text" id="varClassTeacher" name="BrotherClassTr[]" placeholder="Class Teacher" class="form-control" />
<button class="btn add_field_button" style="float: right;">Add Another Brother</button>
</div>
<button class="submit" >Submit</button>
</form>
And I am using following jQuery to add another section to the form.
This will create the set of fields again.
<script>
var max_fields = 10;
var wrapper = jQuery(".add_another");
var add_sec_3 = '<div class="add_another" style="border-top: 1px solid #f0f0f0; border-spacing: 7px;"><label for="BrotherAdmissionNumber" class="p-label-required">Admission Number</label><input type="text" name="BrotherAdmissionNumber[]" placeholder="Admission Number" /><label for="varName" class="p-label-required">Name</label><input type="text" name="BrotherName[]" placeholder="Name" class="form-control" /><label for="BrotherGrade" class="p-label-required">Grade</label><input type="text" id="varGrade" name="BrotherGrade[]" placeholder="Grade" class="form-control" /><label for="BrotherClassTr" class="p-label-required">Class Teacher</label><input type="text" id="varClassTeacher" name="BrotherClassTr[]" placeholder="Class Teacher" class="form-control" />Remove</div>';
jQuery(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
jQuery(wrapper).append(add_sec_3); //add section
jQuery('.add_another .add_another:last').hide();
jQuery('.add_another .add_another:last').show('fast');
}
});
</script>
When clicking on add another button a section is added successfully.
So that's fine.
My issue is, I tried several methods of retrieving for arrays but nothing works.
I want to create another form with hidden fields of brother details to send it to another page.
How can I show the all generated fields values in a php page during the submission?
How do I have to update this action.php file?
action.php
<?php
$BrotherAdmissionNumber = $_POST['BrotherAdmissionNumber'];
$BrotherName = $_POST['BrotherName'];
$BrotherGrade = $_POST['BrotherGrade'];
$BrotherClassTr = $_POST['BrotherClassTr'];
foreach(){
//brothers details start here
?>
<form action="action2.php" method="post">
Admission Number :<?= $BrotherAdmissionNumber ?>
<input type="hidden" value="<?= $BrotherAdmissionNumber ?>" name="BrotherAdmissionNumber" />
Name :<?= $BrotherName ?>
<input type="hidden" value="<?= $BrotherName ?>" name="BrotherName" />
Grade :<?= $BrotherGrade ?>
<input type="hidden" value="<?= $BrotherGrade ?>" name="BrotherGrade" />
Teacher :<?= $BrotherClassTr ?>
<input type="hidden" value="<?= $BrotherClassTr ?>" name="BrotherClassTr"/>
<button name="send_to_other_page">CONFIRM</button> <!-- when this button is clicked the form shoukd send the hidden values -->
</form>
<?php } ?>
Now when send_to_other_page button is clicked the form should send the hidden values to next page action2.php
What I have to update in foreach loop above?
How I can collect these details in action2.php ?
Take a look at this link
You have to serialise form data and then you can easily retrieve and save in database.

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

Jquery:load upload result from iframe

Here is my form
HTML
<div id="contactus">
<form action="carrer_.php" method="POST" ENCTYPE="multipart/form-data" class="contactUs" id="send_cv" target="carrer_iframe">
<label> Name
<input type="text" name="name" />
</label>
<label> Email
<input type="text" name="email" />
</label>
<label> Mobile
<input type="text" class="mobile" name="mobile" />
</label>
<label> Cv
<input type="file" id="cv" name="file" />
</label>
<label> Other Info
<textarea name="message" cols="1" rows="1"></textarea>
</label>
<input type="submit" value="send" />
</form>
<div id="iframe_result"></div>
<iframe name="carrer_iframe" id="carrer_iframe" src="carrer_.php" style="width;0;height:0;display:none;" ></iframe>
</div>
Js
$('#send_cv').submit( function(){
$("#carrer_iframe").contents().html("") ;
$("#iframe_result").load(function(){
alert( 1 ) ;
response = $("#carrer_iframe").contents().find("body:last").text();
alert( response ) ;
$("#iframe_result").html(response).show();
});
} ) ;
After submit the form ( Nothing happened??? )
How can i get the result from the hidden iframe and alert it && Or what is my error
Best regards
There seems to be nothing preventing the form from submitting normally. Try passing the event from the submit function and calling .preventDefault.
$('#send_cv').submit( function(event){
// Preventing the default form submission action
event.preventDefault();
$("#carrer_iframe").contents().html("") ;
$("#iframe_result").load(function(){
alert( 1 ) ;
response = $("#carrer_iframe").contents().find("body:last").text();
alert( response ) ;
$("#iframe_result").html(response).show();
});
} ) ;
Edit:
As far as I know .show() only effects the display attribute. Therefore setting the wdith/height to 0 will mean the iframe will never show.

Categories