An issue when passing a PHP parameter to a JavaScript function - javascript

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"];
}
?>

Related

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 !!

Combine input box and select box to create a search bar

I have an input box that serves as a search box, and I populate a select box by querying a SQL database. For example, there are two organizations called "Dummy Organization" and "Dummy 2" in my db. So when the user starts typing "du", the select box fills with those two organizations. What I want to do is to combine these two fields: the input box (that acts as the search box) and the select box (which displays the results). My research shows that selectize.js can be useful, but since I'm new to js, I can't figure out how. Can someone please help me? My code is as below:
js that gets the data from the db:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output4){
$("#output4").html(output4);
}
</script>
The form:
<form action="newbrand.php" method="post" id="form">
<br>
Brand Name: <input type="text" name="bname" required /><br><br>
Search for an Organization: <input type="text" required name="search" onkeyup="searchq()" id="output"><br><br>
Selected Organization:
<select id="output4" name="taskOption"></select>
</form>
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 = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<option value="<?php echo $orgid; ?>"><?php echo $orgname; ?></option>
<div><?php echo $subs; ?></div>
<?php
} // while
} // else
} // main if
?>

AJAX inserts jQuery script into results div

What I am trying to achieve is have the form appear if there was nothing submitted. So I add the form html to a variable and then echo the variable inside the html.
However ever since I implemented AJAX, inside the #results div. It also exports the jquery.js and my ajax script.
If I remove the PHP else code that displays the form, I won't see the form at all.
So how would someone make sure the js scripts aren't being inserted where they shouldn't be?
PHP:
if( isset($_POST["u_name"]) && isset($_POST["u_lastname"]) && isset($_POST["u_email"]) ){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO testTable (Name, Lastname, Email)
VALUES ('".$_POST["u_name"]."','".$_POST["u_lastname"]."','".$_POST["u_email"]."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."";
}
$conn->close();
}else {
$final_content = '<form action="script.php" method="post" id="user_form">
<input type="text" name="u_name" placeholder="Name" id="user_name"> <br>
<input type="text" name="u_lastname" placeholder="Lastname" id="user_lastname"> <br>
<input type="email" name="u_email" placeholder="Email" id="user_email"> <br>
<input type="submit" value="Submit" name="submit">
</form>';
}
?>
HTML
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
//Set form variable
var form = $("#user_form");
form.submit(function(event){
//Set data variables
var user_name = $("#user_name").val();
var user_lastname = $("#user_lastname").val();
var user_email = $("#user_email").val();
//Check if values are set
if( ($.trim(user_name) != "") && ($.trim(user_lastname) != "") && ($.trim(user_email) != "") ){
$.post("script.php", {u_name: user_name, u_lastname: user_lastname, u_email: user_email}, function(data){
$("#results").html(data);
});
}
event.preventDefault();
});
});
</script>
</head>
<body>
<?php echo $final_content ?>
<div id="results"></div>
</body>
</html>
Add an exit(); right after $conn->close();, just above the else.
This will make sure that once you have output the results, you do not continue with the rest of the code (not included in your question) where you output the full HTML page with script tags and <div id="results"> ...etc.
Apparently that display code is not all inside the else block, but also further down, after the else block.

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

loging php page not redirecting

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
}

Categories

Resources