how to submit ajax form on same page in wordpress - php

I'm new to wordpress, I want a customize form, so I created this form where user can input data from front end. But when I submit this form, if it is successful, Within <div id="feedback"></div>, whole page has been shown again. Because of I get all "data" in the ajax success or error function. How can I get only data which is in echo??
<?php
/*
Template Name: Complain
*/
get_header();
?>
<?php
if($_POST['submit']) {
global $wpdb;
$complain_name = $_POST['complain_name'];
if($wpdb->insert(
'wp_complain',
array(
'name'=>$complain_name
)
)==false) {
echo 'Database insertion failed';
}
else {
echo 'Database insertion successful';
}
}
else {
?>
<form action="" method="POST" role="form" class="form-horizontal">
Name <input type="text" id="complain_name" class="form-control" name="complain_name" required="required" autocomplete="off"/>
<input class="btn btn-block" id="submit" type="submit" value="Submit" name="submit">
<div id="feedback"></div>
</form>
<script>
$(document).ready(function(e){
$("form").on('submit',(function(e) {
e.preventDefault();
//heresome other functions for validation
formData =new FormData(this)
$.ajax({
url:'<?php echo content_url(); ?>/themes/abc/complain-detail.php',
type: "POST",
data: formData ,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('#feedback').html(data)
},
error: function(data)
{
$('#feedback').html(data)
}
});
}
));
})
</script>
<?php
}
get_footer();
?>

Use die("...."); instead of echo "...."; witch will stop your PHP code at this line, So your HTML won't be shown.
if( isset($_POST["submit"]) && !empty($_POST["submit"]) ){
if(inserted)
die("Database insertion successful"); //PHP will stop here
else
die("Database insertion failed"); //or here
}
//Your HTML won't be shown ...

const form = document.querySelector(".form-horizontal");
const ajax = new XMLHttpRequest();
form.addEventListener("submit",function(e){
e.preventDefault();
let data = new ForData();
data.append("complain_name",document.querySelector(".form-control").value);
ajax.open("POST",'<?php echo content_url(); ?>/themes/abc/complain-detail.php');
ajax.send(data);
if (this.readyState == 4 && this.status == 200){
document.querySelector(".feedback").textContent = "Thanks for your feedback.";
}else{
document.querySelector(".feedback").textContent = "Sorry,something when wrong,please try again later.";
}
});
<form action="" method="POST" role="form" class="form-horizontal">
Name <input type="text" id="complain_name" class="form-control" name="complain_name" required="required" autocomplete="off"/>
<input class="btn btn-block" id="submit" type="submit" value="Submit" name="submit">
<div id="feedback"></div>
</form>

Related

Submit form using ajax: Was working, now not working?

