Trying to make php login work with Phonegap - javascript

I understand that for a login / register system to work within Phonegap, you have to use aJax with your php. I've got a sucessful php login and register page working but I'm unsure where to begin with jQuery / aJax a.k.a where I'm meant to put it, and what exactly I should be putting in. I was wondering if someone would know how to point me into the right direction.

jQuery
jQuery is a framework built on Javascript. Javascript is a client-side (browser) language . It runs on your device, unlike PHP that gets executed on the server.
You need to include jQuery in the HTML of your login page using script tags:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
jQuery provides a way to target any html element within your document and perform certain functions on that element. You specify what element by using the following syntax:
$(element).doSomething();
You can select classes or IDs:
<p id="myparagraph">A paragraph of text</p>
<p class="myparagraphclass">A paragraph of text</p>
$('#myparagraph').doSomething();
$('.myparagraphclass').doSomething();
AJAX
AJAX is a method introduced with Javascript that allows a page to request another url along with the result of that request. You will need to use AJAX login with Cordova/Phonegap because the "app" you're building is based on Javascript.
Thankfully, jQuery provides some really nice and easy to use AJAX methods.
Putting it together
I notice from a previous question that you have already created a PHP script that checks the login credentials are correct. Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /public_html/access/login.php on line 15
I have edited slightly the code within that question (/access/login.php):
require_once($_SERVER['DOCUMENT_ROOT'] . "/html5up-aerial/access/functions.php");
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username&&$password) {
session_start();
require_once($_SERVER['DOCUMENT ROOT'] . "db_connect.php");
mysqli_select_db($db_server, $db_database) or
die("Couldn't find db");
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query);
*if($row = mysqli_fetch_array($result)){*
$db_username = $row['username'];
$db_password = $row['password'];
if($username==$db_username&&salt($password)==$db_password){
$_SESSION['username']=$username;
$_SESSION['logged']="logged";
//header('Location: home.php'); // Have commented this out
$message = "YOU ARE NOW LOGGED IN!"; // <- ADDED THIS
}else{
$message = "<h1>Incorrect password!</h1>";
}
}else{
$message = "<h1>That user does not exist!</h1>" .
"Please <a href='index.php'>try again</a>";
}
mysqli_free_result($result);
require_once("db_close.php");
}else{
$message = "<h1>Please enter a valid username/password</h1>";
}
//header/footer only required if submitting to a seperate page
echo $message; // ADDED THIS
die(); // ADDED THIS
This will be the PHP script that AJAX requests.
Now we create the HTML document with a login form and include jQuery and write our ajax code:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<form class="login-form" method="post">
Username: <input name="username" /><br />
Password: <input name="password" type="password" /><br />
<input type="submit" value="Login" />
</form>
<script>
$('.login-form').on('submit', function(e) { // Listen for submit
e.preventDefault(); // Don't actually submit the form
var data = $(this); // Put the form in a variable
$.ajax({
type: "POST",
url: '/access/login.php',
data: $(data).serialize(), // Make form data into correct format
success: function(response) {
alert(response); // Alert with the response from /access/login.php
}
});
});
</script>
To debug this code you will need to use Chrome development toolbar or Firefox Firebug. Hope this helps.

Related

