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.
Related
I'm new with coding and I found some really valuable information that could help my register form look better using Ajax.
The problem is that, even though the php files are working fine, I think that the js file is not doing it's job. here:
in the register form there's this:
<?php
include 'php_includes/conexion.php'; (connect to DB users)
include 'php_includes/conexionlugar.php'; (connect to DB states/cities)
?>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.js"></script>
</head>
in the form there's this:
Select State
<select name="departamento" id="departamento">
<option value="">Seleccione Departamento</option>
<?php echo cargar_departamentos();?>
</select>
Select City
<select name="provincia" id="provincia">
<option value="">Seleccione Provincia</option>
</select>
Now, in the conexionlugar.php (tested/working):
<?php
function cargar_departamentos()
{
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output = '';
$sql = "SELECT * FROM departamentos ORDER BY NOMBRE_DEPA";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDDEPARTAMENTOS"].'">'.$row["NOMBRE_DEPA"].'</option>';
echo "$output";
}
}
return $output;
?>
in the jquery.js (don't know much about this :()
$(document).ready(function(){
$('#departamento').change(function(){
var IDDEPARTAMENTOS = $(this).val();
$.ajax({
url:'../php_includes/fetch_provincia.php',
type:"POST",
data:{departamentoId:IDDEPARTAMENTOS},
dataType:"text",
success:function(data)
{
$('#provincia').html(data);
}
});
});
});
in the fetch_provincia.php (tested/working)
<?php
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output ='';
$sql = "SELECT * FROM provincias WHERE departamentos_IDDEPARTAMENTOS = '".$_POST["departamentoId"]."' ORDER BY NOMBRE_PROV";
$result = mysqli_query($connect, $sql);
$output = '<option value="">Seleccione Provincia</option>';
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDPROVINCIAS"].'">'.$row["NOMBRE_PROV"].'</option>';
echo $output;
}
return $output;
?>
Though separately the PHP files are working, the JS file changing departamentoId for IDDEPARTAMENTOS looks like it's not... help me please.
I think I fixed it, deleting the "return" on both php and adding the js to the same page and not calling it through
The data you are sending from php needs to be sent as json. I would actually not do the "formatting" in php. Just return $result:
echo json_encode($result);
then in your js file, just iterate through "data" and create the options:
success:function(data)
{
$.each(data, function(key, val){
console.log("Key: " + key + " val: " + val);
}
}
have a some errors in your code.
First, in "cargar_departamentos", the return it´s out of a function, and in your fetch_provincia.php, not need a return statement.
In your jQuery code, try remove one of both jQuery called in your head, and Change de dataType directive of "text" to HTML.
#gilgameshbk you are calling jquery 2 times in your head
maybe this may cause some conflict.
I'm new to ajax so I don't know much about ajax syntax. though i am trying here to pass variable from php to ajax and then back to php. I was able able to get it done with one variable when it came to two variables I was confused. I don't even know what to search on google to get an answer my to query. So I will be brief here's my php code. addnewbug.php
<script type="text/javascript" language="javascript" src="./javascripts/jquery.js"></script>
<script type="text/javascript" language="javascript" src="./javascripts/script.js"></script>
</head>
<div class="margin custom">
<body bgcolor="#2e2e2e">
<div style="text-align: center; padding-top: 0px">
<h1 style="color:white;font-size: 50px">Bughound</h1>
</div>
<div class="effect8">
<div class="tableMargin">
<table width="622" class="table">
<tr class="program_row">
<form>
<td width="150" class="td" style="padding-right: 1.9cm">Program</td>
<td width="171" class="td">
<select id="program" class="dropdown">
<option></option>
<?php
require "./db.php";
$sql = "SELECT DISTINCT program_name FROM program";
$result = db($sql);
while ($row = $result->fetch_assoc()) {
$program_name = $row['program_name'];
echo '<option name ="' . $program_name . '">' . $program_name . '</option>';
}
?>
</select>
</td>
<td width="51" class="td">Release</td>
<td width="41" >
<div class="release" id="release">
<select class="release_select" id='release1'>
</select>
</div>
</td>
<td width="103" class="td">Version</td>
<td width="78" class="td">
<div class="version" id="version">
<select class="version_select" id='program_number'>
</select>
</div>
</td>
</form>
</tr>
</table>
This is the original page where I'm trying to make changes in select box using the get passing statement
here's the script.js which I am using to get variable and pass it to another php program..
$(function(){
$("#program").change(function(){
$(".release_select").remove();
$(".version_select").remove();
if($("#program").val() !== "") {
$.get("addnewbug1.php", {program_name: $("#program").val()})
.done(function(data){
$("div.release").after(data);
});
$.get("addnewbug_version.php", {program_name: $("#program").val()})
.done(function(data){
$("div.version").after(data);
});
}
});
$("#program_number").change(function(){
$(".release_select").remove();
if($("#program_number").val() !== "") {
var val2 = $("#program_number").val();
$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
.done(function(data){
$("div.release").after(data);
});
}
});
});
The first function is working fine as it takes values from the program and pass it to addnewbug1.php which takes the program name and generate the new select boxes for release and version of it then which is replaced in div-release and division-version(or number)
this is the file where the first function work perfectly - addnewbug1.php
require "./db.php";
echo "<select class='release_select' id='release1'>";
$programname = $_GET['program_name'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'"';
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
echo "</select>";
?>
Now I am having error in the second change function of script.js where I need to pass two variables in '$.get' area. Also the .change fucntion for program_number is not working and it won't delete the select box on changing it.
$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
and the addnewbug2.php is also the new file which is being used by it is -
require "./db.php";
echo "<select class='release_select' id='release1'><option></option>";
$programname = $_GET['program_name'];
$programnumber = $_GET['program_number'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'" and program_number=' . $programnumber;
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
echo "</select>";
?>
I don't know if you get my question or not. Thank you for replying to this question and please reply if require more info.
this is the addidtional db.php code
function db($sql){
//Check for connection variable already set
if(!isset($conn)){
//Database Connectivity - ip, username, password, database name
$conn = new mysqli("i have filled this correctly");
}
//Check Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, $sql);
mysqli_close($conn);
return($result);
}
If I get that correctly, your initial problem is to pass more than one variable in AJAX call.
You can construct the URL like this :
var val2 = $("#program_number").val();
var val1 = $("#program").val();
$.get("addnewbug2.php?program_number="+val2+"&program_name="+val1)
json_encode() is perfect for transport php variable with ajax
something like
//your ajax call receiver page -: your_link_for_ajax.php
$output = json_encode(array('type'=>'success','address'=>$address,'table_record'=>$table_record));
die($output);
you can read it like
this code on your html page
$.post('your_link_for_ajax', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert alert-danger">'+response.text+'</div>';
}else{
output = '<div class=" alert alert-success">'+response.address+'</div>';
$('#stateIdContact').html(response.table_record);
}
}, 'json');
Thank you for replying, i solved my problem using AngularJS, which i started reading after posting this question. My main moto behind this question was to populate a (2nd)select box and (3rd)select box using value from other (1st) select box and when the values in newly populate (2nd) select box was done. Then change values (3rd)select box using the (2nd) select box. Vice versa for last point. Apply unique filter to select boxes and without moving to next page.
So here's the code simplified form of Addnewbug.php-
<!DOCTYPE html>
<html >
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<select ng-model="selectProgram">
<option></option>
<option ng-repeat="x in programes | unique: 'prognumber'" name=""{{x.progname}}"">{{ x.progname }}</option>
</select>
<select ng-model="selectNumber">
<option></option>
<option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['progrelease']:selectRelease | unique: 'prognumber'" name=""{{x.prognumber}}"">{{ x.prognumber }}</option>
</select>
<select ng-model="selectRelease">
<option></option>
<option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['prognumber']:selectNumber | unique: 'progrelease'" name=""{{x.progrelease}}"">{{ x.progrelease }}</option>
</select>
</div>
<script>
var app = angular.module('myApp', ['angular.filter']);
app.controller('customersCtrl', function($scope, $http) {
$http.get("db/program_db.php")
.success(function (response) {$scope.programes = response.records;});
});
</script>
</body>
</html>
offcourse i used some other stackexchange questions to get it right.
And for the table which is being imported in this code i used this program_db-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if(!isset($conn)){
//Database Connectivity - ip, username, password, database name
$conn = new mysqli("*connection parameters*");
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, "SELECT program_name, program_number,program_release FROM program");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"progname":"' . $rs["program_name"] . '",';
$outp .= '"prognumber":"' . $rs["program_number"] . '",';
$outp .= '"progrelease":"'. $rs["program_release"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
I have same problem as you had in this page: PHP ajax database : how to pass two variables and get data of them in different options? ,i have 2 diffrent php file,one is handling select files,the other handle the database sql,firstly i pass a value which user choosed from first select which updates the second select,and choosing second select should update third select(which is remain empty) i dont know what is my problem(i guess i send value of first ajax to the other php file,and when i get it back to use it for second ajax call,the first value will gone.
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.
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);
Whilst I'm sure it must be something really obvious, I can't see where I am going wrong with this. I have a drop down list with two options in it. When I Select an option it should use XMLHttpRequest() to get a list of customers from the database, based on the option selected.
I have two parts:
ajax2_js.php - contains the javascript and html form.
ajax2_DBAccess.php - contains the PHP that gets the list from the databse.
I have checked everything on the second page, and this works fine on it's own (and displays the relevant list as a dropdown menu), but when I select the option on the first page, nothing happens.
My code thus far is:
ajax2_js.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
function ajaxFunction()
{
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
document.getElementById('customerDiv').innerHTML=req.responseText;
}
}
ajaxResuest.open("GET", strURL, true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
Network : <select name="network" onChange="ajaxFunction('ajax2_DBAccess.php?network='+this.value)">
<option value="">Select Network</option>
<option value="1">Net1</option>
<option value="2">Net2</option>
</select>
</br>
Customer : <div id="customerDiv">
<select name="select">
<option>Select Customer</option>
</select>
</div>
</form>
</body>
ajax2_DBAccess.php
<?php
$network=$_GET['network'];
$q1 = "SELECT `CustName` FROM monitor.customers where network = $network;";
$con = new mysqli('localhost:3306', 'xxx', 'xxx');
if (mysqli_connect_errno())
{
$error = mysqli_connect_error();
echo $error;
exit();
}
else
{
$ConfRes = mysqli_query($con, $q1);
if ($ConfRes)
{
echo "<select name=\"Customers\">";
echo "<option>Select Customer</option>";
while($row=mysqli_fetch_array($ConfRes, MYSQLI_ASSOC))
{
$result = $row['CustName'];
echo "<option value>$result</option>";
};
echo "</select>";
}
else
{
$error = mysqli_error();
echo $error;
exit();
}
};
?>
Any assistance would be appreciated.
Check the javascript error log.
This might be the problem, a spelling error in "Request".
ajaxResuest.open("GET", strURL, true);
Also, your SQL query suffers from an SQL injection vulnerability in the $network parameter.
You can either use XML or JSON to return list. This tutorial should help. I personally would use XML.
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("CustName",$row['CustName']);
}
echo $dom->saveXML();
but there are plenty of tutorials on both methods.
Thanks for all your help guys, I have tracked it down to three things (all my fault):
function ajaxFunction()
should be:
function ajaxFunction(strURL)
.
ajaxResuest.open("GET", strURL, true);
should be:
ajaxRequest.open("GET", strURL, true);
.
and finally:
document.getElementById('customerDiv').innerHTML=req.responseText;
should be
document.getElementById('customerDiv').innerHTML=ajaxRequest.responseText;
.
(and of course the SQL injection vulnerability mentioned above which I will also fix).
cheers.