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 != "t开发者_StackOverflowesting" ) {
die();
}
?>
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 ;)
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.
The simple solution to what you're trying to do (essentially AJAX) is:
- Modify your php script to output something unique on success or failure.
- Use JavaScript to submit the data to the php script, instead of the normal form POST.
- Have the JavaScript alert the user if the password is invalid, or direct to an appropriate page if the password is valid.
Of course those are the broad strokes. In reality you'll need your php script to give one kind of response when an AJAX request (a request made by JavaScript) is made, and another response when the page is requested by a regular form POST - you do want it to work without JavaScript - right? You'll probably want the JavaScript to update the page contents instead of an alert box. You'll want your php script to set session variables so the next page they access knows they are logged in.
Broad strokes.
Reading the jQuery AJAX documentation may help.
When designing a web site, always add JavaScript after everything works fine without it. The reason for this is twofold. For one, some people browse without it turned on. The other reason is that JavaScript is always viewable and editable by the crackers out there.
This approach requires that you have a separate PHP file that validates the success of the password. Everything on the original page (HTML and JS) should only send the password and perhaps wait for the request. To keep things on the same page, you can use AJAX to send the input password and print out the response that it receives. jQuery makes AJAX easy if you don't want mind the overhead.
Using POST over HTTPS is better than using GET and HTTP. Of course, keep track of session variables and you might also want to limit the amount of time from when one first receives the form and when they actually submit it.
精彩评论