I have the following HTML form in signup.php:
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
I am trying to submit the form using ajax, without page refresh:
<!-- include files -->
<?php include 'assets/config.php';?>
<?php if(isset($_SESSION["CUSTOMER_ID"])){
header('Location: myaccount.php'); } ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('assets/login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
I am posting the form to do_signup_check.php and running a query to see if the user is already registered. echo 1 for a positive result and 0 for a negative result:
Do_Signup_Check.php:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn)); }
if(mysqli_num_rows($check) > 0){
echo '1';
}else{
echo '0';
}
?>
If the result is 0 then the ajax should load my page do_signup.php.
But alas it is not getting this far. It was working and then i switched off the computer and came back to it and now it won't work.
Please can someone show me where I've gone wrong?
if(result == 0){ here result is not using in success function:
you must need to pass resultant variable here:
success: function () {
as:
success: function (result) {
Now, you can use your condition if(result == 0){
Second, i suggest you to pass dataType: 'html' in your ajax request.
Edit:
You are using <?php if(isset($_SESSION["CUSTOMER_ID"])){ line in your code, if you are not using session_start() in your code then this check will not work.
For this line data:{"name":name,"email":email}, i didnt see name and email in your code, where you define these 2 variables which you are using in your ajax params.

Google reCaptcha validate using jquery AJAX

I don't know how can i apply this to my login page, once captcha success response on ajax then submit form.
Here's my html form(i leave action null because i'm still in testing)
<form action = "" method = "post">
<input type = "text" id = "email" name = "email">
<input type = "password" id = "pass" name = "password">
<div class = "form-group col-lg-6">
<div class="g-recaptcha" data-sitekey="MY_KEY"></div>
</div>
<input type = "button" id = "submit" value = "submit">
</form>
Here's how i understand ajax on captcha sending captcha word.. if captcha success submit form if failed i will give an alert.
$('#submit').click(function() {
var captcha = "captcha";
$.ajax({
url: "captcha.php",
method: "post",
data:{captcha:captcha},
success:function(data){
if(data=='success'){
$('form').submit();
}
}
else{
alert('captcha failed. try again');
}
});
});
my captcha.php how i receive $_POST['captcha']
<?php
if($_POST['captcha']){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = 'MY_SECRET_KEY';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if($data->sucess==true){
echo "success";
}
else{
echo "failed";
}
}
?>
please help me to understand how will it work and how can it be done using AJAX
THANK YOU IN ADVANCE :)
UPDATE
i just notice how can i $_POST['g-recaptcha-response']; ??
You can use this code:
HTML Code:
<form action="" method="POST" id="loginForm">
<input type="text" id = "email" name="email">
<input type="password" id="pass" name="password">
<textarea type="text" name="message"></textarea>
<div class="g-recaptcha" data-sitekey="10LDDpf0ehtMZY6kdJnGhsYYY-6ksd-W"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
JavaScript
$(document).ready(function() {
var loginForm = $("#loginForm");
//We set our own custom submit function
loginForm.on("submit", function(e) {
//Prevent the default behavior of a form
e.preventDefault();
//Get the values from the form
var email = $("#email").val();
var pass = $("#pass").val();
//Our AJAX POST
$.ajax({
type: "POST",
url: "login.php",
data: {
email: email,
password: pass,
//This will tell the form if user is captcha varified.
g-recaptcha-response: grecaptcha.getResponse()
},
success: function(response) {
console.log(response);
//console.log("Form successfully submited");
}
})
});
});
PHP Code:
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '10LDDpf0ehtMZY6kdJnGhsYYY';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
//captacha validated successfully.
$email = !empty($_POST['email'])?$_POST['email']:'';
$password = !empty($_POST['password'])?$_POST['password']:'';
echo "captacha validated successfully.";
else:
echo "Robot verification failed, please try again.";
endif;
else:
echo 'invalid captcha';
endif;
else:
//Nothing
endif;
?>
I am using re-captcha validation using jQuery / ajax as per below :
<script src="https://www.google.com/recaptcha/api.js" >;
<form method="post" name="contactForm">
<input type="text" name="fname"/>
<input type="text" name="lname"/>
<input type="text" name="Phone"/>
<div class="g-recaptcha" data-sitekey="[site_key]" data-callback="onReturnCallback" data-theme="dark"></div>
<input value="submit" type="submit"/>
</form>
Validation / ajax :
//Initialize jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var onReturnCallback = function(response) {
var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';
$.ajax({ 'url' : url,
dataType: 'json',
data: { response: response},
success: function(result) {
var res = result.success.toString();
alert(res);
if (res == 'true') {
document.getElementById('g-recaptcha').innerHTML = ' Your Success Message';
}
}
});
};
</script>

Pop-up message after submitting a form with php

I'm trying to get a pop-up message saying if it was successfully submitted or not without having to go to a different page.
Now chrome gives me the pop-up message but it redirects me to a blank page after.
Here is my current code.
<?php
include "header.php";
include "conexao.php";
echo "<h1 align='center'>Pagina para alterar produtos</h1><div class='container'><hr>";
$referencia=$_GET['id'];
$sql = "SELECT * ";
$sql = $sql . " FROM tb_produto ";
$sql = $sql . " WHERE pr_codigo='".$referencia."'";
$produtos = $db->query($sql);
foreach ($produtos as $produto) {
$referencia = $produto["pr_codigo"];
$nome = $produto["pr_descricao"];
$preco = $produto["pr_preco"];
$disponivel = $produto["disponivel"];
}
echo "<h2>Referencia: ".$referencia."</h2>";
echo "<h2>Nome: ".$nome."</h2><hr>";
?>
<form action="confirmaAlterar.php">
<div class="form-group">
<label>Referencia</label>
<input class="form-control" type="text" name="referencia" value="<?php echo $referencia?>">
</div>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" name="nome" value="<?php echo $nome?>">
</div>
<div class="form-group">
<label>Preço</label>
<input class="form-control" type="text" name="preco" value="<?php echo $preco?>">
</div>
<button class="btn btn-primary">Alterar</button>
</form>
Here is where it submits the information of the form.
<?php
include "header.php";
include "conexao.php";
$nome=$_GET['nome'];
$referencia=$_GET['referencia'];
$preco=$_GET['preco'];
$sql="UPDATE tb_produto SET pr_descricao='".$nome;
$sql.="', pr_preco=".$preco;
$sql.= " WHERE pr_codigo='".$
try{
$comando=$db->prepare($sql);
$comando->execute();
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header( "refresh2;Location:index.php" );
}
catch (PDOException $e){
echo "A";
}
To pass values using ajax. Form:
<form id="form">
<input type="text" value="test" name="akcija">
</form>
All inputs fields values in your form will be passed.
Ajax:
jQuery(function(){
$('#form').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'yoururl.php', //URL of page where u place query and passing values
data: $('#form').serialize(), //seriallize is passing all inputs values of form
success: function(){ //on success function
$("#input").attr("disabled", true); //example
$("#input").removeClass('btn-primary').addClass('btn-success');//example
},
});
}
});
And on the ajax page you can get values by
$akcija = $_POST['akcija']
for this Problem you must use ajax method .
1- create html form and all input Required .
<form id="contactForm2" action="/your_url" method="post">
...
</form>
2- add jQuery library file in the head of html page .
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
...
3- add this method Under the jQuery library
<script type="text/javascript">
var frm = $('#contactForm2');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data == 'pass')
alert('ok');
else(data == 'fail')
alert('no');
}
});
ev.preventDefault();
});
</script>
4- in your_url .php file
<?php
$a = ok ;
if( $a == 'ok' ){
echo 'pass';
}else{
echo 'fail';
}
?>
this top answer is easy management form with jquery , but you need managment Complex form better use this library http://jquery.malsup.com/form/

