Reputation: 17
I have created a login form and trying to submit it using jquery but it doesn't work.I have searched google but all methods are a bit complicated.Here is my code
<form id="form1">
<p>Username<p/>
<input type="text" id="username"/>
<p>Password</p>
<input type="password" id="password"/>
<p><input type="Submit" value="Log in" id="button"></p>
</form>
<script type="text/javascript" src="jquery.js"></script>
<script>
$("#button").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.get("signing.php",{'username':username,'password':password},function(response){
alert(response);
});
});
</script>
My php file is like this
<?php
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
include 'model/existusername.php';//This is used to connect to database and find the user
if (existusername($username,$password))
{
$_SESSION['username']=$username;
echo "loged in";
}
else
{
echo "not loged in";
}
?>
Is there something wrong with it?If I use a select box(although not useful for loging in) instead of input box the code works fine.How is that possible?? Thank you
Upvotes: 0
Views: 1412
Reputation: 117
It is very simple
$.ajax({
type: "POST",
cache:false,
async:true,
url: "index.php",
data: $('#id').serialize(),
success: function(data){
alert(data);
}
});
Here id is your form id.try this very easy you can do
Upvotes: 0
Reputation: 20267
Edit your method to look like this:
$("#button").click(function(event){
event.preventDefault();
// ...
});
Alternatively, use a button input that won't cause a submission.
<input type="button" value="Log in" id="button">
Since the button is a submit button, the page is performing a form submission before the GET response arrives. Prevent the submission from happening, and your code should work.
Upvotes: 0
Reputation: 9269
Add an "action=" on your form, and after something like that :
$('#button').click(function() {
$('#form').submit();
});
No ?
And you are using GET and try to recover POST..i think it's not normal.
Upvotes: 1
Reputation: 114
You are using $.get() which sends a get request with jquery.
Your php file is checking the $_POST vars.
Upvotes: 1
Reputation: 340
<form id="form1" method="post" action="pathToYourPhpScript">
<p>Username<p/>
<input type="text" id="username"/>
<p>Password</p>
<input type="password" id="password"/>
<p><input type="Submit" value="Log in" id="button"></p>
</form>
You have to remember to select the method, and proberbly the action in the form start tag.
as standard the data is sent through a GET request, and you are trying to read from a post.
The example i have provided is with no AJAX, but again, if you wanna make it work with the ajax, you have to alter your javascript to do a POST request.
Upvotes: 0