loging php page not redirecting - javascript

I'm working on a login page by user level to separate the admin and user. but it didnt seems to work. it doesnt redirect and leave a blank page. I've tried remove the javascript part, but it doesnt change anything either.
index.php
<form class="login" action="login.php" method="post">
Username:<input type="text" name="username" id="username"/>
Password:<input type="password" name="password" id="password"/>
<input type="submit" value="login"/>
</form>
login.php
<?php
session_start();
include('config.php');
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = mysql_query("SELECT * FROM admin WHERE username='$username' AND password='$password'");
$result = mysql_fetch_array($sql);
$username=$result['username'];
$adminID=$result['adminID'];
$userLevel=$result['UserLevel'];
$_SESSION['adminID']=$adminID;
$_SESSION['userLevel']=$userLevel;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
if($userLevel == '1')
{
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script type="text/javascript">
alert("Welcome <?php echo "$username" ?> to Admin page! ");
</script>
<?php
header('Location:admin.php');
exit();
}
elseif($userLevel == '0')
{
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script type="text/javascript">
alert("Welcome <?php echo "$username" ?> to User page! ");
</script>
<?php
header('Location: user.php');
exit();
}
else
{
?>
<script type="text/javascript">
alert("Invalid Username or Password! ");
//window.location.href = "index.php";
</script>
<?php
}
}
?>

Use PHP Header:
for userLevel1:
header("Location: admin.php");
for userLevel2:
header("Location: user.php");
Name in your submit so it will enter your PHP code block:
<input type="submit" name="submit" value="login"/>

try the following code and replace into your code. see whether can work or not. you try on the first if condition first and see on the result. if cannot work tell me what problem you face.
<?php
if($userLevel == '1')
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script>
var a = alert("Welcome <?php echo "$username" ?> to Admin page! ");
if (a === true){
window.location.href="admin.php";
}
else{
window.location.href="admin.php";
}
</script>
<?php
}

Related

An issue when passing a PHP parameter to a JavaScript function

I the following code, I have a form that consists of three fields and two buttons. In the Review button, I would like to show any word in Arabic randomly and let the user show its translation in English by ticking the Show translation button.
<html>
<body>
<script>
function myFun1(var) {
document.getElementById("demo").innerHTML = "The translation in English is " + var;
}
</script>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea name="english" rows="4" cols="70" placeholder="English">English</textarea>
<br>
<textarea name="arabic" rows="4" cols="70" placeholder="Arabic">Arabic</textarea>
<br>
<textarea name="example" rows="4" cols="70" placeholder="Example">Example</textarea>
<br><br>
<input type="submit" name="add" value="Add new">
<input type="submit" name="review" value="Review">
<br>
<p id="demo"></p>
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "vdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['add'])) {
$sql = "INSERT INTO Vocabulary (English, Arabic, Example)
VALUES ('$english', '$arabic', '$example')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['review'])) {
$sql = "SELECT COUNT(ID) as total FROM Vocabulary";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
#echo $row['total'];
$generated = rand(1,$row['total']);
$sql1 = "SELECT * FROM Vocabulary where ID = $generated";
$result1 = $conn->query($sql1);
$row1 = $result1->fetch_assoc();
echo "<br>";
echo $row1['Arabic'];
echo "<br><br>";
$eng = $row1['English'];
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
}
$conn->close();
?>
</body>
</html>
In the code, the following line creates the button and trigger the myFun1() function:
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
The problem is when the button is clicked, nothing happens (the message is not shown at all). Any ideas how to fix it?
Firstly change the argument var to some another argument name as var is a keyword in javascript
<script type="text/javascript">
function myFun(as) {
document.getElementById("demo").innerHTML = "The translation in English is " + as;
}
</script>
Secondly, you have to pass the string value in single or double quotes for that use inverted slash \ and rectify the function name from myFun() to myFun1()
echo '<button onClick = "myFun1(\''.$eng.'\')">Show translation</button>';
Rest your code is perfect.
You have definition of function myFun1(var), but you are calling myFun(). I guess this is the problem why there is nothing after clicking on button.
Add this to the top before
< html > tag
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>

window.location.reload reloads constantly