Complete form submit action without reloading the page

I want the form-data to be sent to my php file after submitting it without loading the php file page. Then the data sent must fade in the feeds after processing. Can anyone help me? Here are my codings:
home.php:
<script>
$(document).ready(function(){
$('#content').load('feeds.php');
}, 1000
);
</script>
feeds.php:
<?php
//after connecting to my database and all
$sql = mysql_query("SELECT * FROM `posts` ORDER BY `post_id` DESC");
while($row = mysql_fetch_assoc($sql)) {
echo '<div id="post">' . $row['post'] . '</div><br />';
}
?>
Here's the form for submitting the post
<form id="post" action="post.php" method="POST">
<textarea name="post" width=300 height=150></textarea>
<input type="submit" value="Post" id="submit">
</form>
post.php:
//after connecting to the database
$post = $_POST['post'];
if($post != '') {
mysql_query("INSERT INTO `posts` (`post`) VALUE('$post')");
}
else {
echo 'Form is empty!';
}
#content:
<div id="content"></div>
nothing else.
Please help me by modifying this code! Thanks in return!
change this from
<form id="post" action="post.php" method="POST">
<textarea name="post" width=300 height=150></textarea>
<input type="submit" value="Post" id="submit">
</form>
to
<form id="form1">
<textarea id="post" width=300 height=150></textarea>
<input type="button" value="Post" id="submit">
</form>
And put this script on javascript area :
$('#submit').click(function(event) {
event.preventDefault(); /* Stops default form submit on click */
var post = $('#post').val();
$.ajax({
url: "post.php?",
data: 'post=' + post,
type: "POST",
success: function(data){
$('#content').empty();
$('#content').load('feeds.php');
}
});
});
I did not test it , but it should be something like this.
Hope this help.
The best solution should be JQuery along with AJAX. Send the data to any page using AJAX and based on the response you can fade the data.
Here is sample implementation:
jQuery(function($){
$("#post").submit(function(){
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(){
alert("data sent");
}
});
return false;
});

