Alert box malfuction - javascript

I have a problem with the script code . I have an alert box which displays the results of the search but the problem is that it displays the previous result not the current one. The first time it gives null ,then it works by giving the previous result. What is wrong? .Thanks in advance
<?php
include_once('dbconnect.php');
if(isset($_POST['search'])){
$q = $_POST['q'];
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
//Replace table_name with your table name and `thing_to_search` with the column you want to search
$count = mysqli_num_rows($query);
if($count == "0" || $q == ""){
$output = '<h2 style="color:white;">No player found!</h2>';
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userIngame']; // Replace column_to_display with the column you want the results from
$output = '<h2 style="color:white;">There are '.$count.' players </h2><br>';
}
}
}
echo json_encode($s);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(){
var player = <?php echo json_encode($s); ?>;
alert("players : " + player);
});
});
</script>

Take a look at what happens when the PHP parts get executed. The first time your page gets displayed, $q is empty. That's why your SQL will return no result. The $output will be set to '<h2 style="color:white;">No player found!</h2>'; and $s[] will not be set. This is what is written to your page inside the javascript tags...
<script>
$(document).ready(function(){
$("form").submit(function(){
var player = null;
alert("players : " + player);
});
});
</script>
That's why, when you sumbit the form, the alert shows null.
The second time when you display the page, the $q has a value and $s is populated by the SQL call. Now the script will look like this ...
<script>
$(document).ready(function(){
$("form").submit(function(){
var player = "Some Playername";
alert("players : " + player);
});
});
</script>
The alert function however will only be executed when you submit the form and then it will show the name inside the alert box. But of course, by then, you are expecting the next playername to be shown.

Related

How to concatenate multiple php variables within Javascript

Hello I am trying to utilize geomapping within in my website and I'm having trouble dynamically pulling the address for a restaurant and putting it into my javascript. I am using the get method to pull the restaurant_id from the url and then use this to pull the restaurant's complete address. This is the line of code I am having trouble with (var destinationAddress):
$con=mysqli_connect("root","");
$rest_id2=$_GET['id'];
$rest_id=(int)$rest_id2;
$sql="SELECT * from restaurant WHERE restaurant_id='".$rest_id."'";
$result=mysqli_query($con,$sql);
$rows=mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
</script>
</head>
....
Any one know see what I am doing wrong here?
Make your life easier: build the destination address outside of the template:
$rows=mysqli_fetch_assoc($result);
if( $rows !== NULL )
{
$destinationAddress = "{$rows['address']}, {$rows['city']}, {$rows['state']}, {$rows['zip']}";
}
else
{
// no rows! (anomaly)
$destinationAddress = "no destination address available";
}
// due to the way you'll later inject the variable
// into JavaScript code double quotes must be escaped
$destinationAddress = str_replace( '"', '\"', $destinationAddress );
Then simply
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?=$destionationAddress?>";
} );
Try adding the commas and spaces.
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
becase u forgot to close the function }) , try
<script>
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
})
</script>

I want to keep on storing and displaying the result I am getting from mysql

I am not an expert at php just a newbie so not sure what to do.What I am trying to do is to keep on saving the result I am getting from the textboxThis is the textbox and shirt,color and price is the result I am getting from the table and keep on displaying it on my page. The picture for the textbox is attached. I want to keep on storing the new result I get from the table and also keep displaying the old one. I hope its clear what I am trying to do. My code has three files the main file products.php has the following code
<!DOCTYPE html>
<html>
<head>
<title>Products</title>
<p> Scan the Barcode of the Product </p>
<link href="mystyle.css" rel="stylesheet">
</head>
<body>
<input type="text" name="enter" required id="item" style="text-align:centre" placeholder=" Barcode ID" autofocus />
<div id="item-data"></div>
<script src="js/jquery-2.2.0.min.js"></script> <!--jquery link-->
<script src="js/global.js"></script> <!--linking event file-->
</body>
</html>
while code for global.js is
$(function(){
//press enter on text area..
$('#item').keypress(function (event) {
var key = event.which;
if(key == 13) // the enter key code
{
var item = $('input#item').val(); // retreiving the value from the item
if ($.trim(item) != ''){ //send this to php file but if its empty or spaces(trim) are there dont send it//
$.post('ajax/name.php',{id:item}, function(data){ //using post method sending to the father(name.php), sending the data through the file item
$('div#item-data').append(""+data+"</br>"); // grabing the data and displaying it
});
}
$('#item').val('');
}
});
});
and the third file my name.php file consists of the following code
<?php
require '../db/connect.php';
$id= $_POST['id']; // your post variable
$sql = "SELECT BarcodeID, shirts, price FROM clothes WHERE BarcodeID=".mysqli_real_escape_string($con,$id);
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
if(mysqli_num_rows($result)>0)
{
while($row = $result->fetch_assoc())
{
echo " " . $row["BarcodeID"]. " shirt color: " . $row["shirts"]. " price: " . $row["price"];
}
}
else
{
echo "ID not found, Please Scan again";
}
mysqli_close($con);
?>
This issue was solved by using append function in the javascript. Check in the global.js file.

AJAX Live Search Not Showing Results

