Call only one function at a time - javascript

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)

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 );
}

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 200 Success/failed execution

I have an issue with ajax and I am kinda new at this. The issue that I am having is even if log in fails ajax is still running the success block of code. How do I direct the code to return a failed status.
I'm not asking for you to inspect my code just more as a reference. I just need to know how to tell my code to send anything other than a 200 for okay so that I can display the errors on the screen.
I type in false information and the ajax thinks that the login happened but it really didn't.
AJAX Section
jQuery(document).ready(function(){
document.body.style.paddingTop="3px";
$('a[href^="#fallr-"]').click(function(){
var id = $(this).attr('href').substring(7);
methods[id].apply(this,[this]);
return false;
});
var methods = {
login : function(){
var login = function(){
var username = $(this).children('form').children('input[type="text"]').val();
var password = $(this).children('form').children('input[type="password"]').val();
var remember = $(this).children('form').children('input[name="remember"]').val();
var token = $(this).children('form').children('input[name="token"]').val();
if(username.length < 1 || password.length < 1 || token.length < 1){
alert('Invalid!\nPlease fill all required forms');
console.log(token)
} else {
var data = {
username: username,
password: password,
remember: remember,
token: token,
}
$.ajax({
type: "POST",
url: "login.php",
data: data,
dataType: "text",
success: function(data){
$('#error').append('Success');
// $.fallr.hide();
// window.location.href = "http://www.bettergamerzunited.com/members/";
},
error: function(data) {
$('#error').append('falied');
}
});
}
}
$.fallr.show({
icon : 'secure',
width : '400px',
content : '<h4 class="titles">Login</h4>'
+ '<span id="error"></span>'
+ '<form>'
+ '<input placeholder="Username" name="username" type="text"/'+'>'
+ '<input placeholder="Password" name="password" type="password"/'+'>'
+ '<input type="checkbox" name="remember" type="remember"/'+'> Remember Me'
+ '<?php echo $hidden; ?>'
+ '</form>',
buttons : {
button1 : {text: 'Submit', onclick: login},
button4 : {text: 'Cancel'}
}
});
}
};
});
Login Section
require 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = New Validate ();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if ($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
$response = $login;
echo $response; // <-- Im going to have an if statement that determines if $login was true or false. But testing still.
} else {
foreach ($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
This is the class that handles the login.
public function login($username = null, $password = null, $remember = false) {
if(!$username && !$password && $this->exists()) {
Session::put($this->_sessionName, $this->data()->id);
} else {
$user = $this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)) {
Session::put($this->_sessionName, $this->data()->id);
if($remember) {
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
if(!$hashCheck->count()) {
$this->_db->insert('users_session', array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
} else {
try{
throw new Exception('The Username or Password combination doesn\'t match. \n Please try again.');
} catch(Exception $e) {
echo $e->getMessage();
}
}
} else {
try{
throw new Exception('The Username you provide does not match anything in our system. Please Try again or Register.');
} catch(Exception $e) {
echo $e->getMessage();
}
}
}
return false;
}
You can add below code for ajax error section ..in this way you will get idea of what's exactly is error and can debug it.
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
}
Use the PHP header function.
header('HTTP/1.0 403 Forbidden'); // or whatever status code you want to return.
There can be nothing else outputted before using the header function.

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources