Login form with ajax does not work - javascript

I have 3 files:
1. Simple form with email and password
2. login_validate.php to validate form input against database
3. login.js to perform ajax task
I tried to validate form with just login_validate.php and everything worked for me. But when i tried to use ajax(login.js), it always tells me wrong email and password even I tried to type in correct email and password in form. Below is my code, please advice what is wrong with it?
Here is my form:
<div id="login_result"></div>
<form action="login_validate.php" method="post">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<input type="password" class="form-control" id="pass" name="pass" placeholder="Password">
<button type="submit" class="btn btn-default" name="submit" id="submit">Submit</button>
</form>
Here is my login_validate.php:
<?php
require("configs/dbconnect.php");
if(isset($_POST["dangnhap"])){
$email=mysql_real_escape_string($_POST["email"]);
$pass=mysql_real_escape_string($_POST["pass"]);
$sql = 'SELECT name, email, pass, visible FROM user WHERE email = "'.$email.'" AND pass = "'.$pass.'"';
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
$num_rows= mysql_num_rows($result); // Get the number of rows
if($num_rows > 0){
$row = mysql_fetch_array($result);
echo 1;
$_SESSION["email"]=$row["email"];
$_SESSION["pass"]=$row["pass"];
$_SESSION["name"]=$row["name"];
}
else{
echo 0;
}
}
?>
Here is my login.js:
$(document).ready(function(){
$('#email').focus(); // Focus to the username field on body loads
$('#submit').click(function(){ // Create `click` event function for login
var email = $('#email'); // Get the username field
var pass = $('#pass'); // Get the password field
var login_result = $('#login_result'); // Get the login result div
login_result.html('loading..'); // Set the pre-loader can be an animation
if(email.val() == ''){ // Check the username values is empty or not
email.focus(); // focus to the filed
login_result.html('<span class="error">Enter the username</span>');
return false;
}
if(pass.val() == ''){ // Check the password values is empty or not
pass.focus();
login_result.html('<span class="error">Enter the password</span>');
return false;
}
if(email.val() != '' && pass.val() != ''){ // Check the username and password values is not empty and make the ajax request
var UrlToPass = 'email='+email.val()+'&pass='+pass.val();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type : 'POST',
cache: false,
data : UrlToPass,
url : 'login_validate.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
login_result.html('<span class="error">Username or Password Incorrect!</span>');
}
else if(responseText == 1){
window.location = 'member/';
}
else{
alert('Problem with sql query');
}
}
});
}
return false;
});
});

No need to test the dangnhap.
in PHP remove the check:
isset($_POST["dangnhap"]) //remove it, no checking for submit required. done in JS file.
Change in JS:
var UrlToPass = {email:email.val(),pass:pass.val()} ;
in HTML:
remove the type( type="submit" ) attribute as you are using <button>

in login_validate.php
if(isset($_POST["dangnhap"])){
but in login.js dangnhap is not set.
in $.ajax({ data can be an object, you dont have to make it a string

Related

back-end error_msg is not giving a alert..!

I am using jquery to make a .php file execute but my major problem is when ever a error is thrown from back-end i used a alert to display that error_msg..but ever i submit with a error intentionally...its just moving on to page specified in action...no error alert poped up...plz help me out of this.!!pardon me if am wrong
here gose the DB_Function.php
<?php
class DB_Functions {
private $db;
// constructor for database connection
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
die('Error in database requirments:' . $e->getMessage());
}
}
/**
* Storing new user
* returns user details of user
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
/*to check if user is
already registered*/
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
}
/*to check if user
exist's by mobile number*/
public function isMobileNumberExisted($mobile){
try{
$sql = "SELECT mobile FROM users WHERE mobile = '$mobile' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch(Exception $e){
die('Error accessing database: ' . $e->getMessage());
}
}
//DB_Functions.php under construction
//more functions to be added
}
?>
here gose the .php file to be clear on what am doing..!!
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate your password
if(strlen($password) > 6){
//validate your mobile
if(strlen($mobile) == 12){
//Check for valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}
} else {
$response["error"] = true;
$response["error_msg"] = "Mobile number is invalid!";
echo json_encode($response);
}
} else {
//min of 6-charecters
$response["error"] = true;
$response["error_msg"] = "password must be of atleast 6-characters!";
echo json_encode($response);
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
and here gose the main file .js
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
e.preventDefault();
}
});
});
});
and here gose the corresponding .html file
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjh8AG"></div>
<!-- End Thumbnail-->
</div>
<?php include("js/captcha.php");?>
</div>
<div class="form-group">
<div cle the terms and policy </label></div>
</div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
<
/form>
From the comments:
So only after displaying Registeration successful! I want to submit the form and redirect it to login.html
Well the solution is quite simple and involved adding and setting async parameter to false in .ajax(). Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
Your jQuery should be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
So the form will only get submitted if the registration is successful, otherwise not.
Edited:
First of all make sure that <!DOCTYPE html> is there on the top of your page, it stands for html5 and html5 supports required attribute.
Now comes to your front-end validation thing. The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method.
For the purpose of simplicity I removed your terms and conditions checkbox and Google ReCaptcha. You can incorporate those later in your code.
So here's your HTML code snippet:
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required />
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required />
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required />
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required />
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required />
</div>
<!--Your checkbox goes here-->
<!--Your Google ReCaptcha-->
<input type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b" value="Register" />
</form>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
And your jQuery would be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
your form submit takes action before ajax action so its reloading the page and use form submit instead of submit button click
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
Ok steps to be sure that everthing works fine while you try to use ajax
1st : use form submit and use e.preventDefault(); to prevent page reloading
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
alert('Form submited');
});
if the alert popup and form not reloading the page then the next step using ajax
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
$.ajax({
url: "register.php",
type: "POST",
dataType: "JSON",
data: {success : 'success'},
success : function(data){
alert(data);
}
});
});
and in php (register.php)
<?php
echo $_POST['success'];
?>
this code should alert with "success" alert box .. if this step is good so now your ajax and php file is connected successfully then pass variables and do another stuff

Username and Password validation to list

I am very new to web development and am attempting to write code to validate username and password combinations. http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php is the link to run the check, and http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/list.php is the list of acceptable entries. I am able to hard code in a username and password and that seems to be working fine, my question is simply "How can I hook up this input, to check inside the server for an acceptable login." Thank you for your help in advance!
Here is my form:
<form id = "formLogin" method = "post" name = "myform">
<label>User Name: </label>
<input type = "text" name = "username" id = "username" />
<label>Password: </label>
<input type = "password" name = "password" id = "password">
<input type = "button" value = "Login" id = "submit" onclick = "validate()">
<input type = "reset" value = "Reset">
</form>
Here is my javascript thus far:
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(username == ""){
alert("Please enter a User Name")
formLogin.username.focus()
return false
}
if(password == ""){
alert("Please enter a Password")
formLogin.password.focus()
return false
}
if( username == "Test" && password == "test#123"){
alert("Login successfully");
window.location = "gameboard.html";
return false;
}
else{
alert("Login failed - Please enter correct Username and Password")
}
}
Try looking into jQuery's AJAX function. Upon submission of the login form, send the username and password combo to http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php as follows.
<form id="formLogin" method="post" name="myform">
<label>User Name:</label>
<input type="text" name="username" id="username">
<label>Password:</label>
<input type="password" name="password" id="password">
<input type="submit" value="Login" id="submit">
<input type="reset" value="Reset">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('#formLogin').submit(function(e) {
e.preventDefault();
var username = $('input#username').val();
var password = $('input#password').val();
if(password == ""){
alert("Please enter a Password");
$('#password').focus();
return false;
}
if(username == ""){
alert("Please enter a Username");
$('#username').focus();
return false;
}
if(username != '' && password != '') {
$.ajax({
url: 'http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php',
type: 'POST',
data: {
username: username,
password: password
},
success: function(data) {
console.log(data);
// It looks like the page that handles the form returns JSON
// Parse the JSON
var obj = JSON.parse(data);
if(obj.result != 'invalid') {
alert("Login succeeded");
// You should redirect the user too
window.location = 'http://redirecturl.com';
}
}
});
}
});
</script>
This effectively validates your form submission. I prefer using the jQuery library as opposed to raw JS. You should look into it too.
It's also worth noting that forms must ALWAYS be validated on the server side as well. Because a client could always just disable JavaScript in their browser to bypass your front end validation. As mentioned by someone who commented on your question, your method of backend validation is pretty insecure. Raw values of passwords should never be stored. Rather, it's good to use an sha1 hash of the password so that if an unwanted user somehow hacks into your DB he/she doesn't have all of the passwords stored in there.
Also, username/password combination validation works a lot smoother on the backend if you just do something like
// Connect to the DB
$con = mysqli_connect('localhost', 'user', 'pass', 'db');
// Escape the form values or user prepared statements
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$sql = "SELECT * FROM users WHERE username = '".$username." AND password = '".$password."'";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
if($count == 1) {
echo "Success";
} else {
echo "Fail";
}
instead of using a static list.
You have two options here -
You can use a server side language like ASP.Net / PHP and you can add an action attribute to your form,
This will then submit to the validate.php passing in any controls with a name tag to the validate.php page.
<form name='something' method='POST' action='validate.php'>
<label>User Name: </label>
<input type = "text" name = "username" id = "username" />
<label>Password: </label>
<input type = "password" name = "password" id = "password">
<input type = "submit" value = "Login" id = "submit"">
<input type = "reset" value = "Reset">
</form>
I would suggest you learn a server side language for this, I'm not going to post the code, I will leave that to you to learn.
OR
You can use JQuery (Don't have too, but it's easier in my opinion) to call an AJAX request to the server to validate.
http://api.jquery.com/jquery.ajax/
Good examples on how to use JQuery and AJAX to call some server side code.
Checking pass in js doesnt make sense, because user can see js code. Use PHP and AJAX.

Pop up form does not send email

I have problem with pop up form . It doesn't send email. Here is html form:
<form action="#" method="post" id="form" >
<img src="images/3.png" id="close"/>
<h2>Contact Us</h2><hr/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<textarea name="message" placeholder="Message" id="msg"></textarea>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
JS to pop up html form:
function check_empty(){
if(document.getElementById('name').value == ""
|| document.getElementById('email').value == ""
||document.getElementById('msg').value == "" ){
alert ("Fill All Fields !");
}
else {
document.getElementById('form').submit();
alert ("Form submitted successfully...");
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}
And php function to send form data to email. Everything work but i don't receive email on gmail. Similar php script i used to post email without pop up and it worked.
<?php
if(isset($_POST['submit'])){
$to = "myemail#gmail.com";
$from = $_POST['email'];
$first_name = $_POST['name'];
$message = $first_name . " wrote following:" . "\n\n" . $_POST['message'];
mail($to,$from,$message);
}
?>
Simple: You don't have an element named "submit" in your form, so your if() test always fails.
id != name in HTML forms; meaning, id does not equal name.
A simple work around:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted ...
}
But this code is bad in any case. You should NEVER use only client-side validation. It's too easy to bypass. ALWAYS validate/verify on the server as well.
You should set your action in the form to the URL of your action in the server.

Check Username Availability via Jquery

I have a code in place to access my database and to check if a username is taken or not. However no matter what i always end up getting a result "Minimum amount of chars is 3 " even when u enter a username that is more than 3 characters long regardless of if it exists in the database or not. What am i doing wrong
This is the html:
<p><input type="text" class="span2" maxlength = "20" name="username" required id="username" placeholder="Username" pattern = "[A-Za-z][0-9]" title = "Ex: John123">
<input type='button' class="btn btn-success btn-mini" id='check_username_availability' value='Check Availability'></p>
<div id='username_availability_result'></div>
This is the php file:
<?php
mysql_connect('localhost', 'root', '*****');
mysql_select_db('testing');
//get the username
$username = mysql_real_escape_string($_POST['username']);
//mysql query to select field username if it's equal to the username that we check '
$result = mysql_query('select username from users where username = "'. $username .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
Finally here is the JQuery:
<script>
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("unamecheck.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not Available');
}
});
}
</script>
You can follow these steps and your problem should be solved :
alert($('#username').val().length) ; it should not be undefined
if you are entering more than 3 char in textbox, then it will show the result, that is how you have written your code.
Use prepared statement while querying the db.
hope it help...!

Kendo UI login functionality

