Insert an paragraph with jQuery in an PHP 'If' statement - javascript

I've written a simple login script that connects to a db, and now I want to insert a paragraph with jQuery in my #loginbox which says 'Login failed' when
if (!$row = mysqli_fetch_assoc($result))
is true.
My thought was:
[function.js]
function loginfailed() {
$('#loginbox').html("<p>Login failed.</p>");
}
[login.php]
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<?php
include '../config.php';
include 'dbh.php';
session_start();
$uid = $_POST['uid'];
$pw = $_POST['pw'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pw='$pw'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php');
echo '<script> loginfailed(); </script>';
}
else
{
header('Location: ../index.php');
}
?>
But it doesn't work.

DON'T EVER STORE PASSWORDS IN PLAIN TEXT!!
Regarding your question.
The header function redirects to index.php and does not execute the echo. One solution can be to add a $_GET parameter and after the redirect check if it exists and echo the message or append it with JS.
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php?status=fail');
}
In the index.php file at the bottom (if you want to use JS/jQuery to show message)
<script>
var status = "<?php echo (!empty($_GET['status']) && $_GET['status'] === 'fail') ? 0 : 1; ?>";
if(!status) loginfailed();
</script>

Thanks guys, but i've found my own solution with the help of Allkin.
My header now redirects to
header('Location: ../index.php?status=fail');
and my #loginbox checks if status is set and then executes my loginfailed() function.
if(isset($_GET['status'])) {
echo '<script> loginfailed(); </script>';
}
Nothing easy like that!
Thanks for your help everyone.

Related

PHP doesn't output error from mysql query for non-existent rows for autocomplete

I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.

make changes in main page after login with php

I have already made registration and login pages for my web page. The question is that I want to display the name and the image of the user after login, in other words, I want to make some changes in my main page after login.
So this is my code:
lib.php
function checkUser($username,$password){
include "connection.php";
$result = mysqli_query($conn, "SELECT * FROM `data` WHERE `username` = '$username' AND `password` = '$password'") or die("No result".mysqli_error());
$row = mysqli_fetch_array($result);
$logic = false;
if (($row['username'] == $username) && ($row['password'] == $password)) {
echo "Login is successfull. Welcome <b>".$row['username']."</b>";
$logic = true;
}
else{
echo "Failed to login. Username or password is incorrect. Try again.";
}
return $logic;
}
function logIn($username, $password){
include ("connection.php");
$_SESSION["loggedInUser"] = $username;
$_SESSION["loggedInTime"] = time();
}
action.php
<?php
include "lib.php";
if(checkUser($username,$password)){
logIn($username, $password);
header("Location: index_en.php");//goes to my main page
?>
<li>Hello, <?php echo $username; ?></li>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
console.log("successfull");
$(".nav_header").remove();//I tried to change my index_en.php page, but no changes appear there
</script>
<?php
}
?>
As I understood the question, so I think your code might be like this,
action.php
<?php
include "lib.php";
if(checkUser($username,$password)){
logIn($username, $password);
header("Location: index_en.php");//goes to my main page
?>
<li>Hello, <?php echo $username; ?></li>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
console.log("successfull");
$(".nav_header").remove();//I tried to change my index_en.php page, but no changes appear there
</script>
<?php
}
?>
As, you want some change in Index_en.php(Home Page) when user is already logged in, your page should contain,
index_en.php
<?php
session_start();
if(isset($_SESSION['username'])){
echo "Hello, ".$_SESSION['username'];
}
?>

append PHP code to HTML input placeholder?

I want to append a PHP function that shows the user his/her IP within an inputs' placeholder. I've never seen anything like this been done before so I'd like to just see if it's possible or not.
My thoughts right now is to do something along these lines:
$('input').attr(placeholder,function(){
$('input').append('<?php $variable ?>');
});
then run the PHP code through here some how. If someone can shed some light on this I would be very grateful!
try this:
$('#inputID').attr("placeholder","<?php echo $variable; ?>");
And if you want to append to all inputs:
$(":input").attr("placeholder","<?php echo $variable; ?>");
should do the work
If you want to do it in PHP you can make a function to retrieve the IP of the user then echo the script in your page:
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
echo "<script type='text/javascript'>
$('input').attr(placeholder,function(){
$('input').append('".getUserIP()."');
});
</script>";
?>

Alert box in PHP - Making me crazy

I know this question is very common, I have search alot, and after alot of hard work, I am asking here.
I simply want to show an alert box and redirect it to a page.
The code below is redirecting me, but not showing me the alert box.
Please, let me know my mistake.
<?php
require_once('connection.php');
if(isset($_POST['person'])){ $name = $_POST['person']; }
if(isset($_POST['pwd'])){ $password = $_POST['pwd']; }
if(isset($_POST['position'])){ $pos = $_POST['position']; }
if(empty($name) or empty($password))
{
echo "<SCRIPT type='text/javascript'>
alert('Places should not be empty! Press Ok and try again!');
window.location.replace(\"addmember.php\");
</SCRIPT>";
}
else
{
//$query=mysqli_query($con,"insert into members (username, password,position) values ('$name','$password','$pos')");
echo "<SCRIPT type='text/javascript'>
alert('Added!');
window.location.replace(\"addmember.php\");
</SCRIPT>";
}
?>
I personally make this function to show an alert box and redirect it to a page.
function do_alert($msg,$link=NULL)
{
echo '<script type="text/javascript">
alert("' . $msg . '");
</script>';
if(!empty($link)) {
echo '<script type="text/javascript">
window.location="'.$link.'";
</script>';
}
}
Use this function both alert and redirect to a page use this
do_alert("Message","URL");
do_alert("Here this is your alert","addmember.php");
do_alert("Only your alert");
If the function 2nd parameter URL is empty then it'll only do alert.
try to change
window.location.replace(\"addmember.php\");
to
window.location='addmember.php';

Embedding Javascript inside PHP doesn't work

My problem is very similar to javascript inside php code
I am trying to embed Javascript code inside PHP. But Javascript code doesn't seem to work. My sample code is as below. I am trying to run is on my local XAMPP server. If i remove Java script code, rest of PHP code works perfectly fine.
<?php
session_start();
include('connection.php');
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$emailID=$_POST['emailID'];
$pwd=$_POST['pwd'];
$phone=$_POST['phone'];
$query = mysql_query("SELECT * FROM user_info WHERE uname = '$emailID' AND pwd = '$pwd'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
mysql_query("INSERT INTO user_info(fname, lname, uname, pwd, phone)VALUES('$fname', '$lname', '$emailID', '$pwd', '$phone')") or die(mysql_error());
?>
<script type="text/javascript" >
window.parent.modalWin.CallCallingWindowFunction(0, 'User registration successful');
</script>
<?php
mysql_close($con);
}
else
{
?>
<script type="text/javascript">
alert("E-mail is already registered");
</script>
<?php
header("location: registration.html");
}
?>
Try directly in you php like this
<?php
echo '<script type="text/javascript">alert("Data alert");</script>';
?>

Categories