jQuery / php - Multply forms on page, submit only one

I have two forms on my website, and I use jQuery to submit them, to my PHP script.
These are the forms:
<form method="post" class="settings-form" id="passwordSettings">
<label id="npasswordbox" class="infoLabel">New Password: </label>
<input type="password" name="npassword" size="50" value="" >
<div class="move"></div>
<label id="cnpasswordbox" class="infoLabel">Confirm: </label>
<input type="password" name="cnpassword" size="50" value="" >
<button class="btn" name="passwordSetings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
And the next:
<form method="post" class="settings-form" id="normalSettings">
<label id="npasswordbox" class="infoLabel">New Username: </label>
<input type="text" name="username" size="50" value="" >
<div class="move"></div>
<button class="btn" name="normalSettings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
Here is the jQuery I have written for these two forms:
$(function() {
$('form#passwordSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
function proccessPWData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
$(function() {
$('form#normalSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#normalSettings').serialize(),
function (data) {
proccessData(data);
}
);
return false;
});
});
function proccessData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
And then the PHP code:
if(isset($_POST['normalSettings']))
{
$username = inputFilter($_POST['username']);
if(!$username){
$error ="no username";
}
if(!$error){
echo "success!";
}
}
if(isset($_POST['passwordSettings']))
{
$password = inputFilter($_POST['npassword']);
if(!$username){
$error ="no pw";
}
if(!$error){
echo "success!";
}
}
My problem is, that whenever I submit one of these forms, I see the form with my $error in the #status div.
How can I have multiply forms on one page, but submit the correct ones?
$(function() {
$('form#passwordSettings').submit(function(e){
e.preventDefault(); // prevents the default action (in this case, submitting the form)
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
or you could just give an hidden input-field with it
<input type="hidden" name="_normalSettings">
and check in your PHP
if (isset($_POST['_normalSettings']) // ...
This is basically just answer to your question: "How can I have multiple forms on one page, but submit the correct ones?"
I have many dynamically generated forms on a single page and I send them to process file one by one. This is one form simplified:
<form name="form" id="form">
<!--form fields
hidden field could be used to trigger wanted process in the process file
-->
<input type="hidden" name="secret_process_id" value="1" />
<a class="button_ajax">Send form</a>
</form>
<div id="process_msg<?php echo $id; ?>"></div>
And here's the form submit function:
$(document).ready(function() {
$('.submit_ajax').click(function() { //serializes the parent form
//alert($(this).serialize());
dataString = $(this).parent().serialize();
//if you want to echo some message right below the processed form
var id = /id=\d+/.exec(dataString);
var id = /\d+/.exec(id);
$.ajax({
type: 'post',
url: '_process.php?ajax=1', //some or none parameters
data: dataString,
dataType: 'html',
success: function(data) {
$('#process_msg' + id).fadeIn(400);
$('#process_msg' + id).html(data);
}
}); //end of $.ajax
return false;
});
});
All you need is a process file/function and you are ready to go. Works just fine with one or dozens of forms. There you can do something like this:
if ($_POST['secret_process_id']==1){
//do something
}
if ($_POST['secret_process_id']==2){
//do something else
}
//etc.

Categories