I am currently making a iPhone application using Kendo UI which i am running through phone gap to test on my iPhone.
The design is all mapped out nicely and I am getting to grips with the Kendo framework. I am trying to make some functionality whereby they log into an account.
My external PHP file which runs the query and returns JSON:
<?php
$arr = array();
//Takes the username and password from the login form and queries the database to find out if they have access to the site.
//Cleanse inputs
$username = $_GET['username'];
$password = md5_base64($_GET['password']);
$stmt = $memberMysqli->prepare("SELECT id, firstname, dob, sex, recordingWeight, blocked, enabled FROM member WHERE email = ? AND password = ?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($memberid, $firstname, $dob, $sex, $recordingWeight, $blocked, $enabled);
$stmt->store_result();
session_start();
while ($stmt->fetch())
{
$userIsBlocked = $blocked;
$enabled = $enabled;
}
if(($numRows = $stmt->num_rows) > 0) //If num rows is 1 the combination exists therefore it is a succesful login
{
if($userIsBlocked)
{
$arr['status'] = "error";
$arr['message'] = "Sorry, your account isnt active. Please contact us to re-activate it.";
}
else if(!$enabled)
{
$arr['status'] = "error";
$arr['message'] = "Sorry, your account isn't enabled. Please contact us.";
}
else
{
$_SESSION['memberid'] = $memberid;
$_SESSION['memberFirstname'] = $firstname;
$_SESSION['dob'] = $dob;
$_SESSION['sex'] = $sex;
$_SESSION['recordingWeight'] = $recordingWeight;
$arr['status'] = "success";
$arr['message'] = "Logged in";
}
}
else
{
$arr['status'] = "error";
$arr['message'] = "Sorry, Wrong Username/Password Combination";
}
header("Content-type: application/json");
echo json_encode($arr);
/* close connection */
function md5_base64 ( $data )
{
return preg_replace('/=+$/','',base64_encode(md5($data,true)));
}
?>
So this returns success, logged in or sorry wrong username/password combination..
Here is my form code:
<form>
<fieldset>
<p><label style="color:white;" for="email">E-mail address</label></p>
<p><input type="email" id="email" value=""></p>
<p><label style="color:white; font" for="password">Password</label></p>
<p><input type="password" id="password" value=""></p>
<p><input type="submit" value="Sign In"></p>
</fieldset>
and the JS:
<script>
$("form").on("submit", function() {
var username = document.getElementById('email').value;
var password = document.getElementById('password').value;
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: 'http://myurl.co.uk/appqueries/login.php?username='+username+'&password='+password,
dataType: "json"
}
}
});
//alert("Your username is "+username+" and your password is: "+password);
});
</script>
Can anybody help me getting what the JSON that the PHP file returns and then letting the user into the app if login is successful, or displaying a message if they were not.
I don't think you want a DataSource for this (it could be done, but the DataSource expects an array of objects from the read operation), unless there are additional requirements.
If this is your HTML:
<input id='username' type='text' value='user'></input>
<input id='password' type='text' value='password'></input>
<button id='loginbutton'>Login</button>
<div id='loginresult'></div>
Then you can use jQuery (which I assume you're using since it's a requirement for Kendo UI):
function loginClick() {
var username = $("#username").val();
var password = $("#password").val();
var loginUrl = 'http://myurl.co.uk/appqueries/login.php?username='+username+'&password='+password;
$.ajax({
url: loginUrl,
type: 'GET',
dataType: 'json',
success: function (data) {
handleLoginResult(data);
}
});
}
$(document).on("click", "#loginbutton", loginClick);
function handleLoginResult(data) {
var status = data.status;
var message = data.message;
if (status === "success") {
// do whatever needs to be done after successful login
$("#loginresult").html(message);
}
}
See a working example here (there are a few differences because this is using jsfiddle's echo api): http://jsfiddle.net/lhoeppner/9TGJd/
This works almost the same for Kendo Mobile, except you'd use the mobile button and the data-click binding:
<a id="loginbutton" data-role="button" data-click="loginClick">Login!</a>
You should not use form submit in Kendo Mobile application as a Kendo mobile application is basically a Single Page Application. What you need to do is to have a Kendo button and on the click event handler, fire the JSON call. You can see the demo of Kendo Button click event here: http://demos.kendoui.com/mobile/button/events.html#/

Categories

Resources