PHPMailer Ajax: File Attachment - ajax

I'm trying to send an attachment via email with Phpmailer, but I get the error: Could not access file: pdf_consenso/.
What am I doing wrong ?
File attachments aren't included in the email sent by PHPMailer when submitting the form via AJAX.
Here is the PHP Mailer:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
$codPre = $_POST['codPre'];
try {
if (isset($_FILES['pdf_consenso']['name']) && $_FILES['pdf_consenso']['name'] != "") {
$file = "pdf_consenso/" . basename($_FILES['pdf_consenso']['name']);
move_uploaded_file($_FILES['pdf_consenso']['tmp_name'], $file);
} else
$file = "";
$mail = new PHPMailer();
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 2; // Enable verbose debug output
//$mail->CharSet = 'UTF-8';
$mail->Host = ; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ; // SMTP username
$mail->Password = ; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587; // TCP port to connect to
$mail->addAttachment($file);
$mail->setFrom('');
$mail->addAddress(''); // Add a recipient
$mail->Subject = "Consenso Informato - Cod.Prenotazione: " . $codPre;
$mail->Body ="Consenso Informato";
$mail->AltBody = "Consenso Informato";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "<script>alert('Message has been sent')</script>";
}
catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Here is the contact form :
<form id="uploadFile" enctype="multipart/form-data">
<div class="field has-addons">
<p class="control">
<input class="input" id="codPre" type="text" placeholder="Codice prenotazione">
</p>
</div>
<input type="file" id="pdf_consenso" name="pdf_consenso" hidden>
<label class="button" for="pdf_consenso">Scegli file</label>
<span id="file-chosen">Nessun file scelto</span>
<footer class="modal-card-foot">
<button type="submit" class="button is-rounded bt-send"><strong>INVIA DOCUMENTO</strong></button>
<button class="button is-rounded bt-erase">ANNULLA</button>
</footer>
</form>
Here is AJAX Call:
// FORM DI CONTATTO - PAGINA DOVE SIAMO
$("#uploadFile").submit(function (event) {
// cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm() {
//Initiate Variables With Form Content
//Creazione di un oggetto FormData…
var datiForm = new FormData();
//… aggiunta del nome…
datiForm.append('codPre',$("#codPre").val());
//… aggiunta del file
datiForm.append('pdf_consenso',$('#pdf_consenso')[0].files[0]);
//Toast messaggio in uscita
iziToast.show({
color: 'light',
timeout: false,
icon: 'fas fa-paper-plane',
message: '<strong>Invio!</strong></br>Il tuo documento sta per essere inviato...',
messageLineHeight: 20,
messageSize: 15,
position: 'center', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: '#00909D',
backgroundColor: ' #9ad3ca',
titleColor: '#222',
messageColor: '#222',
iconColor: '#F7F7F7',
closa: false,
displayMode: 'once',
pauseOnHover: false,
resetOnHover: false,
});
$.ajax({
type: "POST",
url: "fileUpload.php",
data: datiForm,
cache: false,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if (data == 'Message sent') {
iziToast.destroy();
formSuccess();
}
}
});
}
function formSuccess() {
$("#uploadFile")[0].reset();
// custom toast
iziToast.show({
color: 'light',
icon: 'fas fa-paper-plane',
message: '<strong>Grazie!</strong></br>Il tuo messaggio è stato inviato',
messageLineHeight: 20,
messageSize: 15,
position: 'center', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: '#00909D',
backgroundColor: ' #9ad3ca',
titleColor: '#222',
messageColor: '#222',
iconColor: '#F7F7F7',
closa: false,
displayMode: 'once',
pauseOnHover: false,
resetOnHover: false,
});
}

Related

I am send dropzone file through ajax but it show ERROR : "You did not select a file to upload" in Codeigniter 3

View
Image
<!------------------------ Bootstarp Source File ------------------------>
<link rel="stylesheet" href="<?php echo base_url('assets/source_files/bootstrap.min.css');?>" >
<!------------------------ Dropzone Source File ------------------------>
<link rel="stylesheet" href="<?php echo base_url('assets/source_files/dropzone.min.css');?>" >
<label class="form_lable">Select Image </label>
<div class="dropzone-container col-md-6" id="demo-dropzone" >
`your text`
<p >
<div class="dz-default dz-message" >
<div class="dz-icon">
<i class="demo-pli-upload-to-cloud icon-5x"></i>
</div>
<div>
<span class="dz-text">Drop files to upload</span>
<p class="text-sm text-muted">or click to pick manually</p>
</div>
</div>
<div class="fallback">
<input type="file" name="userfile" id="userfile" />
</div>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="submit_btn">Submit</button>
</div>
</form>
">
">
">
$('#demo-dropzone').dropzone({
url:"",
autoProcessQueue: false,
addRemoveLinks: true,
multiple:false,
uploadMultiple:true, // uplaod files in a single request
parallelUploads: 1,
maxFiles: 1,
maxFilesize: 500,
acceptedFiles: ".jpg, .png, .jpeg",
init: function() {
var myDropzone = this;
myDropzone.on('maxfilesexceeded', function(file) {
this.removeAllFiles();
this.addFile(file);
});
this.on("removedfile", function(file) {
});
// Update selector to match your button
$("#submit_btn").click(function(e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on("successmultiple", function(file, response) {
if (response && file) {
console.log(response);
}
});
}
});
# Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Image_upload extends CI_Controller
{
public function index(){
$this->load->view('image_send');
}
`File upload funxction`
public function do_upload(){
$image_name = $_FILES['file']['name'][0];
$target= $_FILES['file']['tmp_name'][0];
$target_file = basename($image_name);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$custom_file=basename(uniqid().'.'.$imageFileType);
if(is_dir('upload_image')){
echo "is present";
}
else{
mkdir('upload_image');
}
$config['upload_path'] = 'upload_image/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $image_name;
$this->upload->initialize($config);
$this->load->library('upload',$config);
if ($this->upload->do_upload('userfile'))
{
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
}
?>
First of all you need to fix your view to have tag to warp out your input.
<form role="form" id="yourFormId" action="#" method="post" enctype='multipart/form-data'></form>
Second, get your form id and set the ajax like this
var frm = $('#yourFormId');
frm.submit(function (e) {
e.preventDefault();
var form_data = new FormData();
var file_data = $('#yourFileInputID').prop('files')[0];
form_data.append('file', file_data);
$.ajax({
type : "POST",
url : TheUrl,
processData : false,
contentType : false,
cache : false,
data : form_data,
dataType : 'json',
success: function (data) {
//Your Code Goes Here..//
}, error: function () {
// Your Code Goes Here //
}
});
});

Wordpress Sending email through Ajax without page refresh hangs on admin_ajax.php

I have this test page on a website - https://piclits.com/test-slideshow/
It displays a bunch of images/PICLITS and grabs them randomly from a folder 12 at a time into a slideshow.
I want to email the main image without refreshing the page (which would bring up 12 new images) from the email button which opens up a popup to add email addresses.
All is good - I can grab the image and mail it but the script does something wacky where it flashes on the page and then hangs up at admin-ajax.php rather than just staying on the page and sending the email.
My Form:
<div class="ajax-form-container" style="float: left">
<form id="ajaxformid" action="" method="POST">
<p>Email this PIC-LIT to a friend.<br />You may include multiple emails if you separate them with a comma.</p>
<ul style="list-style-type: none;">
<li>Email: <textarea name="piclit_email" id="piclit_email" rows="4" cols="50" autofocus=""></textarea><input type="hidden" name="founder_piclit" id="founder_piclit" value=""></li>
<li><input type="hidden" name="piclit_bcc" class="piclit_bcc" value="0"></li>
<li>bcc: <input type="checkbox" name="piclit_bcc" class="piclit_bcc" value="1">
<?php wp_nonce_field( 'fiveb_ajax_nonce', 'fiveb_nonce_field' ); ?></li>
<li><input type="submit" name="submit" value="Send"></li>
</ul>
</form>
<div id="ajax_success" style="display: none">Email sent.</div>
<div id="ajax_error" style="display: none">There was an error. Sorry your email was not sent.</div>
</div>
Javascript
<script>
jQuery('#ajaxformid').submit(function(e) {
e.preventDefault();
var piclit_email = jQuery( "#piclit_email" ).val();
if (piclit_email == '')
alert("Please fill in all fields to send an email.");
else {
var founder_piclit = jQuery( "#founder_piclit" ).val();
// alert (founder_piclit);
var piclit_bcc = jQuery('.piclit_bcc').val();
var formData = {
piclit_email: piclit_email,
founder_piclit: founder_piclit,
piclit_bcc: piclit_bcc,
action: 'fiveb_ajax_mail',
};
jQuery.ajax({
type : 'POST',
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>',
dataType : 'json',
data : formData,
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
}
});
</script>
and php:
function fiveb_function() {
$subject = 'View A Founder PIC-LIT from piclits.com';
$piclit_email = strval($_REQUEST['piclit_email']);
$founder_piclit = strval($_REQUEST['founder_piclit']);
$piclit_bcc = strval($_REQUEST['piclit_bcc']);
if ($piclit_bcc) {
$headers[] = 'Bcc: '.$piclit_email;
}
$message = '<html><head><title>Founder PIC-LIT</title></head><body><table border="0" cellspacing="2" cellpadding="20" bgcolor="#ffffff" width="100%"><tbody><tr><td></td><td width="600"><p style="text-align: center">Hello!<br />View A Founder PIC-LIT from piclits.com.</p></td><td></td></tr><tr><td></td><td><img src="'.$founder_piclit.'" alt="Founder PIC-LIT" width="600" style="display:block;width:100%" /></td><td></td></tr></tbody></table></body></html>';
$headers[] = 'From: PIC-LITS <hello#piclits.com>';
$headers[] = 'Content-Type: text/html; charset=UTF-8';
if ($bcc) $sent_mail = wp_mail( "", "$subject", $message, $headers );
else $sent_mail = wp_mail( "$piclit_email", "$subject", $message, $headers );
if ($sent_mail) {
echo ('email sent');
die();
} else {
echo ('There was an error. Sorry your email was not sent.');
die();
}
}
add_action("wp_ajax_fiveb_function", "fiveb_function");
add_action("wp_ajax_nopriv_fiveb_function", "fiveb_function");
Seems like I am so close but I cannot get the script to stop hanging up on admin-ajax.php. Any help would be so appreciated! Maybe it has something to do with my popup? I am out of ideas
Your code will look like this.
Note - Form action should be blank.
<form action="" method="POST" id="ajaxformid">
</form>
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
wp_localize_script( 'custom-js', 'fiveb_ajax_mail', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
add_action("wp_ajax_fiveb_ajax_mail", "fiveb_ajax_mail");
add_action("wp_ajax_nopriv_fiveb_ajax_mail", "fiveb_ajax_mail");
function fiveb_ajax_mail()
{
$formdata = $_post['formdata'];
wp_mail($to,$subject,$message,$header);
return 'true';
wp_die();
}
//add below js in custom.js file
$('#ajaxformid').submit(function (e) {
e.preventDefault();
jQuery.ajax({
type: "post",
dataType: "json",
url: fiveb_ajax_mail.ajax_url,
data : {action: "fiveb_ajax_mail","formdata":"your form data variable place here"},
success: function(msg){
console.log(msg);
}
});
}
In my local system, it is working fine.

Cropped image encrypted data not post in codeigniter on live server. Why?

I have a situation where a user select photo and cropped it.After cropping encoded data passed to hidden input has successfully but when posting my form the image data not post.Only blank page shown.
Same code are working fine on local server. But on live server this happened to me.
Let me share my code. Please guide me where i am doing wrong.
$(".gambar").attr("src", "<?php echo base_url().'assets/img/users/defualt.jpg");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 150,
height: 150,
type: 'circle'
},
boundary: {
width: 265,
height: 265
},
enforceBoundary: false,
enableExif: true,
enableOrientation: true,
orientation: 4,
});
$('#cropImagePop').on('shown.bs.modal', function(){
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
});
});
$('.item-img').on('change', function () {
imageId = $(this).data('id');
tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId);
readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
format: 'jpeg',
size: {width: 150, height: 150}
}).then(function (resp) {
$('#imageEncoder').val(resp);
$('#item-img-output').attr('src', resp);
$('#cropImagePop').modal('hide');
$('#profile_form').submit();
});
});
<form action="<?= base_url().'userController/update_staff_picture' ?>" method="post" enctype="multipart/form-data" id="profile_form">
<input type="hidden" name="imageEncoder" id="imageEncoder">
<label class="cabinet center-block">
<figure>
<img src="" class="gambar img-responsive img-thumbnail img-circle" id="item-img-output" />
<figcaption><i class="fa fa-camera"></i></figcaption>
</figure>
<input type="file" class="item-img file center-block" name="file_photo"/>
</label>
</form>
User Controller
public function update_staff_picture(){
$data = $this->input->post('imageEncoder');
echo "<pre>";
print_r($data);
exit();
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name = date('ymdgis').'.png';
$req['image']=$image_name;
file_put_contents('./assets/img/users/'.$image_name, $data);
$this->db->set($req);
$this->db->where('userID',$userID);
$this->db->update('users');
redirect(base_url().'staff-profile/'.$_POST['userID']);
}

