I'm having a problem passing a variable selected from a dynamic drop dropdown to a PHP file. I want the PHP to select all rows in a db table that match the variable. Here's the code so far:
select.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>"); var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
$.ajax({
type: 'POST',
url: 'display.php',
data: {'result': myval},
});
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<?php include "display.php"; ?>
<div id="result2"></div>
</body>
</html>
And here's the display.php that I want the variable passed to. This file will select the criteria from the db and then print the results in select.php.
<?php
class DisplayResults
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowResults()
{
$myval = $_POST['result'];
$sql = "SELECT * FROM specialities WHERE 'myval'=sp_name";
$res = mysql_query($sql,$this->conn);
echo "<table border='1'>";
echo "<tr><th>id</th><th>Code</th></tr>";
while($row = mysql_fetch_array($res))
{
while($row = mysql_fetch_array($result)){
echo "<tr><td>";
echo $row['sp_name'];
echo "</td><td>";
echo $row['sp_code'];
echo "</td></tr>";
}
echo "</table>";
//}
}
return $category;
}
}
$res = new DisplayResults();
?>
I'd really appreciate any help. Please let me know if I can provide more details.
Link to db diagram: http://imgur.com/YZ0SuVw
The first dropdown draws from the profession table, the second from the specialties table. What I'd like to do is to display all of the rows in the jobs table that match the specialty selected in the dropdown box. This will require the result from the variable (result) from the dropdown to be converted into the spec_code that is in the job table. Not sure exactly how to do this. Thanks!
Well it's impossible to answer your question correctly as we don't know whether it's the category or type field which is to be used in your SQL query.
Below is some concept code which should point you in the right direction.
But first, a few comments..
HTML/JS
When you're checking that the cat and type variables are 'greater than 0' on submit you should parse the values to integers first as post values are sent as text by default.
Your myval value is impossible to decipher, please specify your intention.
For further reference your repeated jQuery queries like $("select#type") can be stored in a variable like var $type = $("select#type") and then be referenced like $type.attr('disabled', 'disabled'). I'm not 100% sure how jQuery caches the results but in theory it should require less processing from jQuery, also it's reduces duplicated code.
PHP
Check that the supervariable indexes are set by using isset() or !empty() before using the values otherwise an warning (or notification, can't recall) will be shown. So instead of $myvar = $_POST['myfield'] do $myvar = isset( $_POST['myfield'] ) ? $_POST['myfield'] : "";
Make sure that you escape or cast/sanitize values before they're using a SQL query. For the MySQL library you'd use the mysql_real_escape_string() function.
The mysql library is deprecated and prone to hacks. Usage of the newer mysqli library is highly recommended.
Again, no idea if the sp_name column is for the category or type field. I've included both.
All though it weirdly works to put the value first in your where expression (before the colum name) it's against normal practice and not recommended. Instead of 'myval'=sp_name do sp_name='myval'.
Fixed your loop showResults().
You never called the method showResults() in display.php. Also note that it returns a value so we must also print it to screen.
HTML/JS
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>"); var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("form#select_form").submit(function(){
// Fetch values and parse them to integers
var cat = parseInt( $("#category").val(), 10 );
var type = parseInt( $("#type").val(), 10 );
if(cat>0 && type>0)
{
$("#result").html('your choice: '+type);
// Prepare data
var data = {
category: cat,
type: type
}
$.ajax({
type: 'POST',
url: 'display.php',
data: data
});
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form" action="">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<?php include "display.php"; ?>
<div id="result2"></div>
</body>
</html>
display.php
<?php
class DisplayResults
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowResults()
{
// Fetch values from POST and escape/cast the values to prevent SQL injection
$category = (int) ( isset( $_POST['category'] ) ? $_POST['category'] : 0 );
$type = (int) ( isset( $_POST['type'] ) ? $_POST['type'] : 0 );
// Use the values in your SQL query
//
// PLEASE CHANGE THE COLUMN NAMES TO MATCH YOUR SOLUTION
//==================
$sql = "SELECT * FROM specialities WHERE category='". $category ."' and type='". $type ."' ";
$res = mysql_query($sql,$this->conn);
echo "<table border='1'>";
echo "<tr><th>id</th><th>Code</th></tr>";
while($row = mysql_fetch_array($res))
{
echo "<tr><td>";
echo $row['sp_name'];
echo "</td><td>";
echo $row['sp_code'];
echo "</td></tr>";
//}
}
echo "</table>";
return $category;
}
}
$res = new DisplayResults();
// Get and print results
echo $res->showResults();
?>
Related
This is index.php . when i give a input, it fetch the specific name and year. that's OK . but when i submit the form ,without any input it gives all the name of the movie and years but i don't want that ,the user can not show all the data saved in the database. i gave priventdefault() method but it's not working. how can i solve this problem ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///this is query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
Execute the query only if $name is not null.
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
in javascript
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
In query.php, you always assign empty string to $name in the line if empty 'name' value passed into query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
So query will return you all the results in db as $name is an empty string and matches with all the data in db.
You can validate if $name is empty, not to run the query.
This is my coding. This coding allows me to search the keyword in my database and it worked fine. But how can i search the keyword without click the search button? What i want is same as the search function in the google search. It can automatically help you search and review without hit any button.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Search Contacts</title>
</head>
<p><body>
<h3>Search Contacts Details</h3>
<p>You may search either by first or last name</p>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="question">
<input type="submit" name="submit" value="Search">
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['question'])){
$question=$_POST['question'];
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"search")or die(mysqli_error($con));;
$sql="SELECT id , question FROM question WHERE question LIKE '%" . $question . "%'";
//-run the query against the mysql query function
$result=mysqli_query($con, $sql);
while ($row=mysqli_fetch_array($result)){
$question =$row['question'];
$id=$row['id'];
echo "<ul>\n";
echo "<li>" . " " . $question . "</li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
?>
</body>
</html>
</p>
Well, the way Google does it is a bit different. However, what you can do is use JavaScript (jQuery is probably easiest for you here) to send a XHR, which would retrieve the results. This would look something like this
$('input[name="question"]').on('keyup', function (e) {
$.ajax({
url: "search.php?go",
method: 'post',
data: {
query: e.target.val()
}
}).done(function(data) {
// Output your data however you want
});
}
Of course, you could also use the GET HTTP method, that's all your preference.
Now, aside from this, it looks like you have a SQL injection vulnerability in your query. Essentially, if I would input 'DROP DATABASE question as my search query, that would drop your database. What you should be doing is using prepared statements using Mysql::prepare, see the docs here.
Final note: Google does not do it this way. The best way to achieve blazing fast search results is using WebSockets to maintain a socket connection to your server, and letting the search run through a document database such as Elasticsearch, which is optimised for full-text search.
Step 1:
give ID to your input field...
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search Here" />
<div id="result"></div>
</div>
Step 2:
On keyUp search variable is cathed into vaiable and passed via AJAX to "findit.php"
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "findit.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
Step 3:
Now create a php file having name "findit.php" and use the below code
include('conn.php'); //this is your DB connection file
if($_POST)
{
$q = mysqli_real_escape_string($connection,$_POST['search']);
$qry = mysqli_query($connection,"select col_name from tbl_name where col_name like '%$q%' order by col_name LIMIT 7");
while($row=mysqli_fetch_array($qry))
{
$col_name = $row['col_name'];
$b_res = '<strong>'.$q.'</strong>';
$final_res = str_ireplace($q, $b_res, $col_name);
?>
<?php
}
}
?>
I have here a dropdown select and autocomplete function. What I need to do is to pass the selected value of dropdown to autocomplete.php to use in my query. Textbox value should depending on value from dropdown. If selected value is supplies, all supplies only value in textbox (like pencil or ballpen).
I used this Ajax in Dynamic Dropdown. How I can use this to pass the value in autocomplete.php?
Note: this Ajax was not connected in my autocomplete function. How I can use this ajax to pass the value to my autocomplete.php query.
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#sub').html(data);
}
});
});
</script>
Ajax.php
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
Drop1
<?php
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
Auto Complete <input id="tag" type="text">
Autocomplete.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
$('#sub').html(data); should be $('#tag').html(data);
You have not defined #sub element in your html code, when placing this
$('#sub').html(data);
After that your name of the page must be same, while your using getajax.php, and its not you have defined us
I am trying to populate drop down lists one after the other. These drop down lists contain categories and subcategories. I would like to continue creating drop down lists until there are not more subcategories for a particular category.
I am populating my drop down lists with results from MySQL.
I have searched all over and could not find any references to cascading drop down lists using more than two lists.
My code works for two lists, but not for more.
partRequest.php
<HTML>
<HEAD>
<script type="text/javascript" src="..\jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#1").change(function(e) {
e.preventDefault();
getNextCategory("1");
});
$("#2").change(function(e) {
e.preventDefault();
getNextCategory("2");
});
$("#3").change(function(e) {
e.preventDefault();
getNextCategory("3");
});
});
function getNextCategory(htmlID) {
var categoryID = ""
var newHTMLID = 0
var newCategory = ""
categoryID = $("#" + htmlID ).val();
newHTMLID = Number(htmlID) + Number(1)
newCategory = "category" + newHTMLID
$.ajax({
type: "POST",
url: "findNextCategory.php",
data: "ID=" + categoryID + "&Number=" + newHTMLID,
success: function(output){
$("#" + newCategory).html(output);
}
});
}
</script>
</HEAD>
<BODY>
<form name="partSubmissionForm" id="partSubmissionForm" action="" method="POST">
<table width=147 cellpadding=0 cellspacing=0>
<tr><td><select id="1">
<?PHP
$query = "SELECT Name, ID FROM categories WHERE ParentID = 0";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result)){
?>
<option value="<? echo $row['ID'];?>"> <? echo $row['Name'];?></option>
<?}?>
</select>
</td>
<td>
<div id="category2">
test2
</div>
</td>
<td>
<div id="category3">
test3
</div>
</td>
</tr>
<tr><td><input type="submit" name="submit" id="submit" value="GO"></td></tr>
</table>
</form>
</BODY>
</HTML>
findNextCategory.php
<?PHP
define('INCLUDE_CHECK',true);
include ('..\db.php');
$categoryID = $_POST['ID'];
$categoryFieldNum = $_POST['Number'];
echo $categoryID;
echo $categoryFieldNum;
$query = "SELECT Name, ID FROM categories WHERE ParentID = $categoryID";
echo $query;
echo "<select id=$categoryFieldNum>";
$query = "SELECT Name, ID FROM categories WHERE ParentID = $categoryID";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result)){
$optionValue = $row['ID'];
$optionText = $row['Name'];
echo "<option value='$optionValue'> $optionText </option>";
}
echo "</select>";
?>
The problem is that your click function definitions only apply to items that are already on the page at page load. Because you do not yet have a select object on the page with an id of "2", your $("#2").change function does not ever get attached.
What you need to do to get around this is to apply that click definition after you add the select to the page. Try changing your success function to this:
success: function(output){
$("#" + newCategory).html(output);
$("#" + newHTMLID).change(function(e) {
e.preventDefault();
getNextCategory(newHTMLID);
});
}
I have one big file (for right now) that is supposed to:
take a variable from a select widget in a form (jQuery)
submit the form asynchronously (jQuery)
return records from a database using the variable selected from the form (php)
The problem is, the variable never seems to reach the php code.
Can anyone tell me what I'm doing wrong, please?
My code:
(all on one page)
<script type="text/javascript">
$(function() {
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.post("index.php", { zip: str}, function(data){
$('result').text(str); }, "json" );
});//end select
});//end function
</script>
<?php include_once ('../cons.php'); ?>
<?php
if (isset($_POST['zip'])){
$value = $_POST['zip'];
}else{
$value = "nada";
}
echo $value;
//I only get "nada"
?>
</head>
<body>
<div id="body">
<form id="findzip"><!-- jQuery will handle the form -->
<select name="zip">
<option value="">Find your zip code</option>
<?php //use php to pull the zip codes from the database
$mysqli_zip = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit();
}
$q_zip = "select distinct(zip) from mc m group by zip";
$r_zip = $mysqli_zip->query($q_zip);
if ((!$r_zip) || ($r_zip == NULL)) {
echo "no results ";
}
while($row_zip = $r_zip->fetch_array(MYSQLI_BOTH)) {
echo "<option value='". addslashes($row_zip['zip']) . "'>" . addslashes($row_zip['zip']) . "</option>;\n";
}//end while
?>
</select>
</form>
<!-- here's where the results go -->
<result></result>
<br/>
</div>
</body>
</html>
Your script as written is echoing out a value like "12345". But your $.post is expecting it to be type json. When I removed the json type it worked perfectly for me.
Try putting an ID on it, like so:
<select name="zip" id="zip">
Then getting the value from it like so:
$("#zip").val();