1

I'm working on a user login system using jQuery UI modal dialogs to interact between my html and PHP scripts. Recently, I moved all of my user functionality to one PHP file, from where I had them before in my header markup.

I was able to get the login functionality to work if someone puts in a valid username/password, but now I am trying to account for other possibilities, i.e. someone enters a valid username but incorrect password, or if they enter a username that does not exist.

The problem I'm having is with the AJAX call on the Dialog script. I want to submit the login form to the same page, user.php, and either log a user in, or return an error message that would populate a div on the same dialog.

Right now, my code will return an error message, but it also returns a copy of the user form. Not really sure what I am doing wrong here...
Any input would be appreciated.

EDIT: Decided to go ahead and post the entirety of user.php, since making changes based on one answer made the html added by this file disappear entirely. I'm now guessing that there are probably several things I'm doing wrong:

    <html>
    <span id="user">
            <ul>
                <?php
                    //if user is logged in, show name and Log Out option, else show Log In and Sign Up options
                    if(isset($_COOKIE["user"])) {
                        setSessionUserData($_COOKIE["user"]);
                        echo "<li>Logged in as {$_SESSION["username"]}</li>";
                        echo "<li>&nbsp;|&nbsp;</li>";
                        echo "<li><a href='#' id='logout_link'>Log Out</a></li>";
                    } else {
                        echo "<li><a href='#' id='login_link'>Log In</a></li>";
                        echo "<li>&nbsp;|&nbsp;</li>";
                        echo "<li><a href='#'>Sign up</a></li>";
                    }
                ?>
            </ul>
    </span>

    <div id="login_dialog" title="Existing User">
        <form id="login_form">
            <fieldset>
                <label for="userid">Username</label>
                <input type="text" name="username" id="username" />
                <label for="pw">Password</label>
                <input type="password" name="pw" id="pw" />
            </fieldset>
        </form>
        <span class = "error"></span>
    </div>
    <div id="logout_dialog" title="Log Out">
        <p><span class="ui-icon ui-icon-alert alert-icon"></span>Are you sure you want to log out?</p>
    </div>

    <script>
    $(function() {
        var username = $("#username"),
        password = $("#pw"),
        loginFields = $([]).add(username).add(password);

        $("#login_link").click(function() {
            $("#login_dialog").dialog("open"); 
        });

        $("#logout_link").click(function() {
            $("#logout_dialog").dialog("open");
        });

        $("#login_dialog").dialog({
            autoOpen: false,
            height: 200,
            width: 250,
            resizeable: false,
            modal: true,
            buttons: {
                Submit: function() {
                    $.post("auth.php",
                            {
                            username: $("#username").val(),
                            password: $("#pw").val()
                            },
                            function(result) {
                                if(result=='success'){
                                      window.location='Practice.php';
                                }
                                else {
                                    $(".error").html(result);
                                }
                            }
                          )
                    },
                Cancel: function(){
                    $(this).dialog("close");
                }                
            },
            close: function() {
                loginFields.val("");
            }
        });

        $("#logout_dialog").dialog({
            autoOpen: false,
            modal: true,
            height: 150,
            resizeable: false,
            buttons: {
                Okay: function() {
                    window.location = "logout.php";
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });

    });
</script>
</html>

<?php

function setSessionUserData($cookie) {
    $con = connect();

    $query = "SELECT * FROM practice_user WHERE userid = '$cookie'";
    $result = mysqli_query($con, $query);
    $userData = mysqli_fetch_array($result);

    $_SESSION["username"] = $userData["username"];
    $_SESSION["fname"] = $userData["first_name"];
    $_SESSION["lname"] = $userData["last_name"];
}

?>

...and the PHP:

if($_SERVER["REQUEST_METHOD"] == "POST") {
$user = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);

//check if correct login
if (chkLogin($user, $pass)) {
    $id = getUser($user, $pass);
    setUserCookie($id);
    header("Location: Practice.php");
}
//check if username exists but incorrect password entered
else if (chkUser($user)) {
    echo "Username and password do not match";
}
//Or else return that username doesn't exist
else {
    echo "Username does not exist";
}

}

There are other functions in my code to handle validation and such.
If I need to post those, please let me know.

3
  • What do you mean by "returns a copy of the user form"? It looks like this PHP code is only either issuing a redirect or echoing a string. I'm not seeing any other potential output. Is there other output in the code not shown here? It's not really clear to me what's happening here. Commented Jan 29, 2014 at 18:48
  • 1
    in your php you do a redirect on success, why not just return success and do the redirection in javascript? Commented Jan 29, 2014 at 18:48
  • There is a lot of code in this particular file. What I posted here is what is involved in the login functionality only. The rest are validation functions and code for the other functionalities (signout, create account, etc). I think the problem is in how I'm handling things in the PHP. I do want it to redirect on success...I'm probably not doing the AJAX correctly...or the PHP. I'm not really sure :/ Commented Jan 29, 2014 at 18:59

3 Answers 3

2

Can you try this,

You can't able to redirect the page in ajax calling php file itself, So redirection section moved into the javascript side.

Jquery,

    $("#login_dialog").dialog({
            autoOpen: false,
            height: 200,
            width: 250,
            resizeable: false,
            modal: true,
            buttons: {
                Submit: function() {
                    $.post("auth.php",
                            {
                            username: $("#username").val(),
                            password: $("#pw").val()
                            },
                            function(result) {
                                if(result=='success'){
                                    window.location='Practice.php';
                                }else{
                                   $(".error").html(result);
                                   }
                               }
                          )
                    },
                Cancel: function(){
                    $(this).dialog("close");
                }                
            },
            close: function() {
                loginFields.val("");
            }
        });

Create new page called auth.php, Included your dependency php function.

   <?php

    if($_SERVER["REQUEST_METHOD"] == "POST") {
    $user = test_input($_POST["username"]);
    $pass = test_input($_POST["password"]);

    //check if correct login
    if (chkLogin($user, $pass)) {
        $id = getUser($user, $pass);
        setUserCookie($id);
        echo "success";
    }
    //check if username exists but incorrect password entered
    else if (chkUser($user)) {
        echo "Username and password do not match";
    }
    //Or else return that username doesn't exist
    else {
        echo "Username does not exist";
    }
}
?>
Sign up to request clarification or add additional context in comments.

8 Comments

Fixed a bunch of problems with function placement, and now the error messages work correctly, but the setting of the cookie and redirection doesn't happen. Any idea why that might be?
Correction: setting the cookie works. Everything works now EXCEPT for the redirect on success... Banging my head against the proverbial wall right now trying to figure out why this doesn't work..
function(result) { console.log(result); can you update what is the result value in console log!
All that's returned by the console is Uncaught ReferenceError: header is not defined
did you used my auth.php answer? dont use header in auth.php
|
1

If you didn't want to do a redirect at all and you think you got an error because the ajax response was appended to $('.error') container.

This may help you

 Submit: function() {
                $.post("user.php",
                        {
                        username: $("#username").val(),
                        password: $("#pw").val()
                        },
                        function(result) {
                            if(result=='success'){
                              $("#login_dialog").append(result);
                              setTimeout(function(){
                                  $("#login_dialog").dialog("close");
                              },800);
                            }else{
                              $('.error').html(result);
                            }
                        }
                      )
                },

this appends the result into the dialog and closes it after a 800 milliseconds

1 Comment

Doing this produced the same result.
0

After several attempts to get Krish R's method to work, by making an AJAX call to a separate php page's code and redirecting on success via window.location, I found that window.location does not work by itself in the success of an AJAX call. I eventually found this answer to a similar problem that used window.location.assign(data) instead, and that worked perfectly.

While I don't understand exactly why this different method was necessary, it did work to solve the redirect issue. Thank you to all who responded. I am checking Krish R's answer as accepted, as it was that which was closest to the solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.