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.
Related
I've got a table of data with clickable rows which will lead to another page based on the row that was selected. To get the row, I am using a form and post the form to another page to pass the variable to php. Now, the problem is once I refresh the page my info is gone...
How can I avoid that?
<?php
$id = $_SESSION["uid"];
$sql = "select * from std_cources join courses where std_cources.std_id = '$id' and courses.course_id = std_cources.course_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '
<div class="col-md-4">
<span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x text-primary"></i>
<i class="fa fa-shopping-cart fa-stack-1x fa-inverse"></i>
</span>
</br>
<p style="color:white;">'.$row["course_name"].'</p>
Check forthe exams
<form name="myform" id="'. $row["course_id"].'" action="checkMarks.php" method="post">
<input type= "text" value ="'. $row["course_id"].' " name="test" style="visibility: hidden;"></input>
</form>
</br>
</div>';
}
}
?>
<script >
function functionTest(form_id) {
document.getElementById(form_id).submit();
}
</script>
I am retrieving names of few courses from database and put them in a table. Then I can click on each one of them and the form submission will be triggered and sends info to the next page and in the next page I get the given info and retrieve info from database again. However, on the second page, if I refresh the page I get
When you refresh a page that has received data from an earlier POST request, the refreshed page won't have that data unless another POST request is made. This can be done in the window object's DOMContentLoaded or load event.
Or, you can make the initial request for the data via a GET request. This will send whatever data you are sending to the server as part of your request as a query string appended to the URL. If you refresh the page, that query string will persist. This will only work if the data you are attempting to get comes from the server-side processing of the current page and not some other URL entirely.
Lastly, POST requests are for requests that change the state of the server (insert, update and delete type of operations). GET should be used for read operations.
Without your code, there's really not much more to offer.
EDIT:
Now that you have posted your code, I would suggest spending some time and cleaning up the HTML string that is sent back from your .php file. There is no such tag as </input> and you should remove the inline HTML event attributes (onclick, etc.). Here's why. Don't use javascript:... either (for many of the same reasons as in the link.
Lastly, I would suggest you change this from a form submission to an AJAX GET request, which will allow you to stay on the same page and keep the currently loaded data.
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.
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.
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.
I've been working on a web app that allows users to submit content and have that content, and today I've been seeing some unexpected results without making any significant changes.
The basic functionality of the app is that the user submits some POST data from a form on a web page index.php, whereupon a PHP script submit.php is run to add the data to a table in a database. Meanwhile, a Jquery function on index.php is refreshing the contents of a div with rows selected from the table by means of a script load.php, and the function is called once per second.
The problem is that today, suddenly, I'm seeing long (10-20 minute) delays between when the data is added to the table and when it shows up in the Jquery-refreshed div. Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
I've checked the MySQL database before and after submit.php is called and I've verified that the data is being added instantaneously once it's submitted, so the problem has something to do with how the load.php script is called from Jquery.
This just started today. Strangely, I've been seeing this same behavior with another AJAX app that I built earlier to test the same I/O mechanism, and I haven't touched that app's code in over a week. My system administrator says there haven't been any changes to the server that would account for this.
I've posted all the code to provide all necessary information, but I think the problem is either in load.php or the javascript updateMyContent() in index.php.
index.php
<script language="JavaScript">
setInterval("updateMyContent();",1000);
$(function(){
updateMyContent=function(){
$('#refreshData').load("./module/load.php").fadeIn("slow");
}
});
</script>
<script language="JavaScript">
$(document).ready(function(){
$('#submitForm').on('submit',function(e){
$.ajax({
url:'./module/submit.php',
data:$('#submitForm').serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
$('#textID').val('');
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
<div style="float: right;
top: 0;
" id="submitDiv">
<form id="submitForm" action="" method="post">
<textarea id="textID" type="text" name="content" rows=5></textarea>
<input type="submit" value="send" name="submit"/>
</form>
<br>
<span id="error" style="display: none; color:#F00">error</span>
<span id="success" style="display:none; color:#0C0">success</span>
</div>
<div style="float: center;" id="refreshData"></div>
submit.php
<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$insertSQL="insert into submission (content) values (?)";
$stmt=$db->prepare($insertSQL);
$stmt->execute(array($content));
}
else
{
echo "FAIL!";
}
?>
load.php
<?php
try
{
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$PDOsql="select * from submission order by id desc";
$stmt=$db->query($PDOsql);
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $resultRow)
{
printf("%s<br>",$resultRow["ID"]);
printf("%s<br>",htmlspecialchars($resultRow["content"]));
$stmt->closeCursor();
}
}
catch(PDOException $ex)
{
echo "an error occurred! ".$ex->getMessage();
}
?>
The issue with it taking so long to return the Ajax response is probably that the table submissions has grown. Rather than each second loading all the submissions, append only new submissions to the div. I.e. keep track of the last id received and use this in the query so the where clause is limited.
Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
Ajax response can be cached by the browser just like anything else. To prevent that, you can:
Put no-cache headers in the page that processes the request to prevent browser caching of the Ajax responses. IE is particularly stubborn and will require the most forceful headers.
Add a parameter to your Ajax request that is a random number, to make every request unique.
Tell JQuery to prevent caching (it just does #2 for you). Use $.ajaxSetup ({ cache: false }); or add the cache: false, attribute to each call to $.ajax