Ajax call for the Bootstrap Modal not working - javascript

I'm trying to make a simple Ajax call for a Bootstrap login modal. The main HTML code of the login Modal looks like this:
<form method="post" id="loginForm">
<div id="loginMessage"></div>
<div class="modal-footer">
<button type="button" class="btn btn-success mr-auto" data-target="#signupModal" data-toggle="modal" data-dismiss="modal">Register</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<input class="btn" name="login" type="submit" id="inputButton" value="Login">
</div>
</form>
In case the whole HTML code for the modal would help : https://jsfiddle.net/aslah/hykxLqd5/2/
The jQuery code looks like this:
$('#loginForm').submit(function(event){
//prevent default php processing
event.preventDefault();
//collect user inputs:
var datatopost = $(this).serializeArray();
//send the user data to login.php using AJAX
$.ajax({
url: "login.php",
type : "POST",
data : datatopost,
success : function(data){
if(data == 'success'){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
},
error : function(){
$('#loginMessage').html('<div class="alert alert-danger">There was an error with the AJAX call. Please, try again later!</div>');
}
});
});
This is my login.php code :
<?php
//starting the session
session_start();
//connecting to database
include('connection.php');
//check user inputs
// DEFINE ERROR MESSAGES //
$missingEmail = '<p><strong>Please enter your email address!</strong></p>';
$missingPassword = '<p><strong>Please enter a password!</strong></p>';
// $email = $_POST["loginEmail"]
// $password = $_POST["loginPassword"]
if(empty($_POST["loginEmail"])){
$error .= $missingEmail;
}else{
$email = filter_var($_POST["loginEmail"], FILTER_SANITIZE_EMAIL);
}
if(empty($_POST["loginPassword"])){
$error .= $missingPassword;
}else{
$password = filter_var($_POST["loginPassword"], FILTER_SANITIZE_STRING);
}
//If there are any ERRORS
if($error){
$resultMessage = '<div class="alert alert-danger">'. $error .'</div>' ;
echo $resultMessage ;
}else{
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
// $password = md5($password); no secure
$password = hash('sha256', $password);
//check if the user is registered by matching EMAIL & PASSWORD
$sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password' AND activation='activated' ";
$result = mysqli_query($link, $sql);
//if any errors while running the query
if(!$result){
echo '<div class="alert alert-danger"> Error running the query!</div>';
exit;
}
//if login failed print ERROR
$count = mysqli_num_rows($result);
if($count !== 1){
echo '<div class="alert alert-danger">Wrong username or password</div>';
}else{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
//if remember me is not checked
if(empty($_POST['rememberme'])){
echo "success";
}else{
// if rememberme is checked
}
}
}
?>
On submit of the the Login button I want to redirect the user to the mainpage.php. I tried all the different fixes I found here but nothing worked. I can't figure out what I'm doing wrong. Any help is highly appreciated.
This is what I get when I submit the form

Aslah P Hussain
I have tested your code. The first thing that caught my attention is Notice about the undefined variable $error. Possibly you have defined it in include('connection.php'); but if not, this can cause problems with PHP output that you are expecting.
Additionally, if you are 100% sure that the console returns the message success - you can change your check in JavaScript to:
if(data.indexOf('success') >= 0){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
Possibly not the best solution to the problem, but at least will show you that redirect is working

Related

how to display an alert after redirect to another page

login form (index.php) was already created. when form is submitted username and password are passed in to another page (login-controller.php). after verifying, if username or password is incorrect user was redirected to login form(index.php) after display the alert box in login-controller.php.but i want to display an alert box like "invalid login credentials" after redirect to login form(index.php). how can i solve this. code of login-controller.php are given bellow.
<?php
session_start();
if (isset($_SESSION['username'])) {
header('Location: ../service/index.php');
}
include '../include/conn.php'; //database connection
if (isset($_POST["submit"])) {
if (empty($_POST["username"] && $_POST["password"])) {
header('Location: index.php');
} else {
$username = mysqli_real_escape_string($conn, $_POST["username"]);
$password = mysqli_real_escape_string($conn, $_POST["password"]);
$password = md5($password);
$sqli = "SELECT * FROM user WHERE name = '$username' AND password = '$password'";
$result = $conn->query($sqli);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['username'] = $username;
header('Location: ../service/index.php');
} else {
include '../include/bootstrap.php'; //bootstrap js and css
echo '<div class="alert alert-danger"><strong>Oops!</strong> Invalid Login Credentials.</div>';
echo "<script>setTimeout(\"location.href = 'index.php';\",3000);</script>";
}
}
}
?>
Using session variables you can display alerts:
$_SESSION['alerts'][] = "Test Alert";
$_SESSION['alerts'][] = "Another Test Alert";
Then in your config, or any other .php file that gets executed on every page that you have ( If you have a templating system, do that in the template) do this:
if(isset($_SESSION['alerts'])){
foreach($_SESSION['alerts'] as $alertmessage){
echo '<div class="alert">' . $alertmessage . '</div>';
}
}

if(isset($_POST['btn-save'])) doesn't return true

Yep, this old chesnut I'm afraid. I've read through a lot of the previous answers to this question but I cannot get into this if statement even though 'btn-save' is definitely set as the name attribute on my submit button.
I'm using the code from this tutorial to post form data to my database: http://www.phpzag.com/ajax-registration-script-with-php-mysql-and-jquery/
My site structure is like this:
- root
- public_html
- js
app.js
register.php
db_connect.php
form_page.php
My register.php file looks like this and I've added an echo inside the if statement:
<?php
include_once("db_connect.php");
if(isset($_POST['btn-save'])) {
echo "in if";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_id = $_POST['email_id'];
$address_1 = $_POST['address_1'];
$address_2 = $_POST['address_2'];
$address_3 = $_POST['address_3'];
$city_town = $_POST['city_town'];
$county = $_POST['county'];
$post_code = $_POST['post_code'];
$entrant_type = $_POST['entrant_type'];
$chosen_store = $_POST['chosen_store'];
$chosen_charity = $_POST['chosen_charity'];
$agree_terms = $_POST['agree_terms'];
$sql = "SELECT user_email FROM tbl_big_challenge_registrations WHERE user_email='$email_id'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if(!$row['user_email']){
$sql = "INSERT INTO tbl_big_challenge_registrations('uid', 'first_name', 'last_name', 'user_email', 'address_1', 'address_2', 'address_3', 'town_city', 'county', 'postcode', 'entrant_type', 'crew_store', 'charity', 'agree_terms') VALUES (NULL, '$first_name', '$last_name', '$email_id', '$address_1', '$address_2', '$address_3', '$city_town', '$county', '$post_code', '$entrant_type', '$chosen_store', '$chosen_charity', 'agree_terms', NULL)";
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)."qqq".$sql);
echo "registered";
} else {
echo "1";
}
}
?>
My db_connect.php file looks like this (with dummy values for purpose of this post):
<?php
/* Database connection start */
$servername = "servername.com";
$username = "username";
$password = "password";
$dbname = "my_database";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
My form_page.php form looks like this:
<form id="2017-challenge-form" method="post" data-abide>
<!-- form fields are here -->
<input id="btn-submit" type="submit" name="btn-save" value="submit">
</form>
And finally my app.js looks like this:
$('document').ready(function() {
/* handle form submit */
function submitForm() {
var data = $("#2017-challenge-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").val('Submitting...');
},
success : function(response) {
if(response==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").val('Submit');
});
} else if(response=="registered"){
$("#btn-submit").html('<img src="ajax-loader.gif" /> Signing Up ...');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".register_container").load("welcome.php"); }); ',3000);
} else {
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").val('Submit');
});
}
}
});
return false;
}
$("#2017-challenge-form").submit(function(event){
// cancels the form submission
event.preventDefault();
// jumps into ajax submit function
submitForm();
});
});
I have a breakpoint set just inside the ajax success and on submission of the form I would expect the response to have a value of 'registered' (just like the Demo from the PHPZag site: http://phpzag.com/demo/ajax-registration-script-with-php-mysql-and-jquery/
But I get an empty string:
Can anybody see what I'm doing wrong or am missing?
I changed the input to a button as per the demo site and this worked. As per the comment by #frz3993 the btn-save wasn't getting added to the data so the if(isset($_POST['btn-save'])) was never true as it wasn't finding it.

Many spaces before javascript result

I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.

php login form pass vars

i have a page login
in page have html form with textboxes and submit button
and in top of page i have PHP code thet chacke if name and password in database
if name and password in database page go to new page and pass the name and password to next page
i can do it with get metod like the vars in the URL
but i want to pass and go to new page with Post metod
how i can do it??
pleas help me with code....
in code html :
form name="frmlogin"action="<?= $_SERVER['PHP_SELF'] ?>" method="post" >
and in top of the page have PHP code:
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
/*header('Location: YOUR_LOCATION');
exit;*/
$msg = "Username and password match";
echo '<script type="text/javascript">
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
help me to change the javascript window.location to post metod
You can go for php redirect also.
header('location:smartphon100.php?name='. $name .'&password='. $password) ;
BTW: you are passing password in browser?
If I understand correctly, you're trying to redirect a user after successfully logging in.
I see that your current code attempts to redirect using Javascript, the issue seems to be with the quotes on the value you tried to enter.
Try to change this line:
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
to this:
window.location.href = "smartphon100.php?name='.$name.'&password='. $password";
Overall you should read about security as the code you presented is very vulnerable.
PHP: SQL Injection - Manual
If you're trying to pass the values to another page in a POST method using Javascript, you could take a look at this answer:
JavaScript post request like a form submit
Although as I don't see a reason for posting the values more than once,
I recommend you to read about PHP sessions, cookies, and encryption, which allow you to store values that you can use across the website securely.
A simple example to using session:
<?php
//Starts the session, you need to use this line in every PHP file that'll need to access session variables
session_start();
$_SESSION['user'] = "Donny"; //Storing a user name
?>
A simple example of session use with your code:
Foo.php
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['user'] = $name;
$_SESSION['pass'] = $password;
$msg = "Username and password match";
echo '<script type="text/javascript">window.location.href = "smartphon100.php";</script>';
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
Bar.php
<?php
session_start();
//Accessing the values:
echo $_SESSION['user'];
echo $_SESSION['pass'];
?>
NOTE:
It's not good to store values like that as again, they're not secure, please read about hashing passwords.
PHP: Password Hashing

PHP and Javascript - Problems with undefinded variable

Hey guys i am very new to this so i am sorry if there is just something completely stupid i am missing here. I have the following Sign Up Form. And in the URL http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de i am trying to submit the value e. However, in all cases e is simply empty or undefined:
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$p = $_POST['p'];
$e = $_GET['e'];
echo "test";
echo "$e";
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM team WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "UPDATE team
SET username='$u',password='$p_hash',ip='$ip',signup=now(),lastlogin=now(),notecheck=now()
WHERE email='$e'";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>yoursitename Message</title></head>
<body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;">
<div style="padding:10px; background:#333; font-size:24px; color:#CCC;">
<img src="http://www.rockaholics-cologne.de/root/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">Account Activation</div>
<div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* Username: <b>'.$u.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
I do get new entries into the database when i fill out the form. But it does neither send me an email or UPDATE the database at the specified email. It simply updates all the entries with a blank email. The echo "$e" within the script also return nothing.
I used this code to check:
<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
$e = $_GET['e'];
echo "$e";
?>
And in this case it does return an array with [e]=cataras#gmx.de and it also prints out $e. But why doesnt it work in the other skript? I'm using the exact same methods to get e from the URL.
When i run my Javascript function:
function signup(){
var u = _("username").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.replace(/^\s+|\s+$/g, "") == "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&p="+p1);
}
}
I get Uncaught ReferenceError: e is not defined. And the site stops at "please wait...". I just took out the +e+ in the js to get to the php above. Sorry for the long post but i am really running out of ideas. THANKS in advance!!!
I think $_GET['e'] is not working in your original script because it's not getting passed to that processing script from your form page. I accessed the URL you provided (http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de). Note that when you submit your form, the value of "e" in your URL is not being passed to whatever is processing your script. In your form, you need to either do this:
<form action="{yourscripturl}?e=<?php echo $_GET['e']?>" {rest of form tag}>
Or, add a hidden to hold the value of "e", and then use $_POST['e'] on your processing script instead of $_GET['e'].
<input type="hidden" name="e" value="<?php echo $_GET['e']?>" />

Categories

Resources