Getting "SyntaxError: JSON.parse: unexpected character" When aparently the response is correct

I'm crazy with this error, I'm traying to make an Ajax login form, this is my code:
My HTML:
<div id='login-box' name='login-box' class='radius-all-tiny'>
<div class='bt-wrapper bt-wrapper-hover'>
<span class='bt-icon bt-icon-hover btn-users'></span>
</div>
<div id='login-banner' name='login-banner'>
" . $content['SESSION_BANNER'] . "
</div>
<div class='radius-all-tiny' id='login-error' name='login-error'>
</div>
<form id='login-frm' name='login-frm' method='post' action='./'>
<input type='text' id='usuario' name='usuario' placeholder='" . $content['SESSION_USER'] . "' />
<input type='password' id='contrasena' name='contrasena' placeholder='" . $content['SESSION_PASS'] . "' />
<div class='submit-wrap'><input class='bt-submit radius-all-medium' type='submit' id='enviar' name='enviar' value='" . $content['CONTACT_FRM_SEND'] . "' /></div>
</form>
</div>
My JS:
<script type='text/javascript'>
$(document).ready(function() {
// FORCE BROWSER NOT CACHE AJAX CALLS
$.ajaxSetup({ cache: false });
// HIDE ERROR DIALOG
$('#login-error').hide();
// LOGIN/OUT BUTTON BEHAVIOR
$('#bt-login').click(function(){
$('#login-error').hide();
$.fancybox.open({
href : '#login-box',
padding : 0,
onClosed : function() { }
});
});
// LOADING ANIMATION
var ajaxload = '<img src=\"../img/components/spinner-dark.gif\" alt=\"" . $content['MAIN_LOADING'] . "\" />';
$('#login-frm').bind('submit', function(){
// AUTHENTICATING...
// VALIDAMOS QUE NO HAYAN CAMPOS VACÍOS
if (($('#usuario').val().length < 1) || ($('#contrasena').val().length < 1))
{
$('#login-error').html('EMPTY');
$('#login-error').show();
return false;
}
// SI NO ESTÁN VACÍOS LOS CAMPOS, ENTONCES VALIDAMOS...
$.ajax({
type: 'POST',
cache: false,
url: '../libs/class.log.in.out.php',
data: {usuario: $('#usuario').val(), contrasena: $('#contrasena').val()},
dataType: 'json',
success: function(data)
{
if (data.success)
{
// ESCRIBIMOS LA VARIABLE DE SESIÓN
// CERRAMOS FANCYBOX
$.fancybox.close();
// RECARGAMOS LA PÁGINA PRINCIPAL
document.location.href = $('#urlactual');
}
else
{
// MOSTRAMOS ERROR DE AUTENTICACIÓN
$('#login-error').html('FAILED_AUTH');
$('#login-error').show();
}
}
});
return false;
});
});
</script>
My class.log.in.out.php:
/////////////////////////////////////////////////
// TRANSPORTADOR DE DATOS
/////////////////////////////////////////////////
$data = array(
'success' => false,
'msg' => 'No se encontró ningún dato...'
);
// SOLICITAMOS LOS VALORES DE CONEXIÓN
$usr = (isset($_REQUEST['usuario']) ? $_REQUEST['usuario'] : 'NULL');
$pwd = (isset($_REQUEST['contrasena']) ? $_REQUEST['contrasena'] : 'NULL');
// VALIDAMOS LOS DATOS
class_exists('Database') || require ('class.database.php');
$resp = "";
$thisstt = false;
// INSTANCIAMOS LA CLASE DE BASE DE DATOS
$dbs = new Database();
$datos = $dbs->logIn($usr, $pwd, "", $thisstt);
if ($thisstt)
$resp = $datos['usuario'];
else
$resp = "" . $datos['error'] . " Usuario: " . $usr . "";
// DEVOLVEMOS EL ESTADO DE LA VALIDACIÓN
$data = array(
'success' => $thisstt,
'msg' => utf8_encode($resp)
);
/////////////////////////////////////////////////
// EMPAQUETADO DE DATOS
/////////////////////////////////////////////////
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data);
I receive this response from de class.log.in.out.php (Using Firefox's developer tools):
When the authentication fail:
{"success":false,"msg":"Los datos ingresados son incorrectos... Usuario: 123"}
When the authentication is correct:
{"success":true,"msg":"gchinchilla"}
But Firefox says that the Syntax is incorrect, could you help me?
I apologize for my bad english, I'm learning it...
i do not see any need of converting array to object for json_encode.
i will suggest using :
echo json_encode($data);
instead of :
echo json_encode((object)$data);
SOLVED! There was an "codification error", I have converted the PHP file from UTF-8 to UTF-8 Without BOM.
More info here: http://es.wikipedia.org/wiki/UTF-8#Byte_order_mark_.28BOM.29

Form submission using AJAX and handling response in Wordpress Website

I have a wordpress website. I have made a contact form and it is POSTed by AJAX.
Here's the code:
<script type="text/javascript">
jQuery(document).ready(function(){
$("#error_box").hide();
$('#contact_form').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
var na=$("#1").val();
var email2=$("#2").val();
var subject2 = $("#3").val();
var message2 = $("#4").val();
var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;
alert(mydata);
$("#contact_form").css({"opacity":"0.1"});
$.ajax ({
type: 'POST',
url: $(this).attr.action, // Relative paths work fine
data: mydata,
success: function(){
$("#contact_form").css({"opacity":"1"});
$('#error_box').fadeIn('fast').css({"height": "auto"});
}
});
});
});
</script>
When the form is submitted, I want the error box (#error_box) to display a message according to the data submitted, for example if one of the fields is empty it should display an error, or display a success message if the processing is successful and the form has been mailed. Is there any way I can do this?
[UPDATE]
Here's my contact-form.php file(the action)
<?php if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
{
if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
echo 'EMPTY ERROR';
}
else
{
$name = $_POST['pn2'];
$email = $_POST['email'];
$subj = $_POST['subject'];
$msg = $_POST['msg'];
$to = "ankushverma61#gmail.com";
$mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
echo "success";
mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");
}
}
?>
Form submission using Ajax call
Contact Form
<form action="#" id="contactForm" method="post">
<input class="require" type="text" placeholder="First Name" name="firstName">
<span class="fieldError"></span>
<input class="require" type="text" placeholder="Last Name" name="lastName">
<span class="fieldError"></span>
.
.
.
<input type="submit" value="Submit">
</form>
client side validation with ajax call
jQuery('#contactForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newContactForm = jQuery(this).serialize();
var flag = 0;
jQuery('.require', '#contactForm').each(function(){
var inputVal = jQuery(this).val();
if(jQuery.trim(inputVal) === ""){
flag = 1;
jQuery(this).next().html("Can't be blank");
jQuery(this).next().show();
}
else{
jQuery(this).next().hide();
}
});
if(flag){
return false;
}
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php?action=contactForm",
data: newContactForm,
success:function(data){
jQuery(':input','#contactForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
jQuery("#feedback").html(data);
jQuery("#feedback").fadeOut(10000);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
}
store form data in db and send mail
add the following code in functions.php
wp_enqueue_script('jquery');
add_action('wp_ajax_addContactForm', 'addContactForm');
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');
function addContactForm(){
global $wpdb;
$first_name = $_POST['firstName']; $last_name = $_POST['lastName'];
$email = $_POST['email'];
.
.
.
if($wpdb->insert('table_name',array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
.
.
.
))===FALSE){
echo "Error";
}
else {
$headers = 'From: xyz <xyz#xyz.com>';
$subject = "Thank you";
$body = "<p>Thank you</p><p>.........</p>";
wp_mail( $email, $subject, $body, $headers);
echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";
}
exit;
}
You should use:
$.ajax ({
type: 'POST',
url: $(this).attr.action,
data: mydata,
success: function(response) { // here you receive response from you serverside
$("#contact_form").css({"opacity":"1"});
$('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
}
});
Your server action url: $(this).attr.action, should return message which be inserted in #error_box
First create form like this
<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register">
</fieldset>
</form>
then bind the click and send ajax call
<script type="text/javascript">
jQuery('#test').on('click', function(e) {
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") {
jQuery('#email-error').show();
return false;
} else {
jQuery('#email-error').hide();
}
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test", // redirect function in function.php
firstname: firstname,
email: email
},
success: function(results) {
//console.log(results);
if (results == "1") {
jQuery('.register-message').text("Email already exist");
} else {
jQuery('.register-message').text("Register successfu");
}
},
error: function(results) {}
});
});
</script>
In function.php add the below code to insert data in table
<?php
//
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test()
{
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
$res = $wpdb->get_results($q);
if (count($res) > 0) {
echo "1";
} else {
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix . 'test';
$user_id = $wpdb->insert($tablename, $user_data);
echo "0";
}
die;
}

Resources