Redirecting to another page when login is valid, otherwise stay on the same page [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 years ago.
I'm fairly new with PHP programming and still getting myself familiar with the methods and syntax. Right now, I have no knowledge of session yet.
I want the user to get a message that the "user doesn't exist or incorrect login details" if he/she types incorrect login details on the form. Otherwise, redirect user to the next page.
I tried using the header() method of PHP but when I put it after the alert() message line, my alert() message doesn't even show.
nextpage.php
<?php
if(isset($_POST['btnLogin'])){
$con = mysqli_connect("localhost","root","","myDb")or die("cannot connect");
if(!$con){
die("Connection failed: " . mysqli_connect_errno() );
}
$studentNo = $_POST['studentNo'];
$username = $_POST['userName'];
$password = $_POST['password'];
$selectQuery = "SELECT * FROM registered WHERE student_no = '$studentNo' AND username = '$username' AND password = '$password' ";
$result = mysqli_query($con,$selectQuery);
if(mysqli_num_rows($result) == 0){
echo '<script language="javascript">';
echo 'alert("User doesn\'t exist or incorrect login details")';
echo '</script>';
header("Location: login.php"); //take user back to login.php if user doesn't exist
}else{
//do this if user exists
//get Parameters for studentNo, userName, password
}
}
?>
login.php
<form action="nextpage.php" method="POST">
<label>Student No</label>
<input type="text" name="studentNo" placeholder="Student No" required />
<br />
<label>Username</label>
<input type="text" name="userName" placeholder="Username" required />
<br />
<label>Password</label>
<input type="password" name="password" placeholder="Password" required />
<br />
<button type="submit" name="btnLogin">Login</button>
</form>
header() takes user back to login.php but it doesn't display the message.
Is there any other better way to do what I'm trying to do? Validate the login details first before redirecting to page two. Otherwise, don't redirect.
I researched and found that I can post data through <form> or other javascript syntax. I would prefer to learn how to do it with plain php and html
I hope you can help me.
Thank you.
You can display a message on the login page itself by adding a value onto the header itself and having an if statement on your login.php.
For example, change your header to
header("Location: login.php?error=1");
And on your login.php file, add this.
if(isset($_GET['error']) && $_GET['error'] == "1") {
echo '<div class="alert alert-danger">Login failed</div>
}
EDIT: Having seen CD001's comment, i'd recommend reading up on php & mysql on how to better protect yourself from sql injections etc. Here is a good place to start.
First of all, you cannot send a header() when you have already echo'ed output.
Secondly, the alert will never show up, even if redirecting would work, because the <script> is not on login.php. It is not magically stored somewhere to showup later.
Using session you can do like this
In your login.php before html code put this
<?php
session_start();
?>
This will start the session. When user submits the form, in nextpage.php, first you need to put again session_start(); on top of the script, after doing users authentication, you can set session like this
if(mysqli_num_rows($result) == 0){
header("Location: login.php?error=User doesnot exists"); //take user back to login.php if user doesn't exist
}else{
//do this if user exists
//get Parameters for studentNo, userName, password
$_SESSION['user_id'] = '<userId>';
//..
header("Location: <secure_page>");
}
In the secure_page where you've redirected the user, in that php script again on top of the script put session_start(); and after that you can check session
if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] != "") {
header("Location: login.php?error=access denied");
}
This will make sure that un-authenticated users can't access this page.
About the issue of not showing alert
In you're script, where you're using javascript code, there you'll need to add the type.
echo '<script type="text/javascript" language="javascript">';
Another problem with the code is javascript will execute only after you're page is loaded but after echoing all those you're using header("location:login.php"); which will redirect the user without showing javascript alert
Well like others said there are better ways of doing this but if you still want to go with your solution then this will work for you:
echo '<script language="javascript">';
echo 'alert("User doesnt exist or incorrect login details");';
echo 'location.href="http://www.yoursite.com/login.php";';
echo '</script>';
remove the php header redirection.

After redirect, how to display error messages coming from original file?

Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
Any help is certainly appreciated.Thank You
Also it's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
There's multiple ways of doing so. I personally would use AJAX. On a 'form submit', run a javascript function calling an AJAX request to a .php file to check the form information, all using post method. Calculate all the $_POST['variables'] checking for your defined errors. You would have an html element print the errors via AJAX request.
If there are 0 errors then in the request back return a string as so that your javascript function can look for if its ready to go. If ready to go, redirect the user to where ever you please.
AJAX is not hard and I only suggested the idea sense you put javascript in your tags.
Another method:
Having all your code on one .php file. When you submit the form to the same .php file check for the errors (at the top of the file). If $_POST['variables'] exist, which they do after you submit the form, you echo your errors in the needed places. If zero errors then you redirect the page.

Trouble passing variables between PHP and Javascript

I have a simple HTML5 login page that requests a username and a password. The information is passed via POST to PHP for comparison with data in MySQL. I am trying to echo a simple "YES" if data was successfully validated and a "NO" otherwise. I want to take the text value of the response and manipulate it using Javascript. Everything seems to be working properly, but when the $response variable is echoed it is shown by itself on a blank HTML document and the JavaScript never gets executed. Following is the code I am using :
<ul>
<li>
<form action="login_submit.php" id="loginTest" method="post">
<span class="un"><i class="fa fa-user"></i></span><input type="text" id="maindata_email" name="maindata_email" value="" maxlength="40" required class="text" placeholder="Usuario"/></li>
<li>
<span class="un"><i class="fa fa-lock"></i></span><input type="password" id="maindata_password" name="maindata_password" value="" maxlength="10" required class="text" placeholder="Password"/></li>
<li>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>">
<div class="up">
<input type="submit" id ='ingresar' value="ingresar" class="btn">
<!--window.alert(5 + 6);-->
</form>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
var myData = <?php echo json_encode($response); ?>;
window.alert(myData);
if (myData == "YES") {
alert("Usuario aceptado!");
var href = 'http://index2.html';
window.location=href;
} else {
alert("Usuario invalido!");
var href = 'http://index.html';
window.location=href;
}
</script>
<input type="submit" id = 'editar' value="editar" class="btn">
</form>
</div>
</li>
</ul>
And here is the PHP section :
/*** bind the parameters ***/
$stmt->bindParam(':maindata_email', $maindata_email, PDO::PARAM_STR);
$stmt->bindParam(':maindata_password', $maindata_password, PDO::PARAM_STR, 40);
/*** execute the prepared statement ***/
$stmt->execute();
/*** check for a result ***/
$user_id = $stmt->fetchColumn();
/*** if we have no result then fail boat ***/
if ($user_id == false)
{
echo $response = "NO";
}
/*** if we do have a result, all is well ***/
else
{
/*** set the session user_id variable ***/
$_SESSION['user_id'] = $user_id;
/*** tell the user we are logged in ***/
echo $response = "YES";
}
}
catch(Exception $e)
{
/*** if we are here, something has gone wrong with the database ***/
$message = 'No se puede procesar su ingreso. Favor de intentar mas tarde.'."<br />\r\n";
}
}
After I click on ingresar in the HTML the username and password are properly sent and received by PHP, the information is properly processed and compared to the values contained in the MySQL database and I get the proper response upon validation. Could anyone please explain why I get the blank page with the $response and the JavaScript code is never executed??? Thanx
Your code seems to be behaving as expected. Your form, upon submission makes a POST request to the servar at login_submit.php, and the browser displays the response from the server, which is where you've echoed the value of $response. There is no javascript or HTML printed on the PHP page, so no javascript is going to be run, and no HTML is going to be displayed... the browser is merely displaying the raw contents of the POST response from the form action since it's just interpreting it as a text response with no markup.
Now, what you're actually wanting is to get the data from the response on a web-page and run some javascript using that response data. There are a couple ways you could tackle this problem:
Avoid a page reload by using AJAX techniques to asynchronously request data back from the server through login_submit.php. When the data arrives back from the server after some indeterminate period of time, a javascript callback is called on the page which involves an action on the incoming response data.
Your login_submit.php page prints a full HTML page with the javascript embedded on that page, and you populate the variables in the resulting javascript from the PHP code that runs the MySQL query.
Take a page from ASP.NET forms and POST back to the page itself rather than a separate page, and use PHP to detect when a POST-back has taken place. So all the code for the form, MySQL query, etc. exists in the same PHP document, and you POST to the page itself. When the page reloads from the POST, it will populate the necessary javascript variables on the page with the correctly values.

