Ajax request taking too long time to respond - javascript

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.

Related

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

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

How to make this AJAX (login) request to be secured

I'm making a login system to my website, but the browser says it is not secured: the browser's message
Heres is my html:
<div id="loginform">
Bejelentkezés
<input type="text" placeholder="E-mail" id="email"></input>
<input type="password" placeholder="Jelszó" id="password"></input>
<button id="loginbutton">Bejelentkezés</button>
<div id="errormsg"></div>
</div>
Here is my Ajax:
$("#loginbutton").click(function(){
var user ={
email: $('#email').val(),
password: $('#password').val()
};
$.ajax({
url: 'login.php',
type: 'POST',
dataType: "json",
data: {"user": JSON.stringify(user)},
success: function(data){
if(data.success){
alert(data.user_id);
}
else{
document.getElementById("errormsg").innerHTML = "A bejelentkezés sikertelen";
}
}
});
});
And my PHP:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
$results = array(
'success' => false,
'user_id' => "azaz",
'fname' => "",
'lname' => ""
);
if(isset($_POST['user'])){
$user = json_decode($_POST['user']);
$email = $user->email;
$password = md5($user->password);
$sql= "SELECT * FROM users WHERE email = '".$email."' AND password = '".$password."'";
$rowsql = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rowsql, MYSQLI_BOTH);
if(mysqli_num_rows($rowsql) == "1"){
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['fname'] = $row['fname'];
$_SESSION['lname'] = $row['lname'];
$results['success'] = true;
$results['user_id'] = $row['user_id'];
$results['fname'] = $row['fname'];
$results['lname'] = $row['lname'];
}
}
else{
$results['user_id']= "VAnbaj";
}
echo json_encode($results);
?>
It works, but i don't know how to make it safe.
I'd be glad if somebody can help me.
I you want to get rid of that warning message, you have to serve your site over https with a valid certificate.

ajax request after jquery validation

I try to make an ajax request after a successful form validation. If I delete the , after url: 'loginprivate.php' the php code works but the validation dont. If I add the , the validation works but the php code not. The redirection after successful ajax request dont work anyway. How can I make that working, maybe with $(form).ajaxSubmit(); when yes where should I add this line?
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
username: {
required: true,
minlength: 2,
maxlength: 30
},
password: {
required: true,
minlength: 3,
maxlength: 30
}
},
submitHandler: function (form) { // for demo
$.ajax({
type: 'post',
url: 'loginprivate.php', //url where you want to post the stuff.
data:{
username: 'root',
password: ''
},
success: function(res){
//here you will get res as response from php page, either logged in or some error.
window.location.href = "http://localhost/localcorps/main.php";
}
});
return false; // for demo
}
});
});
my php code:
if(isset($_POST["submit"]))
{
$hostname='localhost';
$username='root';
$password='';
unset($_POST['password']);
$salt = '';
for ($i = 0; $i < 22; $i++) {
$salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1);
}
$_POST['password'] = crypt($_POST['password'],'$2a$10$'.$salt);
$new = 0;
try {
$dbh = new PDO("mysql:host=$hostname;dbname=search",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (username, password)
VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
if ($dbh->query($sql)) {
echo "New Record Inserted Successfully";
}
else{
echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0)
{
$t = time() + 60 * 60 * 24 * 1000;
setcookie("username", $_POST['username'], $t);
setcookie("userid", $new , $t);
}
else
{
}
}
Im your ajax add this
data:{
username: 'root',
password: '',
submit: true,// add this line as you are checking in php file.
},

AJAX - JSON Error

When I am trying to receive data from the server side, error I am getting:
06-30 11:23:57.119: I/chromium(7486): [INFO:CONSOLE(50)] "{"readyState":4,"responseText":"","status":404,"statusText":"Not Found"}", source: file:///android_asset/www/js/index.js (50)
JS file:
$j.ajax({
type: 'POST',
url: 'http://www.myrandomurl.com/SupportData/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
//alert(JSON.stringify(response));
//console.log(JSON.stringify(response));
if (response.success) {
myApp.alert("you're logged in");
//window.localStorage["email"] = e;
//window.localStorage["password"] = p;
console.log(window.localStorage["email"]);
//localStorage.removeItem('email');
mainView.router.loadPage('main.html');
} else {
myApp.alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
//myApp.alert('Could not connect to the database' + error);
console.log(JSON.stringify(error));
//window.location = "index.html";
}
});
PHP side:
$sql = "SELECT login_id, email_id, password FROM login WHERE email_id='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$row = mysql_fetch_array($result);
if($num_rows == 1) {
$response['success'] = true;
}else {
$response['success'] = false;
}
echo json_encode($response);

Categories

Resources