Jump to content
Larry Ullman's Book Forums

Login Script - Same Page Ajax Request

Recommended Posts

Hello forum members,

I am using Ajax with one of my forms after having gone through chapter 15: Introducing jQuery.

Script 15.10 - login.js makes a request to a PHP file - login_ajax.php. The Ajax options include this line:

options.url = 'login_ajax.php';

Instead of making a request to another PHP file, I need to make a request to the same PHP page, which includes the login_ajax.php script. I'm using URL rewriting and so the options.url line looks like:

options.url = '/mysite/somedirectory/blah';

Is this correct? I've kept the other Ajax options as they are, for example, options.type = 'get';

So far this isn't working - I don't get any response when the submit button is clicked.

What might the problem be? Please let me know if you require more info. Thank you for any help.

Link to comment
Share on other sites

Hi HartleySan,

thanks for getting back to me. Looking at the console, the response I get back is the complete page and not a specific string such as "INVALID_EMAIL". When I do make a request to another PHP file, then a string is returned.

The reason why I want to make a request to the same page is because once the form has been successfully filled out, I need to call the header function, which includes variables that aren't present in the external PHP file.


Thank you for helping me.


My setup looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
    <script type="text/javascript" src="js/jquery-1.6.1.min.js" charset="utf-8"></script>
    <!-- Script 15.8 - login.php -->
if (isset($_GET['email'], $_GET['password'])) {

    // Need a valid email address:
    if (filter_var($_GET['email'], FILTER_VALIDATE_EMAIL)) {
        // Must match specific values:
        if ( ($_GET['email'] == 'email@example.com') && ($_GET['password'] == 'testpass') ) {
            // Set a cookie, if you want, or start a session.

            // Indicate success:
            echo 'CORRECT';
            header('location: /mysite/$name/$id');
                        exit ();
        } else { // Mismatch!
            echo 'INCORRECT';
    } else { // Invalid email address!
        echo 'INVALID_EMAIL';

} else { // Missing one of the two variables!
    echo 'INCOMPLETE';
<p id="results"></p>
<form action="login.php" method="post" id="login">
    <p id="emailP">Email Address: <input type="text" name="email" id="email" /><span class="errorMessage" id="emailError">Please enter your email address!</span></p>
    <p id="passwordP">Password: <input type="password" name="password" id="password" /><span class="errorMessage" id="passwordError">Please enter your password!</span></p>
    <p><input type="submit" name="submit" value="Login!" /></p>
$(function() {
        var url = window.location.pathname;
    // Hide all error messages:
    // Assign an event handler to the form:
    $('#login').submit(function() {
        // Initialize some variables:
        var email, password;
        // Validate the email address:
        if ($('#email').val().length >= 6) {
            // Get the email address:
            email = $('#email').val();
            // Clear an error, if one existed:

            // Hide the error message, if it was visible:
        } else { // Invalid email address!
            // Add an error class:

            // Show the error message:

        // Validate the password:
        if ($('#password').val().length > 0) {
            password = $('#password').val();
        } else {
        // If appropriate, perform the Ajax request:
        if (email && password) {
            // Create an object for the form data:
            var data = new Object();
            data.email = email;
            data.password = password;
            // Create an object of Ajax options:
            var options = new Object();

            // Establish each setting:
            options.data = data;
            options.dataType = 'text';
            options.type = 'get';
            options.success = function(response) {
                // Worked:
                if (response == 'CORRECT') {
                    // Hide the form:
                    // Show a message:
                    $('#results').text('You are now logged in!');
                } else if (response == 'INCORRECT') {
                    $('#results').text('The submitted credentials do not match those on file!');
                } else if (response == 'INCOMPLETE') {
                    $('#results').text('Please provide an email address and a password!');
                } else if (response == 'INVALID_EMAIL') {                    
                    $('#results').text('Please provide your email address!');
            }; // End of success.
            options.url = url;

            // Perform the request:
        } // End of email && password IF.
        // Return false to prevent an actual form submission:
        return false;
    }); // End of form submission.

}); // End of document ready.
Link to comment
Share on other sites

I would advise against your current approach for reasons that are likely already obvious to you.

Nowadays, I quite often structure my index.php file as follows for any Ajax-driven pages:


  // Include config file.
  // Maybe do some security checks.
  // List array of CSS files to include.
  // List array of JS files to include.
  // Include header.
  // Include content.
  // Include footer.
I then structure my content include so that it loads all the necessary content on page load, but I can also make Ajax requests to the same script, and depending on the request, I can easily route it to return the HTML I desire.
With that said, depending on the complexity of the page, I very well may have additional scripts for handling Ajax POST requests that insert into or update the DB, so don't feel like you have to or attempt to cram all your functionality into one script.
If all your files are well organized, having multiple files to handle a page is not a bad thing.
Link to comment
Share on other sites

Thanks for all of the info. If I do an Ajax request to another PHP script, as in chapter 15, do you know how I should handle the header function?


Instead of:

 if (response == 'CORRECT') {
                    // Hide the form:
                    // Show a message:
                    $('#results').text('You are now logged in!');


I would need to do:

 if (response == 'CORRECT') {

            header('location: /mysite/$name/$id');
            exit ();


But clearly this won't work? I am a bit lost...


Thank you for your help.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...