I didn't find an answer so im asking you guys.
window.location.reload() constantly reloads without a break.
I'm trying to make something that checks if the form has no input in it, and if doesn't I want it to make an alert, it's working but it reloads constantly. Here's my code:
<?php
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
echo '<script language="javascript">';
echo 'alert("First Name is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['subject'] == "") {
echo '<script language="javascript">';
echo 'alert("Subject is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['email_adress'] == "") {
echo '<script language="javascript">';
echo 'alert("Email Adress is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['message2'] == "") {
echo '<script language="javascript">';
echo 'alert("A Message is Mandatory.");';
echo 'window.location.reload("contactus.html");';
exit;
echo '</script>';
exit;
} else {
header("Location: contactus.html");
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
?>
Maybe this can be an inspiration?
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$is_redirect = isset($_SESSION['to']);
if ($is_redirect && !is_mail_valid($_SESSION)) {
$to = $_SESSION['to'];
$subject = $_SESSION['subject'];
$body = $_SESSION['body'];
}
$_SESSION = array();
} else {
if (is_mail_valid($_POST)) {
$to = $_POST['to'];
$subject = $_POST['subject'];
$body = $_POST['body'];
mail($to, $subject, $body);
} else {
$_SESSION = $_POST;
}
header("Location: index.php");
exit;
}
function is_mail_valid($mail) {
global $errors;
global $valid;
$errors = array();
if (trim($mail['to']) == FALSE) { $errors['empty_to'] = TRUE; }
if (trim($mail['subject']) == FALSE) { $errors['empty_subject'] = TRUE; }
if (trim($mail['body']) == FALSE) { $errors['empty_body'] = TRUE; }
$valid = empty($errors);
return $valid;
}
?>
<?php if (!$valid) { ?>
<script type="text/javascript">
<?php if ($errors['empty_to']) {?>
alert('To: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_subject']) {?>
alert('Subject: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_body']) {?>
alert('Body: cannot be empty')
<?php } ?>
</script>
<?php } ?>
<form method="post">
<div>
<label for="to">To</label>
<input id="to" type="email" name="to" value="<?php echo $to;?>" />
</div>
<div>
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" value="<?php echo $subject;?>" />
</div>
<div>
<label for="body">Body</label>
<textarea id="body" name="body"><?php echo $body;?></textarea>
</div>
<div>
<input type="submit" value="Send">
</div>
</form>
Basically you start using session using session_start()
On POST:
If you don't have an error:
send the mail
redirect to the conctactus page.
If you have an error:
save the input in the session
redirect to the contact us page
On GET:
If you have nothing in session or the mail in session is valid, just render the html.
If you have something in session and that data is invalid, render the html, render the alert script, and set the "value" attributes of the input to maintain the user's input values.
Clear the session data.
This solution requires that you change your contactus.html to contactus.php in order to use sessions.
<?php
// to use a session, you must start it
session_start();
// variable to store any error message
$error = null;
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
$error = "First Name is Mandatory.";
} elseif ($_POST['subject'] == "") {
$error = "Subject is Mandatory.";
} elseif ($_POST['email_adress'] == "") {
$error = "Email Adress is Mandatory.";
} elseif ($_POST['message2'] == "") {
$error = "A Message is Mandatory.";
}
if ($error) {
// store the error in a session so that you can use it on another page
$_SESSION['error'] = $error;
} else {
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
// regardless of whether there is an error or not, it always goes to Contact Us page
header("Location: contactus.php");
exit;
?>
Then in your contactus.php, you would have
<?php
// resume session again
session_start();
?>
<!-- somewhere in your HTML code -->
<?php if (isset($_SESSION['error'])) : ?>
<div class="error-message"><?php echo $_SESSION['error'] ?></div>
<?php endif ?>
<?php
// you probably will want to remove the error afterwards
unset($_SESSION['error']);
?>
If you can't do that, then this solution will not work and you'll have to resort to AJAX (where you send back your error message via the response you get back from your AJAX response).

Autocomplete dynamic search SQL database from PHP

I have a search box where search is done through database. In the code I have, the search is done in one input box and the dynamic search output is shown in a text area below it.
What I want is a search like Google, where when the user stars typing, it should show similar items from the db table.
For example, if I have two organizations named "Dummy 1" and "Dummy 2" and the user types in "du", the search bar should show the 2 results and user should be able to select one.
The code I have is:
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
The js is like this:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
This is the search.php file:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%$searchq%'")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
//$output = echo "<option value='".$orgname."'>" . $orgname . "</option>";
$output = $orgname;
$output2 = $orgid;
$output3 = $subs;
//$output = '<div>'.$orgname.'</div>';
}
}
}
echo ($output);
?>
How can I achieve that?
In the JS code...
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
you have given the id(#output) of a input type element to display(or to return) the HTML statements and the js script also not closed properly (syntax error).So the valid statement will be...
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
<br>
<div id="mydiv"></div>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#mydiv").html(output);
});
}
</script>
Just change your query :
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
And the query will work fine :)
Then output the response in HTML in your search.php (manage the css accordingly) :
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<div><?php echo $orgname; ?></div>';
<div><?php echo $orgid ; ?></div>';
<div><?php echo $subs ; ?></div>';
<?php
} // while
} // else
} // main if
?>
I hope this is what you required !!

AJAX passing value confusion

