I got a database table called category as shown:
I am trying to do a dynamic drop down box and the index script is shown as:
<?php
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `category`
WHERE `master` = 0";
$statement = $objDb->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Dependable dropdown menu</title>
<meta name="description" content="Dependable dropdown menu" />
<meta name="keywords" content="Dependable dropdown menu" />
<link href="/css/core.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="/js/core.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
</div>
</body>
</html>
The update.php is shown as:
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `category`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option
value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('',
$out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
The 2nd drop down box is not showing the values dependent on the 1st drop down box as shown:
Can someone help me please.
Here is an example that will do what you want. Essentially, you can use jQuery / AJAX to accomplish this.
I updated my example code to match your server login / table / field names, so if you copy/paste these two examples into files (call them tester.php and another_php_file.php) then you should have a fully working example to play with.
I modified my example below to create a second drop-down box, populated with the values found. If you follow the logic line by line, you will see it is actually quite simple. I left in several commented lines that, if uncommented (one at a time) will show you what the script is doing at each stage.
FILE 1 -- TESTER.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
FILE 2 - another_php_file.php
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'root';
$pword = '';
$dbname = 'test';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT * FROM `category` WHERE `master` = 0";
$result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<select>
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<option value="' .$row['id']. '">' . $row['name'] . '</option>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</select><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
To answer your question in the comment: "How do you make the 2nd drop down box populate fields that are only relevant to a selected option from the 1st drop down box?"
A. Inside the .change event for the first dropdown, you read the value of the first dropdown box:
$('#dropdown_id').change(function() {
var dd1 = $('#dropdown_id').val();
}
B. In your AJAX code for the above .change() event, you include that variable in the data you are sending to the 2nd .PHP file (in our case, "another_php_file.php")
C. You use that passed-in variable in your mysql query, thereby limiting your results. These results are then passed back to the AJAX function and you can access them in the success: portion of the AJAX function
D. In that success function, you inject code into the DOM with the revised SELECT values.
That is what I am doing in the example posted above:
The user chooses a student name, which fires the jQuery .change() selector
Here is the line where it grabs the option selected by the user:
var sel_stud = $(this).val();
This value is sent to another_php_file.php, via this line of the AJAX code:
data: 'theOption=' + sel_stud,
The receiving file another_php_file.php receives the user's selection here:
$selStudent = $_POST['theOption'];
Var $selStudent (the user's selection posted in via AJAX) is used in the mysql search:
$query = " SELECT * FROM `category` WHERE `master` = 0 AND `name` = '$selStudent' ";
(When changing the example to suit your database, the reference to $selStudent was removed. But this (here, above) is how you would use it).
We now build a new <SELECT> code block, storing the HTML in a variable called $r. When the HTML is fully built, I return the customized code back to the AJAX routine simply by echoing it back:
echo $r;
The received data (the customized <SELECT> code block) is available to us inside the AJAX success: function() {//code block}, and I can inject it into the DOM here:
$('#LaDIV').html(whatigot);
And voila, you now see a second dropdown control customized with values specific to the choice from the first dropdown control.
Works like a non-Microsoft browser.
Related
I am trying to create a dependent dropdown using php and ajax. What I am expecting is when the 'Make' of car is selected the relevant car models should automatically load on the 'Model' dropdown. I have manged to do the preloading of 'Make' of cars. But the 'Model' dropdown remains empty. I have used a single tale and in sql statement used (select model where make= selected make). here is my code
php
<form method="GET">
<div class="form-group">
<select class="form-control" name="make" id="make">
<option value="" disabled selected>--Select Make--</option>
<?php
$stmt=$pdo->query("SELECT DISTINCT make FROM cars WHERE cartype='general' ");
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?= $row['make']; ?>"> <?= $row['make']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<select class="form-control" name="model" id="model">
<option value="" disabled selected>--Select Model--</option>
</select>
</div>
.......
....
.....
script
<script type="text/javascript">
$(document).ready( function () {
// alert("Hello");
$(#make).change(function(){
var make = $(this).val();
$.ajax({
url:"filter_action.php",
method:"POST",
data:{Make:make},
success: function(data){
$("#model").html(data);
});
});
});
</script>
filter_action.php
<?php
include('db_config2.php');
$output='';
$stmt=$pdo->query("SELECT DISTINCT model FROM cars WHERE cartype='general' AND make= '".$_POST['Make']."'");
$output .='<option value="" disabled selected>--Select Model--</option>';
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$output .='<option value="'.$row["model"].'">'.$row["model"].'</option>' ;
}
echo $output;
?>
There appeared to be a couple of mistakes in the Javascript that would have been obvious in the developer console and your PHP had left the mySQL server vulnerable to sql injection attacks.
<script>
$(document).ready( function () {
// The string should be within quotes here
$('#make').change(function(e){
var make = $(this).val();
$.ajax({
url:"filter_action.php",
method:"POST",
data:{'Make':make},
success: function(data){
$("#model").html(data);
};//this needed to be closed
});
});
});
</script>
The direct use of user supplied data within the sql opened your db to sql injection attacks. To mitigate this you need to adopt "Prepared Statements" - as you are using PDO anyway this should be a matter of course.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['Make'] ) ){
# The placeholders and associated values to be used when executing the sql cmd
$args=array(
':type' => 'general', # this could also be dynamic!
':make' => $_POST['Make']
);
# Prepare the sql with suitable placeholders
$sql='select distinct `model` from `cars` where `cartype`=:type and `make`=:make';
$stmt=$pdo->prepare( $sql );
# commit the query
$stmt->execute( $args );
# Fetch the results and populate output variable
$data=array('<option disabled selected hidden>--Select Model--');
while( $rs=$stmt->fetch(PDO::FETCH_OBJ) )$data[]=sprintf('<option value="%1$s">%1$s', $rs->model );
# send it to ajax callback
exit( implode( PHP_EOL,$data ) );
}
?>
I have try this using php pdo.
first i have create a 3 files.
db.php
htmlDropdown.php
modelAjax.php
here, db.php file can contain my database connection code. and htmlDropdown.php file contain my dropdown for car and models. and modelAjax.php file contain ajax to fetch all models.
db.php
<?php
$host_name = 'localhost';
$user_name = 'root';
$password = '';
$db_name = 'stackoverflow';
$conn = new PDO("mysql:host=$host_name; dbname=$db_name;", $user_name, $password);
?>
htmlDropdown.php
<?php include "db.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cars</title>
<!-- jQuery cdn link -->
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<!-- Ajax cdn link -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxy/1.6.1/scripts/jquery.ajaxy.min.js" integrity="sha512-bztGAvCE/3+a1Oh0gUro7BHukf6v7zpzrAb3ReWAVrt+bVNNphcl2tDTKCBr5zk7iEDmQ2Bv401fX3jeVXGIcA==" crossorigin="anonymous"></script>
</head>
<body>
<?php
$car_sql = 'SELECT car_name FROM cars'; //select all cars query
$cars_statement = $conn->prepare($car_sql);
$cars_statement->execute();
?>
<select name="car" id="car">
<option value="">Cars</option>
<?php
while ($cars = $cars_statement->fetch()) { // fetch all cars data
?>
<option value="<?php echo $cars['car_name']; ?>"><?php echo $cars['car_name']; ?></option>
<?php
}
?>
</select><br><br>
<select name="model" id="model">
<option value="">Model</option>
</select>
</body>
</html>
<script>
$(document).ready(function () {
$('#car').on("change", function () {
let car = $(this).val(); // car value
$.post("http://local.stackoverflowanswer1/cars/modelAjax.php", { car_name : car }, function (data, status) { // ajax post send car name in modelAjax.php file
let datas = JSON.parse(data); // convert string to json object
let options = '';
options = '<option>Model</option>';
$.each(datas.model, function (key, value) {
options += "<option>"+value.modal_name+"</option>";
});
$('#model').html(options);
});
});
});
</script>
modelAjax.php
<?php
include "db.php";
if ($_POST['car_name'])
{
$car_id_sql = "SELECT id FROM cars WHERE car_name LIKE ?"; // get id from given car name
$id_statement = $conn->prepare($car_id_sql);
$id_statement->execute([$_POST['car_name']]);
$id = $id_statement->fetch();
$model_sql = "SELECT modal_name FROM models WHERE car_id = ?"; // get model name from given id
$model_statement = $conn->prepare($model_sql);
$model_statement->execute([$id['id']]);
$models = $model_statement->fetchAll();
echo json_encode(["model" => $models]); // i have a conver array to json object
}
?>
I'm trying to create a program that when you select a state from the drop down menu, it will display the list of cities for that state in another drop down menu that you can select from. After you choose your city and state, you type in an address, hit submit, and it will display the full address on a new php file.
My issue at the moment is I can get the states displayed, but when the state is selected, it is not giving me the list of options for that city in the second drop down menu. Any help is appreciated, thanks!
You can view the behavior at this link
select.php
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<!DOCTYPE html>
<form action = "display.php">
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Address Generator</p>
<center>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option>Select state</option>
<?php
include ( "accounts.php" ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$select=mysql_query("select state from zipcodes group by state");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['state']."</option>";
}
?>
</select>
<select id="new_select">
</select>
<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<input type = submit>
</form>
fetch.php
<?php
include(accounts.php);
if(isset($_POST['get_option']))
{
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$state = $_POST['get_option'];
$find=mysql_query("select city from zipcodes where state='$state'");
while($row=mysql_fetch_array($find))
{
echo "<option>".$row['city']."</option>";
}
exit;
}
?>
1)First of all your state option's value attribute is missing
echo "<option value='".$row["state"]."'>".$row["state"]."</option>";
2)Include(accounts.php); accounts.php should be enclosed by double quotes
3) And city option's value attribute is missing
echo "<option value='".$row["city"]."'>".$row["city"]."</option>";
4) Instead of echoing each time concatenate and echo finally like this
$options="";
while($row=mysql_fetch_array($find))
{
$options.= "<option value='".$row["city"]."' >".$row["city"]."</option>";
}
echo $options;
Warning!!!
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
I've modified your code a little. Tried to do it the elegant way. You had wrote too much of superfluous code. You didn't need a <form> element to perform the asked operation. Anyway below is the modified code.
<!DOCTYPE html>
<head>
<title>Address Generator</title>
</head>
<body>
<p id="heading">Address Generator</p>
<center>
<!-- <div id="select_box"> -->
<select name="select_box" id="select_box">
<?php
include ( "accounts.php" ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) ) or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$select=mysql_query("select state from zipcodes group by state");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['state']."</option>";
}
?>
</select>
<select id="new_select">
</select>
<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#select_box').on('change', function() {
var state = $(this).val();
$.ajax({
url: 'fetch.php',
type: 'POST',
data: {state: state},
success: function(response)
{
var response = JSON.parse(response);
$('#new_select').find('option').remove();
var option = '';
$.each(response.cities, function(key, val) {
option = option + "<option value='" + val + "'>" + val + "</option>";
});
$('#new_select').append(option);
}
});
});
});
</script>
</body>
I've added Jquery before the end of </body> tag. This doesn't hinder your current code execution. However you could always preload it but that tactic is for later.
Since you didn't need any <form> element so I've completely removed it. You can always add it according to your convenience.
I'm running a loop on the cities array of the object response that I'm getting from fetch.php.
parsing the JSON data using JSON.parse() function.
You'll need to json_encode your json variable which will store the corresponding citites data.
I hope this helps. Any further queries are welcome too.
New in php and ajax, building a dropdown based on another dropdown through database.Up to now code is sucessfully running, you can check my code having two php pages, dropdown2.php and postbrand.php now just want to know how to use $brand variable value in postbrand.php to use in the sql query in second dropdown in dropdown2.php.
<?php
require 'connect.inc.php';
$query = "SELECT * FROM `brand` ";
$data = mysql_query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Input form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12/jquery.min.js"></script>
</head>
<body>
<form>
<label>Brand:</label>
<select name="brand" id="sb" onchange="myFunction()">
<?php
while($row=mysql_fetch_array($data))
{
?>
<option value="<?php echo $row['b_name'];?>">
<?php
echo $row['b_name'];
?>
</option>
<?php
}
?>
</select>
<br/><br/>
<label>Model:</label>
<?php
$query = "SELECT model.model, model.b_id from model inner join brand on model.b_id= brand.b_id where brand.b_name like 'sony'";
$result = mysql_query($query);
$select= '<select name="select" id="sm">';
while($rs=mysql_fetch_array($result)){ $select.='<option value="'.$rs['b_id'].'">'.$rs['model'].'</option>';
}
$select.='</select>';
echo $select;
?>
</form>
<div id="result"></div>
<script>
function myFunction() {
//alert('working!!');
var brand = $('#sb').val();
$.post('postbrand.php', {postbrand:brand},
function(data){
$('#result').html(data);
});
}
</script>
</body>
</html>
postbrand.php
<?php
$brand = $_POST['postbrand'];
echo $brand;
?>
If I get it correct you want to populate the second dropdown based on the chosen value of the first dropdown.
To steps to achieve this are:
listen to "change" event on the first dropdown (using JQ)
var selected = ""
$('select#sb').on('change', function() {
selected = $(this).val(); // get the chosen value
});
$.post("postbrand.php", selected, function(resp){ //send the selected value to postbrand.php which will return an array of elements from db based on what was selected
$.each(resp,function(key, val){ //traverse the response and
$('select#secondDropdown').append('<option>'+val+'</option>') //populate the 2nd dropdown
})
})
I am creating a MySQL query that will be execute when user select options from more a dropdown lists.
What I want is, on selecting a dropdown list option a query related to that option should be automatically executed using ajax/javascript on the same page. As I have the both html and php code on the same page.
Earlier I was using form submit options for dropdown list but as the number of dropdown option are more than five for filtering the result so queries became complicated to implement. That's why I want to refine result of each dropdown individually.
Any help is appreciated. Thanks in advance!
My HTML code for dropdown list is:
<p>
<label for="experience">Experience :</label>
<select id="experience" name="experience">
<option value="" selected="selected">All</option>
<option value="Fresher">Fresher</option>
<option value="Experienced">Experienced</option>
</select>
</p>
PHP code for executing related queries is:
<?php
if (isset($_GET['exp'])) {
switch ($_GET['exp']) {
case 'Experienced':
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers where job_seekers.Experience!='Fresher'";
break;
case 'Fresher':
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers where job_seekers.Experience='Fresher'";
break;
default:
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers";
}
}
$result = mysql_query($query) or die(mysql_error());
echo "<ul class=\"candidates\">";
while($row = mysql_fetch_row($result))
{
echo "<li>";
echo "<p> <b>ID:</b> <u>$row[0]</u> </p>";
echo "<p> <b>Name :</b> $row[1] </p>";
echo "<p> <b>Key Skills:</b> $row[2] </p>";
echo "<p> <b>Experience:</b> $row[3] </p>";
echo "</li>";
}
echo "</ul>";
?>
When you want to AJAX call a php script, you should you $.ajax provided by Jquery
http://api.jquery.com
so you can use it like so:
$.ajax({
url: 'ajax.php',
data: {
//put parameters here such as which dropdown you are using
},
success: function(response) {
//javascript and jquery code to edit your lists goes in here.
//use response to refer to what was echoed in your php script
}
});
this way, you will have dynamic dropdowns and the refined results you want
<?php
if (isset($_GET['experience'])) {
echo $_GET['experience'];
/* do mysql operations and echo the result here */
exit;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
function myFunction(value)
{
if(value!="All")
{
$.ajax(
{
type: "GET",
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { experience: value},
success: function(data) {
$('#resultDiv').html(data);
}
});
}
else
{
$('#resultDiv').html("Please select a value.");
}
}
</script>
</head>
<body>
<p>
<label for="experience">Experience :</label>
<select id="experience" name="experience" onChange="myFunction(this.value)">
<option value="All" selected="selected">All</option>
<option value="Fresher">Fresher</option>
<option value="Experienced">Experienced</option>
</select>
</p>
<div id="resultDiv">
Please select a value.
</div>
</body>
</html>
You cannot re-execute a PHP part on the same page. Rather use Ajax request to perform the action.
I have a form on my website with 3 drop-down boxes. After user select an option from each one and hit submit the data is posted to an external php file, that makes an query to MySQL and then the page is reloaded and result posted. I'd like to make this more fancy - with ajax without reloading the page. the problem is I'm completely nube. I search interned and tried a couple of examples but no result. Here is the code:
HTML FORM:
<form name="showprice" id="showprice" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="industry" id="industry" onchange="setOptions(document.showprice.industry.options[document.showprice.industry.selectedIndex].value);">
<option value="">Select Industry</option>
</select>
<select name="quality" id="quality">
<option value=" " selected="selected">Select country and industry first.</option>
</select>
<input value="Submit" type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
var frmvalidator = new Validator("showprice");
frmvalidator.addValidation("country","req","Please select country");
frmvalidator.addValidation("industry","req","Please select industry");
frmvalidator.addValidation("quality","req","Please select quality");
</script>
NOTE: I have removed the options to save space.
The external view.prices.php:
It is in another folder and now I am calling the result with
<?php include('includes/view.prices.php'); ?>
Present code is:
if(isset($_POST['submit'])) {
include ('config.php');
$con1 = mysql_connect($server, $username, $password);
if (!$con1)
{
die(<b>Could not connect: </b> . mysql_error());
}
echo'<br /><br /><table id="myTable" class="tablesorter" align="center">
<thead>
<tr>
**some table headers (8 columns)**
</tr>
</thead>
<tbody>';
$cou = $_POST['country'];
$ind = $_POST['industry'];
$qua = $_POST['quality'];
$sql = "SELECT * FROM $ind WHERE quality=$qua AND desig=$cou ORDER BY id ASC" or die('<b>Data Insert Error:</b> ' . mysql_error());
echo("<tr>
**Some table results with 8 variables taken from the MySQL database**
</tr>");
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
echo '</tbody>
</table>';
mysql_close($con1);
}}
else {
echo '<div class="grid_9">
<p><b>TIP:</b> Pick country, industry and quality from the drop-down above and hit "Submit" button to view results.</p>
</div>';
}
Any help highly appreciated.
I'd investigate jQuery. You will want to disable the default handler:
e.preventDefault();
Then with jQuery you can do something like:
$.ajax({
type: 'POST',
url: '',
data: $("#showprice").serialize(), dataType: 'json',
success: function(data){
if( data['status'] == 'success' )
{
// Do stuff here
}
}
});
That code assumes that you're going to return a json encoded string. Which jQuery can handle without any problems.
I use jQuery for this all the time.
$(function() {
$('#showprice').sumbit(function() {
$.post('includes/view.prices.php', $(this).serialize(),function(data) {
$('#idoftag').html(data);
})
});
})
With some help from a friend I've managed to do this:
1) In head of the file where is the form add:
<script type="text/javascript" src="path-to-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var working = false;
$('#id-of-form').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
//$('#submit').val('Sending..');
$.post('path-to-php-file-to-be-executed',$('#id-of-form').serialize(),function(msg){
working = false;
//$('#submit').val('Submit');
$('#id-of-div-where-result-will-be-outputed').html(msg);
});
});
});
</script>
2) After the form add the div for outputed data
<div id="output_div"></div>
3) In path-to-php-for-execution add:
if(isset($_POST['id-of-form-field-1']) && isset($_POST['id-of-form-field-2']) && isset($_POST['id-of-form-field-3'])) {
// some queries here
}
That's all
in your form, reference your current page as the action value...example, if your page is index.php. then use action="index.php" and method = "post". within the div you want the data to appear, write the php code in the correct format and enclose all this code with an if($_POST){ -your database retrieval code - } ?>. This means that your post action will call the same page which will make the condition surrounding your code to be true, hence executed. Hope this helps, it nagged me back then but i this worked.
In Notepad++, it looks like your { } are mismatched. They line up when I deleted one after the die statement and one above the else.