Return success with parameter in php/jquery - javascript

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 -->

Related

Ajax undefined value in PHP

When I call the function I always get an undefined value, I don't understand what can ruin it.
You are logged in as undefined, Error undefined
Ajax script:
function Submit() {
console.log('asd')
$.ajax({
url: "Server.php",
type: "POST",
dataType: "json",
data: {
name: "Test2",
email: "Test#gmail.com"
},
success: function(data, textStatus, jqXHR) {
console.log("You are logged in as: ", data.name);
$('#user').html("You are logged in as: " + data.name);
},
error: function(request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error + " DATA: " + data);
}
})
}
PHP Script:
<?php
header("Content-type: application/json; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
I tried every solution in vain, so I still get an indefinite value. I’m slowly starting to think there’s nothing wrong with the script.
You want to use data.name but you never return name. hence the undefined.
I've added data.name in the example below and it seems to work fine.
<?php
header("Content-type: text/html; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
Also the parameters used in the succes function are in a different order than you seem to use, in your case the request will have your data in it
the callback parameter not
success:function(request, data, error)
but
success: function(data, textStatus, jqXHR)
data.name of course undefined because it is string
and your Server.php return this
{"success":true,"message":"Success!"}
no data.name but data.success and data.message
so you have to write
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name']; // add this
}

Open popup after form submit in php/jquery

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 -->

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.

Categories

Resources