2

I am trying to implement a simple login system with php/mysql/jquery. I want it to be a single page app, so I have this for my "index.php":

<?php session_start(); ?>

<!DOCTYPE html>
<html>
<head>
<title>it IT</title>
<script src="reqscripts/jquery.js" type="text/javascript"></script>
<script src="js/application.js" type="text/javascript"></script>
</head>
<body>
    <div id="main"></div>
</body>
</html>

I have this for my jquery:

js/application.js

$(document).ready(function() {
    $("#main").load("templates/indexforms.php");

    $("#login").submit(function(e) {
        e.preventDefault();
        $.post("checklogin.php", $(this).serialize(), function(){
            $("#main").load("templates/login_success.php");
            $("#login").remove();
            $("#register").remove();
        });
    });
});

This form gets loaded (templates/indexforms.php):

<?php session_start(); ?>

<form id="login" method="post" action="checklogin.php">
    <h1>Member Login</h1>
    <p>Username:<input name="myusername" type="text" id="myusername"></p>
    <p>Password:<input name="mypassword" type="password" id="mypassword"></p>
    <input type="submit" name="Submit" value="Login">
</form>

Right now, when I try to login - it gets stuck on localhost/~Eamon/checklogin.php (which doesn't have any html in it) and a completely blank page is rendered (no source code at all). Do I need to include application .js in my indexforms.php template? Where would I do this? Also, if you look at my jquery, I am loading the forms right after the DOM is ready - but on form submission...the forms are supposed to be removed - and the login_success.php should be loaded.

UPDATE

checklogin.php

<?php

session_start();

$host="localhost"; // Host name
$username="xxx"; // Mysql username
$password="xxx"; // Mysql password
$db_name="itit"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
$mysqli = new mysqli("$host", "$username", "$password", "$db_name")or die("cannot connect");

// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

$sql = $mysqli->prepare("SELECT * FROM $tbl_name WHERE username=? and password=?");
$sql->bind_param('ss',$myusername,$mypassword);
$sql->execute();
$sql->store_result();//apply to prepare statement
$numRows = $sql->num_rows;

if($numRows === 1){
    $_SESSION['username'] = $myusername;
}
else {
    echo "Wrong Username or Password";
    session_destroy();
}
?>

UPDATE

I don't think my javascript file is being loaded. I put alert("here") before e.preventDefault and nothing happens...is the second line of my application.js file messing things up? Why is it not getting loaded?

I found this here - does this help anyone?

JavaScript files loaded using the script tag are blocking by nature. Everything that’s happening or loading on the page is halted while the script is downloaded and executed. And remember that this applies to each script tag. Some modern browsers may let you download these in parallel, but the rest of the page is still blocked from doing anything meaningful

UPDATE

I put echo "success" inside the if block of checklogin.php...like this (at the bottom):

...

if($numRows === 1){
    $_SESSION['username'] = $myusername;
    echo "success";
}
else {
    echo "Wrong Username or Password";
    session_destroy();
}
?>

and it never gets there. If I put it just before the if statement it displays the echo message...which means that the user isnt being found in my database...or something like that?

UPDATE

Put var_dump($numRows) after $numRows = $sql->num_rows; like this:

...

$numRows = $sql->num_rows;
var_dump($numRows);

if($numRows === 1){
    $_SESSION['username'] = $myusername;
}
...

I get int(1) as response...

UPDATE

Change the if condition in checklogin.php:

if($numRows === "int(1)"){
    $_SESSION['username'] = $myusername;
}
else {
    echo "Wrong Username or Password";
    session_destroy();
}

The else block gets executed and I see "Wrong Username or Password" - as I should.

UPDATE

Changed jquery code to this...still no luck:

$(document).ready(function() {
    $("#main").load("templates/indexforms.php", function () {
        $("#login").submit(function(e) {
            e.preventDefault();
            $.post("checklogin.php", $(this).serialize(), function() {
                $("#main").load("templates/login_success.php");
                $("#login").remove();
                $("#register").remove();
            });
        });
    });
});

CORRECTION

The above code is correct! I just needed to restart the server! Thanks!

UPDATE

Found a new problem, here you go: simple login system spa/php/mysql/jquery

Community
  • 1
  • 1
ewizard
  • 2,801
  • 4
  • 52
  • 110
  • Placement of PHP and HTML is important. Are you placing any output before PHP? I.e.: HTML, whitespace etc. – Funk Forty Niner Jun 17 '13 at 02:20
  • Also if possible, can you show us what is inside `checklogin.php`? Omitting any vital information of course. – Funk Forty Niner Jun 17 '13 at 02:22
  • @Fred hey...i will update my question with checklogin.php...and i dont think I am outputting anything (like echo?) unless the login fails. – ewizard Jun 17 '13 at 02:24
  • Make sure you don't have any `echos` mixed in with `header` stuff. Do you have error reporting set to `on` to see if there are in fact any errors? – Funk Forty Niner Jun 17 '13 at 02:25
  • Safest way to build, is PHP, then HTML. That way, if you have any header information, it needs to be placed before any output, including `echos`. – Funk Forty Niner Jun 17 '13 at 02:26
  • Modify your edit to remove and replace username and password with generic information. You have yours posted, not safe. Generic meaning, `username=myusername` and `password=mypassword`. – Funk Forty Niner Jun 17 '13 at 02:28
  • What's in your `index.php`? That I need to see what kind of structure you have. Calls to files, etc. – Funk Forty Niner Jun 17 '13 at 02:29
  • @Fred the only echo i have is in the else statement at the bottom of checklogin.php - which isnt being executed because I know I am typing in the correct member username and password (as i created it in the mysql database). thanks for the password thing...and i posted my index.php...it is the first block of code in my question – ewizard Jun 17 '13 at 02:32
  • @Fred do i need session_start() in my indexforms.php? – ewizard Jun 17 '13 at 02:36
  • Try adding `` above ` ` in your index.php file. – Funk Forty Niner Jun 17 '13 at 02:38
  • Yes, you need `session_start();` in every .php file involved, and it needs to be on top, as you have it in your others right now. See my above comment about adding it to your index.php – Funk Forty Niner Jun 17 '13 at 02:38
  • If you don't have any PHP tags already set for `indexforms.php`, then you'll need to put `` on top of the forms code. – Funk Forty Niner Jun 17 '13 at 02:41
  • @Fred ..tried your suggestion - still no luck - i added session_start to the indexforms.php too - should i do that? – ewizard Jun 17 '13 at 02:42
  • @Fred we must have posted at the same time...didnt see your comment about the indexforms...funny i had that question. where would i have php tags? – ewizard Jun 17 '13 at 02:44
  • Just do `
    ... rest of form`
    – Funk Forty Niner Jun 17 '13 at 02:47
  • @Fred tried it...no luck – ewizard Jun 17 '13 at 02:48
  • 1
    let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/31843/discussion-between-ewizard-and-fred) – ewizard Jun 17 '13 at 02:48
  • When you fire up the whole thing, does the form show up? – Funk Forty Niner Jun 17 '13 at 02:50
  • I'd also recommend to use more than just jquery for a spa – Ven Jun 17 '13 at 20:29
  • @user1737909 what else should i use? im trying to avoid using any frameworks (like backbone or node) as I am still learning the in's and out's of the languages – ewizard Jun 17 '13 at 21:22
  • yeah, that's a valid point, but i'm afraid you're going to have a code spaghetti. But if you want to train, that still can fits – Ven Jun 18 '13 at 06:44

1 Answers1

1

Try changing the JavaScript to this:

$(document).ready(function()
{

  $("#main").load("templates/indexforms.php", function ()
  {

    $("#login").submit(function(e)
    {

      e.preventDefault();

      $.post("checklogin.php", $(this).serialize(), function()
      {
        $("#main").load("templates/login_success.php");
        $("#login").remove();
        $("#register").remove();
      });

    }
    )

  }
  )

}
)

Notice that the script waits until indexforms.php is loaded in #main before adding the submit event to #login (at the moment it's trying to do it (pretty much) at the same time so $("#login").submit(... is run before there is any #login element).

Michael
  • 11,912
  • 6
  • 49
  • 64
  • i updated my question to show you what I did...I wasn't sure how your brackets were working...im not sure if i got it or not...let me know if there are any syntax errors – ewizard Jun 17 '13 at 21:51