Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused on the basics of AJAX

So right now, I'm just using a basic form to check a password. I want it to check the password and basically remain on page.html so I can use JavaScript to alert incorrect password or something. I'm not really sure how to do that. It seems it would bring me to check.php. I'm not too sure on the whole process, any help appreciated! Thanks!

Page.html

<form action="check.php" method="post">
    <input type="password" name="password" />
    <input type="submit" value="Submit" />

</form>

check.php

   <?php
    $password = $_POST['password'];
    if ( $password != "testing" ) {
        die();
    }
?>
like image 502
Strawberry Avatar asked Dec 10 '22 16:12

Strawberry


2 Answers

PHP runs at the webserver which usually runs at a physically different machine (the server side) than where the webbrowser runs (the client side). The machines are usually connected by a network. HTTP is a network protocol. The webbrowser sends a HTTP request. The webserver retrieves a HTTP request whose URL indicates that it should be forwarded to PHP for further processing. PHP retrieves the HTTP request and does the processing and returns a HTTP response. Usually in flavor of a plain vanilla HTML page. The webserver sends HTTP response back to the webbrowser.

JavaScript runs at the webbrowser and knows nothing about PHP since it runs at the webserver. PHP in turn also knows nothing about JavaScript (although it can produce some JS code which is in turn to be sent to the webbrowser over HTTP). The only way to communicate between JS and PHP is HTTP. One of the ways to let JS fire a HTTP request and retrieve a HTTP response is using XMLHttpRequest. This is the core technique behind Ajax.

I see in your question history that you're already familiar with jQuery. It's a JS library with a lot of convenient functions to fire ajaxical requests. In this specific case you would like to use $.post. E.g.

$('#formId').submit(function() {
    $.post('check.php', $(this).serialize(), function(valid) {
        if (valid) {
            alert('Valid!');
        } else {
            alert('Invalid!');
        }
    });
    return false; // Important! This blocks form's default action.
});

With in check.php:

<?php
    echo $_POST['password'] != "testing";
?>

This is however not unobtrusive. If the user has JS disabled, then all will fail. Your best bet is to check in PHP if an ajaxical request is been fired by jQuery or not and handle accordingly:

if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    // Ajax.
} else {
    // No ajax.
}

Alternatively you can let jQuery also reach a different URL or append an extra parameter.


Update: here is how the JavaScript would look like when not using jQuery:

document.getElementById('formId').onsubmit = function() {
    var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            if (xhr.responseText) {
                alert('Valid!');
            } else {
                alert('Invalid!');
            }
        }
    }
    xhr.open('POST', 'check.php', true);
    xhr.send(serialize(this));
    return false; // Important! This blocks form's default action.
}

function serialize(form) {
    var query = '';
    for(var i = 0; i < form.elements.length; i++) {
        var e = form.elements[i];
        if (!e.disabled && e.name 
            && ((e.type != 'checkbox' && e.type != 'radio') || e.checked)
            && (e.type != 'submit' || e == document.lastClicked))
        {
            if (query.length) query += '&';
            query += e.name + '=' + encodeURIComponent(e.value);
        }
    }
    return query;
}   

document.onclick = function(e) {
    e = e || event;
    document.lastClicked = e.target || e.srcElement;
}

Bloated and verbose, yes ;)

like image 94
BalusC Avatar answered Dec 31 '22 20:12

BalusC


You'll have to use ajax if you want to remain on the same page. I recommend using jquery and jquery's post function.

Basically you create a javascript function that gets called when the login button is clicked. The function will send a request to check.php. Check.php will output a status message (maybe 1 for succes, 0 for fail) that will be returned to the original script. From there you can output a message saying invalid password, or set a cookie if it was correct.

like image 20
Galen Avatar answered Dec 31 '22 19:12

Galen