Update innerHTML by an email

I don't know if this is possible so I'm very open to trying other methods to achieve similar results.
Basically I have a website and a certain div
<div id="mainContent">Content here...</div>
What I want to do with this, is be able to send an email to a certain address or something similar and the body of the email will define the "innerHTML" of this div.
I can imagine it would look something like this in Javascript:
document.getElementbyId("mainConetent").innerHTML = emailBody;
With obviously "emailBody" being a pre-defined variable.
I am almost certain nothing like this could work but is there any way to achieve a similar thing?
I also know that 'innerHTML' in javascript becomes restored when a page is refreshed. I would like it to be there permenantly on the original document, until a new email is recieved with the new content. This method with javascript is probably not the way to do is. I just used it to explain bettter
Store email body in input hidden field and then using javascript you can retrieve them based on id and store them in respective div.Try this:
html:
<div id="mainContent">Content here...</div>
<input type="hidden" value="<?php echo $inputbody;?>" id="emailbody">
javascript:
var emailBody = document.getElementbyId("emailbody").value;
document.getElementbyId("mainContent").innerHTML = emailBody;
Updated Example:
<?php
$to = "someone#example.com";
$subject = "Test mail";
$inputbody = "Hello! This is a simple email message."; // insert this into hidden field
$from = "someonelse#example.com";
$headers = "From:" . $from;
?>
In your index.php file add the following piece of code for database connection
<?php
// Create connection
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM table_name Where type='mail'"));
//Inside your mainContent div
<div id="mainContent"><?php echo $result['innerhtml'] ?></div>
?>
In your js file
If your email is being sent on button click perform this
$('#button').on('click',function(){
emailBody = document.getElementbyId("mainConetent").innerHTML;
$.ajax({
type: "POST",
url: "update_mail content.php",
data: "emailBody="+ emailBody,
success: function(){
}
});
})
//Updates the content in the databse table usinganother php file named update_mail content.php .This flow might help u mate.. :)

Upload an image without refreshing page in php

I want to upload an image without refreshing page. please help me for this purpose. I find many thing but ever
Complete Script :
you need ajax to do it and here some code to work for u :
ajaximage.php
Contains PHP code.
This script helps you to upload images into uploads folder.
Image file name rename into timestamp+session_id.extention
<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
index.php
Contains simple PHP and HTML code.
Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
Sample database design for Users.
Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200),
`profile_image_small` varchar(200),
)
Javascript Code
$("#photoimg").on('change',function(){})
// photoimg is the ID name of INPUT FILE tag and
$('#imageform').ajaxForm()
//imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').on('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>
Uploading files to the server without a page refresh requires some additional client-side tools. These tools will then need to communicate with the PHP backend that you have written. Here are some popular solutions which offer what you are looking for:
Uploadify, my favorite of these solutions: http://www.uploadify.com/
SWFUpload, similar to Uploadify: http://swfupload.org/
jQuery Form Plugin, an AJAX-based uploader: http://jquery.malsup.com/form/#file-upload
Hope that helps.
Two good tutorials:
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
http://css-tricks.com/6522-ajax-image-uploading/
You need to use ajax to do that. Ajax will send the request to a PHP script that will do the work without refreshing the entire page.
Submit it via XMLHttpRequest. In a nutshell you would need to initialise a FormData() object and append your file to the object, then initiate an xhr connection, and send your object via xhr xhr.send.
This is all at a very basic level...
Or, better yet, use a pre-existing tool.
Lot of jquery plug ins are available, you can show progress bar too. refer this
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

Categories