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

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.

Related

pass data from mysql to javascript

Is this the right way to retrieve data from mysql using jquery? The php side is working fine ($data gets printed onto the page) but jquery doesn't seem to be receiving the variable at all.
Besides that, is there a way to get the jquery function to run after the page AND after the google maps initMap() function has finished loading? Is it possible to include jquery code inside a standard javascript function?
admin.php
<?php
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
echo json_encode($data);
?><!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
What I've tried
js/admin.js
$(document).ready(function() {
$.ajax({
url: '../admin.php',
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
})
});
I received a "404 Not found" error in the console
The 404-Error indicates that you are using a wrong URL in your jQuery code to get the data. Try to enter not just the filename but the whole URL like https://example.com/admin.php for the url parameter.
Besides your problem getting the data via jQuery, what happens when you open admin.php directly in your browser? Are you getting the $data AND your HTML Code? If thats the case I would recommend you to wrap the whole PHP-Code inside an if-statement:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
die(json_encode($data));
}
else{ ?>
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
<? } ?>
Now, if its a POST-Request like from your js, the PHP will return the data as JSON. Also the right header will be set. If its not a POST-Request the PHP will return your HTML.
To your other question: Yes, it is possible to use jQuery in a normal JavaScript function.

Alert box malfuction

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.

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.

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.

PHP SQL Query to Select Tag

I am trying to make a select have some pre-loaded options.
I have a php script that queries for these options, and I want to load them into the select on an html page.
My attempt right now..
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$("#usersList").html(data.value);
});
});
});
</script>
</head>
<body>
<form>
Find Users in: <select id="usersList" name="usersList">
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
PHP
<html>
<head>
</head>
<body>
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$ary[] =$info['State'];
}
mysql_close();
?>
</body>
</html>
My PHP works fine, but I am not sure how to get that information into my select.
All help appreciated!
First:
The html select-tag needs to get closed like this:
<select></select>
Next:
Your $ary isnt defined anywhere and it isnt returned anywhere
Use json_decode(); to return json
(and dont use any html head/body in your php file which outputs json)
Your json.php:
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
$ary = Array();
while($info = mysql_fetch_array( $data ))
{
array_push($ary,$info["state"]);
}
mysql_close();
echo json_encode($ary);
?>
Next:
You need to append option tags to your select with jquery like this:
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$.each(data,function(key,indata){
$("#usersList").append($("<option>",{
html : indata
}));
})});
});
});
Seems you have jquery library is missing. Please add it after the <head> tag and try:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the php, after mysql_close(). Add
print json_encode($ary);

Categories

Resources