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>';
?>
Related
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.
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'];
}
?>
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.
I'd appreciate some help in getting a simple demo working of the Twitter typeahead.js library as I've struggled with it over the last two days.
I'm using a MAMP development server on my Macbook, and have a (large) MySQL database table that I'd like to query to use with a typeahead field on a Web page.
This is my main HTML file that I'm using. It literally has one field in it.
type-ahead.php
<?php
// HTML5 Header stuff
echo '<!DOCTYPE html>'.PHP_EOL;
echo '<html>'.PHP_EOL;
echo '<head><meta charset="UTF-8">'.PHP_EOL;
echo '<title>Typeahead Example</title>'.PHP_EOL;
// include the two libraries for typeahead to work
echo '<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '</head>'.PHP_EOL;
echo '<body>'.PHP_EOL;
echo '<h2 class="myclass">Typeahead testing</h2>'.PHP_EOL;
echo 'Type in a search: <input type="text" name="user_search">'.PHP_EOL;
echo "<script type='text/javascript'>".PHP_EOL;
echo "$('#user_search').typeahead({".PHP_EOL;
echo " name: 'user_search',".PHP_EOL;
echo " remote: './type-ahead-ajax.php?query=%QUERY',".PHP_EOL;
//echo " minLength: 3,".PHP_EOL;
//echo " limit: 10".PHP_EOL;
echo "});".PHP_EOL;
echo "</script>".PHP_EOL;
echo '</body></html>'.PHP_EOL;
?>
The source of this from the browser looks OK, but I'll paste it here too just in case.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<title>Typeahead Example</title>
<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>
</head>
<body>
Type in a search: <input type="text" name="user_search">
<script type='text/javascript'>
$('#user_search').typeahead({
name: 'user_search',
remote: './type-ahead-ajax.php?query=%QUERY',
});
</script>
</body></html>
I've tested my call back script separately, and it is definitely connecting to the database and pulling back some results. For example if I use '/type-ahead-ajax.php?query=bleach' as a URL, I get all the products containing the word 'bleach'
type-ahead-ajax.php
<?php
// Connect to the database
try {
$dbh = new PDO('mysql:host=localhost; dbname=menu;', 'root', 'root');
$query = '%'.$_GET['query'].'%'; // add % for LIKE query later
//$query = '%milk%'; //debug
echo $query.PHP_EOL;
// do query
$stmt = $dbh->prepare('SELECT title FROM waitrose WHERE title LIKE :query');
$stmt->bindParam(':query', $query, PDO::PARAM_STR);
$stmt->execute();
// populate results
$results = array();
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
$results[] = $row;
echo strtolower($row).PHP_EOL; //debug
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// and return to typeahead
return json_encode($results);
?>
Basically, when you type into the input field nothing happens. It's as though either the callback isn't being called, it's returning nothing, or it's not registered properly in the first place.
Any suggestions?
When you do $('#user_search'), you're referring to an element with id user_search. You haven't, however, given your input any id. Add it:
<input type="text" name="user_search" id="user_search">
If that doesn't work, make sure you get the data you assume by accesssing ./type-ahead-ajax.php?query=%QUERY manually with some query, and check for JavaScript errors in your browser console.
I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>