Open popup after form submit in php/jquery - javascript

I need to configure send.php file so that it triggers a hidden popup(look at the HIDDEN section, #modal_success) after form submit. At this point, it only sends data from forms on my email, but the popup with the "success" message won't show. Please help. Thank you
This is the send.php file
<?php
$to = "mail#mail.com";
$tema = "New request";
$message = "Name: ".$_POST['name']."<br>";
$message .= "E-mail: ".$_POST['email']."<br>";
$message .= "Phone: ".$_POST['phone']."<br>";
$message .= "Form: ".$_POST['form']."<br>";
$message .= "Where: ".$_POST['where']."<br>";
$message .= "Square: ".$_POST['square']."<br>";
$message .= "Price: ".$_POST['price']."<br>";
$message .= "When: ".$_POST['when']."<br>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
isset($_POST['agree']);
if(mail($to, $tema, $message, $headers)) {
echo 'success';
}
else {
echo 'error';
};
?>
This is JavaScript file
// MODAL
$('.modalshow').on('click', function(e){
e.preventDefault();
var
$href = $(this).attr('href'),
$form = $(this).attr('data-form');
if($form) {
$($href).find('input[name="form"]').val($form);
}
$.fancybox.open({
src : $href,
type : 'inline',
afterLoad : function() {
window.quizSlider.update();
}
});
})
$(document).on('click', '.fmodal', function(e){
e.preventDefault();
var $href = $(this).attr('href');
$.fancybox.open( $($href+' a'), {});
})
// # MODAL
// FORM SUBMIT
$('.form').on('submit', function () {
var
$form = $(this),
$name = $form.find('input[name="name"]'),
$phone = $form.find('input[name="phone"]'),
$email = $form.find('input[name="email"]'),
$agree = $form.find('input[name="agree"]:checked'),
$rv_email = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/,
$error = false;
if ($form.hasClass('form__file')) {
var $data = new FormData();
if ($name.length) {
$data.append('name', $name.val());
}
if ($phone.length) {
$data.append('phone', $phone.val());
}
if ($email.length) {
$data.append('email', $email.val());
}
} else {
var $data = $form.serialize();
}
if ($form.find('input[name="agree"]').length && !$agree.length) {
$form.find('.agree__cont').addClass('invalid');
$error = true;
} else {
$form.find('.agree__cont').removeClass('invalid');
}
if ($name.length) {
if ($name.val().length < 3) {
$name.addClass('invalid');
$error = true;
} else {
$name.removeClass('invalid');
}
}
if ($phone.length) {
if ($phone.val().length < 1) {
$phone.addClass('invalid');
$error = true;
} else {
$phone.removeClass('invalid');
}
}
if ($email.length) {
if ($email.val().length < 1 || !$rv_email.test($email.val())) {
$email.addClass('invalid');
$error = true;
} else {
$email.removeClass('invalid');
}
}
if ($error) {
return false;
} else {
if ($form.hasClass('form__file')) {
if ($form.find('input[name="file"]').length) {
$data.append("file", $form.find('input[name="file"]')[0].files[0]);
}
$.ajax({
type: "POST",
url: "./send.php",
dataType: "json",
data: $data,
processData: false,
contentType: false,
beforeSend: function ($json) {
},
success: function ($json) {
if ($json['success']) {
$instance = $.fancybox.getInstance();
if ($instance) { $instance.close(); }
$.fancybox.open({
src: $('#modal_success'),
type: 'inline'
});
}
},
error: function (json) {
console.log(json);
}
});
} else {
$.ajax({
type: "POST",
url: "./send.php",
dataType: "json",
data: $data,
beforeSend: function ($json) {
},
success: function ($json) {
if ($json['success']) {
$instance = $.fancybox.getInstance();
if ($instance) { $instance.close(); }
$.fancybox.open({
src: $('#modal_success'),
type: 'inline'
});
}
},
error: function (json) {
console.log(json);
}
});
}
}
return false;
})
// # FORM SUBMIT
This is HTML part on my page
<!-- HIDDEN -->
<div id="modal_success" class="modal__item success__modal">
<div class="modal__title">Thank you! Your request has been sent!</div>
<div class="success__text">we will contact you shortly</div>
</div>
<!-- # HIDDEN -->

Related

Return success with parameter in php/jquery

I need to adjust send.php file so that it returns success with parameter and check $json['success'] == 'success'. Then show popup with a "success" message (look at the HIDDEN section, #modal_success) after form submit.
At this point, the data from all contact forms is sent to my email, but the popup with the "success" message won't show up. Could you please help me. Thank you
This is JavaScript file
// MODAL
$('.modalshow').on('click', function(e){
e.preventDefault();
var
$href = $(this).attr('href'),
$form = $(this).attr('data-form');
if($form) {
$($href).find('input[name="form"]').val($form);
}
$.fancybox.open({
src : $href,
type : 'inline',
afterLoad : function() {
window.quizSlider.update();
}
});
})
$(document).on('click', '.fmodal', function(e){
e.preventDefault();
var $href = $(this).attr('href');
$.fancybox.open( $($href+' a'), {});
})
// # MODAL
// FORM SUBMIT
$('.form').on('submit', function () {
var
$form = $(this),
$name = $form.find('input[name="name"]'),
$phone = $form.find('input[name="phone"]'),
$email = $form.find('input[name="email"]'),
$agree = $form.find('input[name="agree"]:checked'),
$rv_email = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/,
$error = false;
if ($form.hasClass('form__file')) {
var $data = new FormData();
if ($name.length) {
$data.append('name', $name.val());
}
if ($phone.length) {
$data.append('phone', $phone.val());
}
if ($email.length) {
$data.append('email', $email.val());
}
} else {
var $data = $form.serialize();
}
if ($form.find('input[name="agree"]').length && !$agree.length) {
$form.find('.agree__cont').addClass('invalid');
$error = true;
} else {
$form.find('.agree__cont').removeClass('invalid');
}
if ($name.length) {
if ($name.val().length < 3) {
$name.addClass('invalid');
$error = true;
} else {
$name.removeClass('invalid');
}
}
if ($phone.length) {
if ($phone.val().length < 1) {
$phone.addClass('invalid');
$error = true;
} else {
$phone.removeClass('invalid');
}
}
if ($email.length) {
if ($email.val().length < 1 || !$rv_email.test($email.val())) {
$email.addClass('invalid');
$error = true;
} else {
$email.removeClass('invalid');
}
}
if ($error) {
return false;
} else {
if ($form.hasClass('form__file')) {
if ($form.find('input[name="file"]').length) {
$data.append("file", $form.find('input[name="file"]')[0].files[0]);
}
$.ajax({
type: "POST",
url: "./send.php",
dataType: "json",
data: $data,
processData: false,
contentType: false,
beforeSend: function ($json) {
},
success: function ($json) {
if ($json['success']) {
$instance = $.fancybox.getInstance();
if ($instance) { $instance.close(); }
$.fancybox.open({
src: $('#modal_success'),
type: 'inline'
});
}
},
error: function (json) {
console.log(json);
}
});
} else {
$.ajax({
type: "POST",
url: "./send.php",
dataType: "json",
data: $data,
beforeSend: function ($json) {
},
success: function ($json) {
if ($json['success']) {
$instance = $.fancybox.getInstance();
if ($instance) { $instance.close(); }
$.fancybox.open({
src: $('#modal_success'),
type: 'inline'
});
}
},
error: function (json) {
console.log(json);
}
});
}
}
return false;
})
// # FORM SUBMIT
This is the send.php file
<?php
$subject = "New request";
$message = "Name: ".$_POST['name']."<br>";
$message .= "E-mail: ".$_POST['email']."<br>";
$message .= "Phone: ".$_POST['phone']."<br>";
$message .= "Form: ".$_POST['form']."<br>";
$message .= "Where: ".$_POST['where']."<br>";
$message .= "Square: ".$_POST['square']."<br>";
$message .= "Price: ".$_POST['price']."<br>";
$message .= "When: ".$_POST['when']."<br>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$success = mail("email#email.com", $subject, $message, $headers);
echo $success;
?>
This is HTML part on the same page where contact forms are
<!-- HIDDEN -->
<div id="modal_success" class="modal__item success__modal">
<div class="modal__title">Thank you! Your request has been sent!</div>
<div class="success__text">we will contact you shortly</div>
</div>
<!-- # HIDDEN -->

Ajax response isn't showed on page

My ajax is
$.ajax({
type: 'POST',
url: ajax.ajax,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(msg){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
This is the PHP part
function form(){
global $wpdb;
$table = cars;
foreach ($_FILES as $file) {
if($file['error'] == UPLOAD_ERR_NO_FILE) {
continue;
}
$valid_ext = array( 'img' , 'png');
$extension_upload = strtolower( substr( strrchr($file['name'], '.') ,1) );
if ( in_array($extension_upload,$valid_ext) ) {
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$data = array( 'customer_resume' => $name_upload );
$format = array( '%s' );
$success=$wpdb->insert( $table, $data, $format );
$msg_true = 'Upload ok ';
} else {
$msg_error = 'Upload error';
}
}
$result = !isset($msg_error);
$msg = array();
if($result) {
$msg['error'] = 'true';
$msg['true'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['false'] = $msg_error;
}
header('Content-Type: application/json');
echo json_encode($msg);
}
And the HTML where I try to show the success or error message
<div id="error_message"></div>
<div id="success_message"></div>
When I click on Submit button I everything works fine and saved in database but there is no indication wheather is success or no. I've tried to add this msg's but still nothing shows on page.
PHP side:
You need to print same variable for success and failure:
if($result) {
$msg['error'] = 'true';
$msg['msg'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['msg'] = $msg_error;
}
JavaScript Side:
The AJAX response will come as
data.error -> true or false.
data.msg -> Success or Error message depending upon program logic.
...
success: function(data){
$('#success_message').fadeIn().html(data.msg);
...
What is hiding behind "ajax.ajax" ?
Also if you want to show your data you need to use "msg"
success: function(msg){
$('#success_message').fadeIn().html(msg);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}

Call only one function at a time

I am creating a login and register example function using php OOP method with ajax.
When i click on login button it automatically fires the register function as well and when click on register fires login function. I know the issue is when i create an object and calls both the functions below class. I want to know is there any way that i can call only one function at one time. Here is the code:
Ajax
function login() {
jQuery('#loginform').on('submit', (function(e) {
e.preventDefault();
jQuery.ajax({
url: 'scripts/controller.php/login',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
cache: false,
beforeSend: function() {
jQuery('#btn-login').html('<i class="fa fa-spinner fa-spin fa-fw"></i>');
},
success: function(data) {
if(data == 'Logged in') {
jQuery('.result').show();
jQuery('.result').html(data);
jQuery('#btn-login').html('Login');
}
else {
jQuery('.result').html(data);
jQuery('.result').show();
jQuery('#btn-login').html('Login');
}
}
});
}));
}
function register() {
jQuery('#signupform').on('submit', (function(e) {
e.preventDefault();
jQuery.ajax({
url: 'scripts/controller.php/register',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
cache: false,
beforeSend: function() {
jQuery('#btn-signup').html('<i class="fa fa-spinner fa-spin fa-fw"></i>');
},
success: function(data) {
if(data === 'An email has been sent. Please verify your account with in 3 days.') {
jQuery('.result').show();
jQuery('.result').fadeOut(5000);
jQuery('.result').html(data);
jQuery('#btn-signup').html('Sign Up');
jQuery('.result').html(data);
jQuery('#signupform')[0].reset();
}
else {
jQuery('.result').show();
jQuery('.result').html(data);
jQuery('#btn-signup').html('Sign Up');
}
}
});
}));
}
PHP Code
<?php
require('model.php');
class curd {
/************************************************/
/*** LOGIN **/
/************************************************/
public function login() {
$restricted = array('--', '#', "'--", '/*', '*/', '/**/', '/*', '1/0', '*/ 1', "'", ';', '1=1','true','false', 'BEGIN', '+', '||', '|', "' or 1=1/*", "') or '1'='1--", "') or ('1'='1--", '*', 'drop' );
$userEmail = strip_tags(stripcslashes(htmlspecialchars($_POST['email'])));
$password = strip_tags(stripcslashes(htmlspecialchars($_POST['password'])));
if(in_array($userEmail, $restricted) or in_array($password, $restricted)) {
echo 'Avoid SQL injection attacks.';
}
else if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email address.';
}
else if(strlen(trim($userEmail)) < 5) {
echo 'Minimum characters in email are 5.';
}
else if(strlen(trim($password)) < 5) {
echo 'Minimum characters in password are 5.';
}
else {
$model = new curd_model();
echo $model -> login($userEmail, md5(sha1($password)));
}
}
/************************************************/
/*** REGISTER **/
/************************************************/
public function register() {
$restricted = array('--', '#', "'--", '/*', '*/', '/**/', '/*', '1/0', '*/ 1', "'", ';', '1=1','true','false', 'BEGIN', '+', '||', '|', "' or 1=1/*", "') or '1'='1--", "') or ('1'='1--", '*', 'drop' );
$username = strip_tags(stripcslashes(htmlspecialchars($_POST['username'])));
$userEmail = strip_tags(stripcslashes(htmlspecialchars($_POST['email'])));
$password = strip_tags(stripcslashes(htmlspecialchars($_POST['password'])));
$question = strip_tags(stripcslashes(htmlspecialchars($_POST['question'])));
$answer = strip_tags(stripcslashes(htmlspecialchars($_POST['answer'])));
if(in_array($userEmail, $restricted) or in_array($password, $restricted) or in_array($userEmail, $restricted) or in_array($question, $restricted) or in_array($answer, $restricted)) {
echo 'Avoid SQL injection attacks.';
}
else if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email address.';
}
else if(strlen(trim($userEmail)) < 5) {
echo 'Minimum characters in email are 5.';
}
else if(strlen(trim($password)) < 5) {
echo 'Minimum characters in password are 5.';
}
else {
$model = new curd_model();
echo $model -> register($username, $userEmail, md5(sha1($password)), $question, $answer);
}
}
}
$object = new curd();
$object -> login();
$object -> register();
?>
Anytime you'll load the file the following lines would run:
$object = new curd();
$object -> login();
$object -> register();
And therefore, both of the login and register functions would run.
You have 2 options:
Split those functions into 2 different files.
In your Ajax, add a parameter which would tell this file which function to run.
In MVC you might have a Routing mechanism (for instance: /user/login -> Controller User -> Method login)
In case you don't, you can simply use a query string, like: /scripts/controller.php?do=login and in your php file have a condition:
$object = new curd();
$do = $_GET['do'];
if($do == 'login'){
$object -> login();
} else {
$object -> register();
}
and in your ajax, update the request url:
jQuery.ajax({
url: 'scripts/controller.php?do=register',
(for login request as well .. ?do=login)

Ajax request taking too long time to respond

Javascript
<script>
loginValidator = $('#login').validate({
errorClass: 'error1',
focusInvalid: false,
errorElement: "div",
rules: {
username: {
required: true,
email: true
},
password: "required"
},
messages: {
username: {
email: "Please Enter a Valid E-mail Id"
},
password: {
required: "Please Enter Your Password"
}
},
submitHandler: function (form) {
var email = $('#username').val();
var password = $('#password').val();
var url = "<pre> ?php echo site_url() ?></pre> /register/do_login";
$.ajax({
type: 'post',
url: url,
data: {'username': email, 'password': password},
dataType: 'html',
success: function (data) {
if (data == 0) {
$('.invalidlogin').html('Invalid Username or Password').css('color', 'red');
}
if (data == 1)
{
window.location.href = "<?php echo site_url(); ?>/home/landing_home";
return false;
}
if (data == 2)
{
window.location.href = "<?php echo site_url(); ?>/home/first_login_disclaimer";
}
}
});
}
});
</script>
Register.php-Controller
<?php
function do_login() {
echo $result = $this->obj_users->check_login();
exit;
}
?>
Registration.php-Model
<?php
function check_login() {
$username = $this->input->post('username');
$password = $this->input->post('password');
$last_logged = date('Y-m-d H:i:s');
$salt = sha1($password);
$password = md5($salt . $password);
$this->db->where(array('email' => $username, 'password' => $password, 'status' => '1'));
$query = $this->db->get('registration');
$result = $query->result();
if (count($result) > 0) {
$first_login_status = $result[0]->first_login;
if ($first_login_status == '1') {
$datas = array('last_logged' => $last_logged);
$this->db->where(array('email' => $username));
$this->db->update('registration', $datas);
$this->session->set_userdata('user_id', $result[0]->id);
$this->session->set_userdata('user_type', $result[0]->user_type);
$this->session->set_userdata('ADMIN_NAME', $result[0]->name);
return "1";
} else {
$this->db->where(array('email' => $username, 'password' => $password, 'first_login' => '0', 'status' => '1'));
$query = $this->db->get('registration');
$result = $query->result();
$this->session->set_userdata('first_login_user_id', $result[0]->id);
$this->session->set_userdata('first_login_user_type', $result[0]->user_type);
$this->session->set_userdata('FIRST_LOGIN_ADMIN_NAME', $result[0]->name);
if (count($result) > 0) {
return "2";
}
}
} else {
return "0";
}
}
?>
Here, the ajax request is taking more than 5 seconds to respond to the request and redirect to next page.. Please suggest me if there is any way to reduce Ajax response time. Thank you.

jQuery ajax call not triggering success function on Safari 9.1

In a project I have a particular ajax call that works fine on PC Chrome/Firefox, but on Safari 9.1 it fails to trigger the success function.
The ajax call:
$('#new_file_form').submit(function(e) {
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
url: '/includes/ajax/file-manager.php',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
success: function(result) {
JSON.parse(result);
alert(result);
if (result == true) {
$('#new_file_form').reset;
$('#new_file_modal').modal('hide');
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-info-sign blue"></i>File successfully saved.',
callback: function() {
location.reload();
}
});
} else if (result == false) {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>File not saved.',
callback: function() {
location.reload();
}
});
} else {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>Whoa! That escalated quickly..',
callback: function() {
location.reload();
}
});
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
This doesn't throw any errors. The file is uploaded and the data inserted into the database, it's just the success function that sits there and seems to be laughing at me.
Based on the returned error in Safari it seems useful to post the file-manager.php code:
if(!empty($_POST['file_name']) && !empty($_POST['file_type']) && !empty($_POST['file_user'])) { // && !empty($_FILES['file'])
$ownerid = $mysqli->real_escape_string($_POST['file_user']);
$ownertype = 1;
$name = $mysqli->real_escape_string($_POST['file_name']);
$visible = $mysqli->real_escape_string($_POST['visible']);
$filetype = $mysqli->real_escape_string($_POST['file_type']);
$ownerid = filter_var($ownerid, FILTER_SANITIZE_NUMBER_INT);
$visible = filter_var($visible, FILTER_SANITIZE_NUMBER_INT);
$filetype = filter_var($filetype, FILTER_SANITIZE_NUMBER_INT);
$cdate = date('Y-m-d H:i:s');
$edate = $cdate;
$u_file_name = $_FILES['file']['name'];
$u_tmp_file = $_FILES['file']['tmp_name'];
$u_file_type = $_FILES['file']['type'];
$u_file_error = $_FILES['file']['error'];
$u_file_content = file_get_contents($_FILES['file']['tmp_name']);
$upload_result = '';
if($u_file_error == 'UPLOAD_ERROR_OK') {
if($u_file_name == '') {
$upload_result = false;
} else {
$sql = "SELECT path FROM filetypes WHERE id = '$filetype'";
$result = $mysqli->query($sql);
$record = $result->fetch_object();
$file_type_path = $record->path;
$extension = end(explode(".", $u_file_name));
if($ownertype == 1) {
$s_file_name = preg_replace("![^a-z0-9]+!i", "-", $name).'-'.date('Y-m-d_H-i').'.'.$extension;
$s_file_dest = LOCAL_BASE_PATH.'/uploads/'.$ownerid.'/'.$file_type_path;
$s_file_location = $s_file_dest.'/'.$s_file_name;
$s_file_path = '/uploads/'.$ownerid.'/'.$file_type_path.$s_file_name;
}
if(!file_exists($s_file_dest)) {
mkdir($s_file_dest, 0755, true);
}
move_uploaded_file($u_tmp_file, $s_file_location);
$sql = "INSERT INTO files (ownertype, owner, type, visible, extension, name, path, cdate, edate) VALUES ('$ownertype', '$ownerid', '$filetype', '$visible', '$extension', '$s_file_name', '$s_file_path', '$cdate', '$edate')";
$result = $mysqli->query($sql);
$upload_result = true;
}
}
echo json_encode($upload_result);
exit();
}
When I alert the ajax result before parsing it, I get a PHP error:
Strict Standards: Only variables should be passed by reference...

Categories

Resources