Have a live search page as shown in livesearch.php below, when typing entries into the input box am not getting any results show under it. The html code and script in search.php are shown beelow.
search.php
<!DOCTYPE HTML>
<html>
<header>
<link href="css/main.css" rel="stylesheet" type="text/css">
<link href="css/search.css" rel="stylesheet" type="text/css">
</header>
<body>
<div id="searchContainer">
<div class="searchMainTitle">Search Schedules</div>
<div class="searchSubTitle">
<p>Enter any information you wish, this will search all schedule fields.</p>
</div>
<form role="form" method="post">
<input type="text" class="form-control" size="100%" placeholder="Enter Search Term(s) Here" id="keyword" />
</form>
<ul id="liveSearch"></ul>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#keyword').on('input', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('livesearch.php', { keywords: searchKeyword }, function(data) {
$('ul#liveSearch').empty()
$.each(data, function() {
$('ul#liveSearch').append('<li>' + this.title + '</li>');
});
}, "json");
}
});
});
</script>
</body>
</html>
The livesearch.php that is being referenced by the script is shown below
livesearch.php
<?php
session_start();
require 'dbconnect.php';
echo "Keyword: ".$_POST['keywords']."<br/><br/>";
$liveSearchArray = array();
if (!empty($_POST['keywords'])) {
$keywords = $connection->real_escape_string($_POST['keywords']);
$sql = "SELECT OWNER_SURNAME,OWNER_FIRSTNAMES,OWNER_TITLE FROM testucm_owners WHERE OWNER_SURNAME LIKE '%".$keywords."%'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "We Have A Result, There Are ".$result->num_rows." Rows";
while ($obj = $result->fetch_object()) {
$liveSearchArray[] = array('id' => $obj->OWNER_SURNAME, 'title' => $obj->OWNER_TITLE);
}
} else {
echo "No Matches";
}
}
echo json_encode($liveSearchArray);
mysqli_close($connection);
?>
If a manually add a value for keywords into the livesearch.php query I get the correct results, however no resutls display if I enter search terms via search.php. I have partially test this by putting an alert after var searchKeyword = $(this).val();, this shows the correct term as typed in however still no results showing.
I suspect the error may be with this line of code:
$('ul#liveSearch').append('<li>' + this.title + '</li>');
Either that or for some reason the $liveSearchArray is not being passed back to the script, however I'm unable to determine where the error lies or how to fix it. Any help would be greatly appreciated
Maybe you should check the php return data.
here:
echo "We Have A Result, There Are ".$result->num_rows." Rows";
see,the return data is not pure json.
I think that may be the key.
When you expect data for "json", you have to keep the return data is only json ,not anything else.Otherwise ,the ajax will get an parse error which is not displayed directly,and your "success" function will not be executed.And it seems like you don't get the data,but actually it's because you get the wrong format data.
It works like this:

dynamic dropdown based on autocomplete value

I am trying to populate a dynamic dropdown list based on the value user has inserted in the previous textbox(auto-complete). So, when user insert an actor/actress name in the auto-complete textbox, a dropdown will be populated by list of movies in which that actor has played.
Problem:
Could someone kindly let me know what is the problem with this code and why it populate an empty dropdown?
Here is the html/js code:
<html>
<?php
print_r($_POST);
?>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
</head>
<body>
Source:
<input type="textbox" name= "tag" id="tags">
<select id="movieImdbId" name="movieImdbId[]" multiple="multiple" width="200px" size="10px" style=display:none;>
</select>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
$("#tags").change(function () {
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#movieImdbId").html(response).show();
});
});
}
});
});
</script>
</body>
</html>
and this is actions.php code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['q']) && !empty($_POST['q'])){
$q = $_POST['q'];
$html = "";
try{
$conn = new PDO('mysql:host=localhost;dbname=imdb;charset=utf8mb4','user','pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = $conn->prepare("SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q");
$sql->execute(array(':q' => $_POST['q']));
while($rows = $sql->fetch(PDO::FETCH_OBJ)){
$option = '<option value="' . $rows['movieImdbId'] . '">' . $rows['movieImdbId'] . '</option>';
}
$html .= $option;
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
I really appreciate if someone can help me fix it.
Thanks.
You call via POST
$.post("actions.php")
but check for GET Variables
if(isset($_GET['q']) && !empty($_GET['q']))
So i guess your php script delivers an empty string.
Print the response to console and see if you get a result.

Populate a dynamic dropdown based on value inserted in the text-box

Please someone help, I am really going to be crazy!.
I have a PHP form with some questions and one of the question is "Which are your favourite movies?" for which I used jQuery auto-complete feature which works fine!. However, It is possible that users forget the name of a movie, but remember an actor that played in that movie. So, I would like to enable user typing an actor/actress name in the auto-complete textbox (e.g., "Tom Cruise") and based on inserted actor name, a dynamic dropdown menu should be added which contains list of movies that the actor (e.g, Tom Cruise) has played in them.
This is what I tried but not work :((
<html>
<?php
print_r($_POST);
?>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
</head>
<body>
<input type="textbox" name= "tag" id="tags">
<select id="movieImdbId" name="movieImdbId[]" multiple="multiple" width="200px" size="10px" style=display:none;>
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php", //php file which fetch actors name from DB
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags.
$("#movieImdbId").html(response).show();
});
}
});
});
</script>
</body>
</html>
and this is actions.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_GET['q']) && !empty($_GET['q'])){
$q = $_GET['q'];
include('Connection.php'); //connection to the DB
$sql = $conn->prepare("SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q");
$sql->execute(array(':q' => $q));
$html = "";
while($row = $sql->fetch(PDO::FETCH_OBJ)){
$option = '<option value="' . $row->movieImdbId . '">' . $row->movieImdbId . '</option>';
$html .= $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
Question: Why when user insert an actor name in the text-box, the dropdown menu is populated but is EMPTY?
In your ajax call, you send a POST request, and you try to get the params with $_GET in you php.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags.
$("#movieImdbId").html(response).show();
});
change the $.post method to $.get.
OR
if(isset($_GET['q']) && !empty($_GET['q'])){
$q = $_GET['q'];
}
change $_GET to $_POST.

Categories

Resources