user1552172
user1552172

Reputation: 676

Cannot get ajax post to work

I am able to the js file to fire which does do the first alert but i cannot get the 2nd alert to happen, php file is there and working returning 0 but the alert('finished post'); is not coming up. I think its some syntax I am missing.

$(function () {
$("#login_form").submit(function () {
    alert('started js');
    //get the username and password  
    var username = $('#username').val();
    var password = $('#password').val();

    //use ajax to run the check  
    $.post("../php/checklogin.php", { username: username, password: password }, 
        function (result) {
            alert('finished post');
            //if the result is not 1  
            if (result == 0) {
                //Alert username and password are wrong 
                $('#login').html('Credentials wrong');
                alert('got 0');
            }
    });
});

});

Here is the php

session_start();
include 'anonconnect.php';

// username and password sent from form 
$myusername= $_POST['username']; 
$mypassword= $_POST['password']; 

$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$sql = $sql->fetch();

$admin = $sql['admin'];

$password_hash = $sql['UserPass'];
$salt = $sql['salt'];

/*** close the database connection ***/
$dbh = null;

if(crypt($mypassword, $salt) == $password_hash){
    // Register $myusername, $mypassword and redirect to file
    $_SESSION['myusername'] = $myusername;
    $_SESSION['loggedin'];
    $_SESSION['loggedin'] = 1;

    if($admin == 1){
        $_SESSION['admin'] = 1;
    }

    header("location:search.php");
}
else {
    $_SESSION['loggedin'];
    $_SESSION['loggedin'] = 0;
    echo 0;
}

Upvotes: 1

Views: 1550

Answers (4)

Jeff Escalante
Jeff Escalante

Reputation: 3167

Ok so I'll take a stab at this, see if we can work this out. First, let's clean up your code a little bit - clean code is always easiest to debug:

$(function () {
  $("#login_form").on('submit', function(){
    console.log('form submitted');

    // get the username and password  
    var login_info = { username: $('#username').val(), password: $('#password').val() }

    // use ajax to run the check
    $.ajax({
      url: '../php/checklogin.php',
      type: 'POST',
      data: login_info,
      success: loginHandler
      error: function(xhr, status, err){ console.log(xhr, status, err); }
    });

   return false;

  });

  function loginHandler(loggedIn){
    if (!loggedIn) {
      console.log('login incorrect');
    } else {
      console.log('logged in');
    }
  }

});

...ok great, we're looking a little better now. Let's go over the changes made quickly.


  • First, swapped alerts for console.logs - much less annoying. Open up your console to check this out -- command + optn + J if you're using Chrome.

  • Second, we compressed the login info a bit - this is just aesthetics and makes our code a little cleaner. Really you should be using variables when they need to be used again, and in this case you only use them once.

  • Next, we swapped the $.post function for $.ajax. This gives us two things -- one is a little finer control over the request details, and the second is an error callback, which in this case is especially important since you almost certainly are getting a server error which is your original problem. Here are the docs for $.ajax for any further clarification.

  • We're also pointing the success handler to a function to minimize the nesting here. You can see the function declared down below, and it will receive the data returned by the server.

  • Finally we're returning false so that the page doesn't refresh.


Now, let's get to the issue. When you use this code, you should see a couple things in your console. The first will probably be a red message with something like 500 internal server error, and the second should be the results of the error callback for the ajax function. You can get even more details on this in Chrome specifically if you click over to the Network Tab and look through the details of the request and response.

I can't fix your PHP because you didn't post it, but I'll assume you'll either follow up with an edit or figure that out yourself. Once you have the server issue ironed out, you should get back a clean console.log with the response you sent back, and you can move ahead.

Alternately, this will work because of the lack of page refresh in which case you can ignore the previous 2 paragraphs and declare victory : )

Hope this helps!

Upvotes: 3

MichaelLuthor
MichaelLuthor

Reputation: 436

try this:

$("#login_form").submit(function () {
    alert('started js');
    //get the username and password  
    var username = $('#username').val();
    var password = $('#password').val();

    //use ajax to run the check  
    $.post("../php/checklogin.php", { username: username, password: password }, function (result) {
        alert('finished post');
        //if the result is not 1  
        if (result == '0') {
        //Alert username and password are wrong 
            $('#login').html('Credentials wrong');
            alert('got 0');
        }
    }, 'text');
});
  1. }, 'text');

maybe the server does not give the right data format. for example, if you request for json, and the jQuery cannot convert result sting to json. then the function would not be executed and then you would not able to get 'alert('got 0');' thing.

Upvotes: -1

Michael B.
Michael B.

Reputation: 2809

you need to change 2nd line and add the e.preventDefault to prevent the form from refreshing the whole page.

$("#login_form").submit(function (e) {
    e.preventDefault();

Also I would change the AJAX request to use GET and change the code in PHP to read variables from GET so you can easily test the PHP page is working by running it in the browser like this checklogin.php?username=x&password=y

Upvotes: -1

Phil
Phil

Reputation: 164766

Ah, so damned obvious. You aren't cancelling the default submit action so the form is submitting normally. Add this

$("#login_form").submit(function (e) {
    e.preventDefault();

    // and so on

See http://api.jquery.com/event.preventDefault/

Upvotes: 1

Related Questions