I was looking for a way to submit data through a button so that the data will be saved or updated in database, without reloading. Now updating and inserting of data works. But I have used dataString a javaScript variable. I thought through this dataString variable post data are passed. But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
How post method gets the data from my ajax call here.
<html>
<title>Registration</title>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
$dbname = "registration_project";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<div style="width:350px">
<div style="float:left;width:40%">
Id:<br/><br/>
First Name:<br/><br/>
Last Name:<br/><br/>
Age:<br/><br/>
</div>
<div style="float:left;width:60%">
<form action="" method="post">
<input type="number" id="id_id" name="id" value=<?php
if (isset($_POST['id']))
echo $_POST['id'];
?>><br /><br />
<input type="text" id="id_fname" name="fname" value=<?php
if (isset($_POST['fname']))
echo $_POST['fname'];
?>><br /><br />
<input type="text" id="id_lname" name="lname" value=<?php
if (isset($_POST['lname']))
echo $_POST['lname'];
?>><br /><br />
<input type="number" id="id_age" name="age" value=<?php
if (isset($_POST['age']))
echo $_POST['age'];
?>><br /><br />
<input type="submit" id="id_submit" name="submit">
</form>
</div>
</div>
<script src="js/jquery-1.11.3.js"></script>
</body>
</html>
<?php
if (isset($_POST['id']))
echo $_POST['id'] . "<br/><br/>";
if (isset($_POST['fname']))
echo $_POST['fname'] . "<br/><br/>";
if (isset($_POST['lname']))
echo $_POST['lname'] . "<br/><br/>";
if (isset($_POST['age']))
echo $_POST['age'] . "<br/><br/>";
?>
<?php
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "select max(id) from registration";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$id = $row["max(id)"];
}
} else {
echo "0 results";
}
if ($id==$_POST['id']) {
$id = $_POST['id'];
$sql = "update registration set firstName='$fname', lastName='$lname', age=$age where id=$id";
mysqli_query($conn, $sql);
} else {
$id=$_POST['id'];
$sql = "Insert into registration(id,firstName,lastName,age) values($id,'$fname','$lname',$age)";
mysqli_query($conn, $sql);
}
}
mysqli_close($conn);
?>
<script>
$("#id_submit").click(function(e) {
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
</script>
Your click handler doesn't have e.preventDefault() in it. So after the AJAX call is sent, the form is also submitted normally. So even if you don't fill in dataString, the database will be updated from the form.
To make it only use AJAX, you should call e.preventDefault(). You also need to submit a value for the submit parameter, because the PHP code uses if(isset($_POST['submit'])) to know if it should process the form parameters.
$("#id_submit").click(function(e) {
e.preventDefault();
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "submit=submit&id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
In your case, values aren't getting passed. More over, the way you're trying to do ( ?id=...&fname=... etc) would be for passing it with $_GET.
You have to make something similar to :
$.ajax({
type:'POST',
data: { id : $("#id_id").val(),
fname : $("#id_fname").val(),
lname : $("#id_lname").val(),
age : $("#id_age").val()
},
url:'Registration.php',
success:function(data) {
// code
}
});
But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
Answer
When you remove var dataString all the fields having name attribute are automatically submitted along with form

header (location: someurl.php) not working in online server

the header(location: agentverification.php) does not work when uploaded to godaddy server while it works on localhost server. I've try to edit my codes but the result is still the same. if any of you could help me, I'd appreciate it and thanks in advance.
agentlogin.php
<form method = "post" action = "agentverification.php" >
<table>
<input type="text" name="ID" size=20 ><br></td></tr>
<tr>
<td>Password <font color=red>*</font></td>
<td><input type="password" name="pass" size=20><br></td></tr>
</table>
<input type = "hidden" name = "login">
<input type = "submit" name = "login" value = "submit" id="pop">
agentverification.php
<?php
session_start();
$link = mysqli_connect('localhost', 'root', '','db5') or die(mysqli_error());
if(isset($_POST['login']))
{
extract($_REQUEST);
$id = $_POST['ID'];
$pass = $_POST['pass'];
$query= "SELECT * FROM agentReg WHERE AgentID = '$id'";
$record = mysqli_query ($link,$query);
$check=FALSE;
while($row=mysqli_fetch_array($record))
{
if($id === $row['AgentID']&& $pass === $row['password'] )
{
$check=TRUE;
}
}
if($check == TRUE)
{
$_SESSION['AgentID'] = $id;
$_SESSION['password'] = $pass;
header("Location: agentpage.php");
}
else
{ ?> <script>
alert ("Wrong combination of ID and Password. Please try again.");
</script> <?php
session_destroy();
header("location: agentlogin.php");
}
}?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
agentReg database structure
CREATE TABLE agentReg
(AgentID varchar (100) primary key,
password varchar (100));
You cannot use header('Location: ...'); after you've printed an output.
In your last else you should only include session_destroy(); and for instance header('Location: agentlogin.php?error=idpassword');. The error message should be in agentlogin.php.
Use
window.location.href = 'http://www.google.com'; //Will take you to Google.

Categories

Resources