Reputation: 13
I am trying to get a basic AJAX form working. I want to get a line of text to display upon success of a PHP form through AJAX, but on submission of the form I am just directed to the PHP file. Can anyone identify the problem to make the text appear on the same page upon login success?
Code is below:
HTML JS PHP
in order:
$(document).ready(function() {
$(".loginform").submit(function () {
var username = $('input[id=username]').val();
var password = $('input[id=password]').val();
$.ajax({
type: "POST",
url: "login.php",
data : "username="+username+"&password="+password,
type: "POST",
success: function (data) {
var success = data['success'];
if(success == false){
var error = data['message'];
alert(error);
}
if(success == true) {
$('#result').write('Login success! Loading dashboard...');
}
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>
Please log in:
<form name="loginform" class="loginform" method="post" action="login.php">
Username: <input name="username" id="username" /><br />
Password: <input name="password" id="password" /><br />
<input name="submit" type="submit" />
</form>
</p>
<p>
<div id="result">
</div>
</p>
Upvotes: 1
Views: 112
Reputation: 12181
Check this similar one: event.preventDefault doesn't seem to work
TLDR Answer: You have to just return false;
to prevent PHP form submission in the callback for the onSubmit event:
For Code Improvement:
Please use correct indentation for better clarity and feel free to follow the comments for some suggestions of improvement ;). Let me know if you need any more clarifications :)
JQuery:
$(document).ready(function() {
$(".loginform").submit(function (event) {
// the proper way would be
//var username = $('input#username').val();
//var password = $('input#password').val();
var username = $('input[id=username]').val();
var password = $('input[id=password]').val();
$.ajax({
type: "POST",
url: "login.php",
//based on michael's post it should be
//data: {username: username, password: password},
data : "username="+username+"&password="+password,
//type: "POST", <-- not needed based on michael's post
success: function (data) {
var success = data['success'];
//probably needs to be success==="false" and I suggest
//not to use success name again in there..
if(success == false){
var error = data['message'];
alert(error);
}
// probably should be just else{ or else if(success==="true")
// I would check it first in the if because usually you will
// have a success more often than a failure
if(success == true) {
//based on Styphon's answer there is no write so it should be
//one of: append(element), prepend(element), text("content") or html("content")
$('#result').write('Login success! Loading dashboard...');
}
}
});
// return false is like calling event.preventDefault(); and event.stopPropagation().
//As such prevents redirection to PHP/Server code */ or in other words it WON'T
//submit the form to PHP using the name=" " input attributes
//and method=" "/action=" " attributes in your form tag
return false;
});
});
HTML
If you are submitting the form only through AJAX and not the old way then you only need whatever I have below. Some suggestions:
<br/>
use css positioning<button class="someclass">value</button>
instead of <input type="submit"/>
and in javascript you would do $("button.someclass").click(function(event){ blabla })
instead of $(".loginform").submit(function(event){blabla});
but don't forget return false;
<p>
Please log in:
<form class="loginform">
Username: <input id="username" /><br />
Password: <input id="password" /><br />
<input name="submit" type="submit" class="someclass" />
</form>
</p>
<p>
<div id="result">
</div>
</p>
PHP:
IMPORTANT: Never store passwords in plain text in your database (e.g for production). Use some hashing (MD5/SHA-1) and compare the user's input hashed with what it is in the database hashed (See for details: How do I create and store md5 passwords in mysql). Btw even that is not enough and you need to also use Salting before hashing..
e.g:
$hashedpass = hash('sha256', $pass);
$query = "select * from user where name = '$escapedName' and password = '$hashedpass'; ";
Upvotes: 1
Reputation: 40038
This might not be your problem, but FWIW:
In your ajax code block, you are posting the data to login.php
. You have not mentioned the name of the page on which your ajax source code resides -- if it is login.php
, then you will get the behaviour you are describing.
By design, AJAX should post to an external (separate) PHP file. There is a way to post AJAX to the same page, but it requires configuration (ask Felix Kling, he knows how to do it).
See this answer for more information.
values not updated after an ajax response
Upvotes: 0
Reputation: 10447
The problem is you're not stopping the form from submitting, so after it runs the Ajax the form goes on to submit like a normal form. To stop this just return false
at the end of your function.
$(document).ready(function() {
$(".loginform").submit(function () {
var username = $('input[id=username]').val();
var password = $('input[id=password]').val();
$.ajax({
type: "POST",
url: "login.php",
data : "username="+username+"&password="+password,
type: "POST",
success: function (data) {
var success = data['success'];
if(success == false){
var error = data['message'];
alert(error);
}
if(success == true) {
/* There is no .write function, you either want .append() to
add text on to the end, or to replace the contents .text()
or .html(). In this case I would use .text() */
$('#result').text('Login success! Loading dashboard...');
}
}
return false; /* <-- returning false here stops the form submitting. */
});
});
});
Upvotes: 0
Reputation: 73231
You need to return false to prevent form from submitting. Also, you have declared type: "POST" two times and the data looks more like a $_GET request. I've changed the code below.
$(document).ready(function() {
$(".loginform").submit(function () {
var username = $('input[id=username]').val();
var password = $('input[id=password]').val();
$.ajax({
type: "POST",
url: "login.php",
data : {
username : username,
password: password
},
success: function (data) {
var success = data['success'];
if(success == false){
var error = data['message'];
alert(error);
}
if(success == true) {
$('#result').write('Login success! Loading dashboard...');
}
}
});
return false;
});
});
Upvotes: 1