I don't know how to run $.ajax properly. I usually make all xmlHTTP objects manually using javascript and then use jQuery wherever required. So please help me use this function properly in jQuery.
HTML
<form action="login.php" method="post" onSubmit="return login()" >
<input type="text" name="eMailTxt" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="passWordTxt" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
JQuery Ajax
function login()
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
$("#loginForm p").innerHTML = xmlhttp.responseText;
return false; //is this the correct way to do it?
}
});
return true; //not really sure about this
}
PHP MySQL
$q=$_POST["q"];
$s=$_POST["s"];
$con=mysqli_connect("localhost","root","","SocialNetwork");
$check="SELECT PassWord FROM people WHERE EMAIL = '".$q."'";
$data=mysqli_query($con,$check);
$result=mysqli_fetch_array($data);
if ($s != $result)
{
echo "Password does not match";
}
jQuery object doesn't have a property innerHTML which is used on DOM element. Use method html() instead:
$("#loginForm p").html(response);
Or you could refer to DOM element like that:
$("#loginForm p")[0].innerHTML = response; // equivalent to .get(0)
Be aware as ajax is async by default, your login function here will always return true.
BTW, response here corresponds to the returned value from server, not the jqXHR object (xhr object wrapped inside a jquery object).
UPDATE
function login(form)
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
if(response === "Password does not match") {
$("#loginForm p").html(response);
return false;
}
//if password match, submit form
form.submit();
}
});
//we always return false here to avoid form submiting before ajax request is done
return false;
}
In HTML:
<form action="login.php" method="post" onSubmit="return login(this)" >
HTML
<form action="login.php" method="post" class="js-my-form">
<input type="text" name="record[email]" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="record[password]" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
jQuery
$(document).ready(function () {
$('.js-my-form').submit(function () {
var data = $(this).serialize();
var action = $(this).attr('action');
var methodType = $(this).attr('method');
$.ajax({
url: action,
type: methodType,
data: data,
beforeSend: function () {
//Maybe Some Ajax Loader
},
success: function (response) {
// success
},
error: function (errorResponse) {}
});
return false; //Send form async
});
});
PHP
if (isset($_POST['record']) {
//Your PHP Code
} else {
header("HTTP/1.0 404 Not Found"); // Trow Error for JS
echo 'invalid data';
}
Ajax success call back contains only data (you are confused with the compete function of ajax or pure javascript xmlhttp request)
therefore
success:function(response){
$("#loginForm p").html(response);
}
Also seeing your query you are susceptible to sql injection
Related
Here is my javascript and php code for loging in jquery mobile but i got parser error for this request. please help me with this.
<script>
$("#login").click( function () {
//collect userName and password entered by users
var username = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(username, password);
});
//authenticate function to make ajax call
function authenticate(username, password) {
$.ajax({url: "http://localhost/track/signinmobile.php",
data: '{"username": "' + username + '", "password" : "' + password + '"}',
dataType: "jsonp",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
alert(result);
},
error: function (request,error) {
alert("this is"+ error);
},
successCallback:function(){
}
});
</script>
<div data-role="fieldcontain" class="ui-hide-label">
<form id="login" >
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username"/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
<input type="submit" name="login" id="login" value="Login"/>
</form>
</div>
Is there any error in my javascript code?
Here is my signinmobile.php and the data base connections are working.
<?php include"connection.php";
$email=$_GET['username'];
$password=$_GET['password'];
$user=mysql_query("SELECT * FROM users");
while($row=mysql_fetch_array($user))
{
if (($email==$row['email']) && ($password==$row['password']))
{
$response_array['status'] = 'success';
}
else {
$response_array['status'] = 'error';
}
}
header('Content-type: application/json');
echo json_encode($response_array);
?>
You are missing a } to close the authenticate function.
Besides that your form and the submit button have the same id. It is in general a bad idea to have two html tags with the same id and this means that your function is called after clicking on the form.
You should wrap your script inside a $(document).ready.
$(document).ready(function() {
// your script.
});
This will prevent your script from running before the elements are loaded.
You should also prevent the form from submitting by ending the click function with a return false; statement. This prevents the page refresh.
And I don't have experience with jsonp but it generates an error for me. I would suggest using normal json but I don't know your other plans with the script.
The data you send to the server is a string, you should use a javascript object. This is done by removing the quotes and the plus signs.
data: { username: username, password: password },
EDIT:
This was related to a typo elsewhere in my Javascript. I had forgotten to check the Javascript console. Thank you for your comments.
This is my first post on this site. I have been reading it for a long while though.
I am working on a login form utilizing jQuery, AJAX, and PHP. Several times now I have run into the problem where I am redirected to the PHP page where I see the echoed data I wanted returned. I have tried to figure this out but I am stuck.
EDIT:
I did include jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
HTML:
<form name="login" id="loginForm" action="login.php" method="post">
<label for="usernameInput">Username: </label>
<input type="text" name="usernameInput" id="usernameInput" placeholder="Username" autofocus required>
<label for="passwordInput">Password: </label>
<input type="password" name="passwordInput" placeholder="Password" required>
<input type="submit" name="loginSubmit" value="Log In">
</form>
jQuery:
function login () {
$('#loginForm').on('submit', function(e){
e.preventDefault();
var formObject = $(this);
var formURL = formObject.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: formObject.serialize(),
dataType: 'json',
success: function(data)
{
$("#loginDiv").remove();
if(data.new) {
$("#setupDiv").show();
} else {
statusUpdate();
/* EDIT: Changed from dummy text 'continue()' */
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#loginDiv").append(textStatus);
}
});
});
}
Call:
$(document).ready(function() {
login();
});
PHP:
// Main
if (isset($_POST['usernameInput'], $_POST['passwordInput']))
{
require "hero.php";
// Starts SQL connection
$sql = getConnected();
$userArray = validateUser($sql);
if ( $userArray['id'] > 0 ) {
sessionSet($userArray);
$userArray['user'] = (array) unserialize($userArray['user']);
$userArray = json_encode($userArray);
echo $userArray;
exit();
}
else
{
echo 'Username does not exist';
}
}
else
{
echo "Please enter a username and password.";
}
I know I have not included everything, but here's the output:
{"id":"11","name":"st5ph5n","new":true,"user":[false]}
So everything up to $userArray is working as expected. Why is this not staying on index.html and instead redirecting to login.php?
Thank you for any responses.
Trying to create a login form using AJAX so the page does not have to change to log a user in. So far I have the following after using a tutorial I found however I have the problem of the form is reloading the page instead of calling the JavaScript function.
HTML:
<form class="login-form" onSubmit="check_login();return false;">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn trans login-button">Login</button>
</form>
PHP:
// Retrieve login values from POST variables
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
// Salt and hash password for database comparison
$password = saltHash($password);
// Check that both fields are not empty
if(!empty($email) || !empty($password)) {
// Query database to check email and password match entry
$database->query('SELECT * FROM users WHERE email = :email AND password = :password');
$database->bind(':email',$email);
$database->bind(':password',$password);
$result = $database->single();
if(!empty($result)) {
// Check entered details match the database
if($email == $result['email'] && $password == $result['password']) {
// If login details are correct, return 1
echo '1';
}
}
else {
// If not returned results, return 2
echo '2';
}
}
else {
// If either fields are empty, return 3
echo '3';
}
JavaScript / jQuery:
// Login function
function check_login() {
$.ajax({
type: 'POST',
url: 'check-login.php',
data: 'email=' + $('input[value="email"]').val() + '&password=' + $('input[value="password"]').val(),
success: function(response){
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
Any help is greatly appreciated.
Use This bro...
<form id="F_login" class="login-form">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit" class="btn trans login-button">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: 'check-login.php',
data: parm,
success: function (response) {
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
},
error: function (error) {
alert("Login Fail...");
}
});
});
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
It should run well...
Try this:
<form class="login-form">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button class="btn trans login-button" onclick="check_login()">Login</button>
</form>
When the login submits, it will still try to reload the page, so you should remove the submit type and put the login function on the button
Attaching event listeners via tags is not a good practice and using jQuery for it it's cleaner and easier.
Try doing this:
$("form.login-form .login-button").click(function(e) {
e.preventDefault();
check_login();
});
Remember to remove this:
onSubmit="check_login();return false;
The statement check_login();return false will not work. You have to call return check_login(); and return false inside the function.
HTML
<form onsubmit="return check_login();">
<!-- input fields here -->
</form>
Javascript
function check_login() {
// Do your ajax call.
return false;
}
Right way is:
HTML Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Login function
$(function() {
$('.login-button').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'check-login.php',
data: $('form.login-form').serialize(),
success: function(response) {
if (response === '1') {
alert('Log In Success');
} else if (response === '2') {
alert('Incorrect Details');
} else if (response === '3') {
alert('Fill In All Fields');
}
}
});
});
})
</script>
<title>Ajax Login Form (Demo)</title>
</head>
<body>
<form class="login-form" name="login-form" method="POST" action="">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit" class="btn trans login-button">Login</button>
</form>
</body>
</html>
Write your ajax code inside
$(document).ready(function(){
//
}); or
$(function(){
//
});
User Prevent Default to stop Form Submission
You can use 'serialize' function to make POST pram.
Remove the button type and use the onclick handler on it, not on the form.
It will also take care of the situation when it automatically submits on pressing enter key by accident.
Happy Coding !!!
there are a lot of way to do this:
write this code in your index:
index
use "eval" function in javascript instead of "alert" to show the reasult
it means that on your PHP code when the code receive the true inputs and there is a user in your database like the input, the PHP code echo javascript orders (bellow is your PHP codes that you send an ajax request to that):>
<?php if(response==1){
echo '$("link_reload").trigger("click");';
} ?>
and in your javascript use evel() instead of alert()
Try changing the input type from "submit" to a regular button whose onclick action is to call check_login()
I have a form in that evaluates information in the database on my process page and returns errors if necessary. I'm using Ajax so it shouldnt actually be going to the process page and loading what I have encoded in Json to return. Here is my form plus Javascript:
<form method="post" action="../user/process_login" id="login_form">
<input type="hidden" name="action" value="login">
<label>Email Address:</label>
<input type="text" id="email" name="email" placeholder="Email" />
<label>Password:</label>
<input type="password" id="password1" name="password0" placeholder="Password" />
<input type="submit" id="submitbtn" placeholder="Submit" class="button"/>
</form>
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$('#login_form').submit(function(){
$.post
(
$(this).attr('action'),
$(this).serialize(),
function(data){
if (data['errors'] == '') {
consle.log(data);
};
else{
console.log(data);
$('#alert_box').html(data);
};
},
"json"
);
return false;
});
});
</script>
Here is the relevant section of my validation code:
if (count($user) > 0 AND $decrypted_password == $this->input->post('password0'))
{
$this->session->set_userdata('user_session', $user);
$this->load->view('main.php');
}
else
{
$errors = "<div class='alert-box alert' id='error-box'><p>Your login information did not match our reccords. Try again</p></div>";
echo json_encode($errors);
}
I think it's because there is an error in your code. I point it out below
Here is without the error ----> WITHOUT ERRORS
Here is with the Error -----> WITH ERRORS
As you can see the return false does work without errors.
<script type="text/javascript">
$(document).ready(function(){
$('#login_form').submit(function(){
$.post
(
$(this).attr('action'),
$(this).serialize(),
function(data){
if (data['errors'] == '') {
consle.log(data);
}; <----------------------- Error Not supposed to be there
else{
console.log(data);
$('#alert_box').html(data);
}; <----------------------- I think will still work but don't need
},
"json"
);
return false;
});
});
</script>
You can't use input type submit, while calling an Ajax function, if you use it, your code will not work as expected, so change it to:
<input type="button" id="submitbtn" placeholder="Submit" class="button"/>
I'm trying to send post variables to php himself document via jQuery ajax, but after send, the post vars are not set.
the code:
if(isset($_POST['email']) && isset($_POST['pass'])){
do something
}
<form id="form_login_pv">
Email: <input type="text" name="email" id="email"><br>
Password: <input type="password" name="pass" id="pass">
<div class="send_login_button_pv">Login</div>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e){
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
});
</script>
why dont you try to use form submit jquery function.
if(isset($_POST['email']) && isset($_POST['pass']))
{
//do something
}
<form id="form_login_pv" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Email: <input type="text" name="email" id="email">
Password: <input type="password" name="pass" id="pass">
<button type="submit" class="send_login_button_pv">Login</button>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e)
{
e.preventDefault(); // just to make sure it wont perform other action
$("#form_login_pv").submit(function(){
//afte server response code goes here
});
});
</script>
Make sure form must have action set.
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
Try this in jQuery ready event:
//you can also use an <input type="submit" value="login" /> instead ofusing a button!
$("#button_id").on("click",function(e){
$("#form_login_pv").submit();
return e.preventDefault();
});
$("#form_login_pv").submit(function(e) {
var email = $('input[name=email]').val();
var pass = $('input[name=pass]').val();
// validate given values here
// if bad value detected, output error and return false;
if(!email.test(YOUR REGEX HERE)) {
$('#error-message').text('Wrong E-Mail Format!');
return false;
}
if(pass.length<6) {
$('#error-message').text('Password to short! At least 6 Characters!');
return false;
}
$.ajax({
type: "POST",
url: "index.php",
data: {
email: email,
pass: pass,
},
success: function(response){
alert("mensaje enviado");
}
});
return e.preventDefault();
});
And don't forget to pervent the form from submitting via HTTP Post!
You can do this by returning false at the end of your button click event.
Or by using a method of your event object e, e.preventDefault();
I suggest to return e.preventDefault(); at the end of your click function!
You also can check if given variables are empty or validate them with javascript, before submitting via ajax!