How to get auto response value by using Two Drop-Down List in PHP & Ajax? - ajax

How to get the final value in AJAX using two drop-down value,
Koluextension.php
<html>
<head>
<title> Upgrade Cost</title>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select onchange="getvalue()" id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select onchange="getvalue()" id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
</html>
upgratedcost.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){
echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));
}
else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
calculatecost.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){
echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));
}
else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
Expected Output:
If customer choose: I have -> one and I want -> two the cost should
be $10 as an Auto response to show to the customer. [Every combination has its own cost]

I have done some changes to your code. And add some Ajax to this and also created separate PHP code, you can get basic idea using this code example.
Html page -
<html>
<head>
<title> Upgrade Cost</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
<button id="btn_check_value">Check for value</button>
<script>
$(document).ready(function(){
$('#btn_check_value').on('click',function(){
var old_val = $("#old option:selected").val();
var new_val = $("#new option:selected").val();
$.ajax({
method: "POST",
url: "value_calculate.php",
data: { old: old_val, new: new_val }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
})
})
</script>
</html>
PHP page code -
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));}else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
Here what happen is, once user do the selections user have to click the "Check for value" button and once user click on that button it'll make Ajax request to PHP page "value_calculate.php" and php code return value according to user selection.
This is not complete solution but you can get basic idea and improve this code according to you.
Thanks,
Tharanga.

You can try this solution:
1) Modify Your HTML like this:
<html>
<head>
<title> Upgrade Cost</title>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select onchange="getvalue()" id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select onchange="getvalue()" id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
</html>
2) Add this JavaScript function to your page:
function getValue() {
var cost1=$('#old').val();
var cost2=$('#new').val();
$.ajax({
url: '{{ url("calculateCost.php") }}',
type: 'get',
//async:true,
data: {
oldId: cost1,
NewId: cost2,
},
dataType: 'json',
success: function(json) {
//you can calculate total cost on server and show updated cost using
//jquery anywhere on your form
//do whatever you wanted to do
//you can easily manipulate DOM using jQuery
},
error : function(xhr, textStatus, errorThrown ) {
//in case ajax call error
}
});
}
}
}
Haven't tested this code. Please make necessary changes. If you still don't know what is going on then I would recommend you to go through a detailed tutorial in order to understand the concepts first and then code. e.g. https://www.w3schools.com/php/php_ajax_intro.asp

Issues (based from your post in daniweb website):
There is no input field with an id of est_shi_val
Looking at your code, you want to use both the old and new select fields, when changed will put the result to a hidden input field. But the result will only return if both the old and new have selected options. Is this what you want? Or at least one of them should be selected, and the result will return?
Use a database to look-up for conditions instead of manually creating if-else conditions
Instructions:
You may remove first your onchange attribute/call in your old and new select fields.
AJAX Call:
$("#old, #new").change(function(){ /* WHEN YOU CHANGE THE VALUE OF THE OLD OR NEW INPUT FIELD */
var old = $("#old").val(),
newval = $("#new").val();
$.ajax({ /* TRIGGER THE AJAX CALL */
type: "POST", /* TYPE OF METHOD TO USE TO PASS THE DATA */
url: "ajax_ship_data.php", /* PAGE WHERE WE WILL PASS THE DATA */
data: {'old':old, 'new':newval}, /* THE DATA WE WILL BE PASSING */
dataType: 'json',
success: function(result){ /* GET THE RETURNED DATA */
$("#results").html(result.message); /* THE RETURNED MESSAGE WILL BE SHOWN IN THIS DIV, PROVIDED THAT YOU HAVE A DIV WITH AN ID OF "results" */
$('#shipping_weight').val(result.weight); /* ASSUMING THAT YOU HAVE A HIDDEN INPUT FIELD WITH AN ID OF "shipping_weight" */
}
});
});
Then at your ajax_ship_data.php:
$shipping_weight = 0;
$message = 'Please select an option from both fields.';
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
//part 1
if($old == 'three_compact' && $new == 'five_compact'){
$shipping_weight = 10;
$message = 'Shipping weight is 10.';
}
/** REST OF IF-ELSE CONDITIONS **/
}
echo json_encode(array('message' => $message, 'weight' => $shipping_weight));
Other Option: No AJAX
You may also do this without using AJAX since you're manually creating conditions:
$("#old, #new").change(function(){
var old = $("#old").val(),
newval = $("#new").val();
if(old=='three_compact' && newval=='five_compact'){
$("#results").text('10');
}
/* REST OF IF-ELSE CONDITIONS */
});
Take a look at this fiddle.

Related

Populate dynamic dropdown, Codeigniter

I'm trying to make a dynamic dropdown with Codeigniter but I'm having trouble getting the values on the next dropdown. When I select and option on the first dropdown, the second dropdown is not populated:
I'm also not familiar at using AJAX, I only write the script based on what I searched so please teach me what to do to make the dynamic dropdown work.
This is my Model:
public function category()
{
$this->db->order_by("category", "ASC");
$query = $this->db->get('categories');
return $query->result();
}
function get_subcategory($parent_id)
{
$this->db->where('parent_id', $parent_id);
$this->db->order_by('sub_category', 'ASC');
$query = $this->db->get('sub_categories');
$output = '<option value="">Select Sub-Category</option>';
foreach ($query->result() as $row) {
$output .= '<option value="' . $row['id'] . '">' . $row['sub_category'] . '</option>';
}
return $output;
}
My Controller:
public function category()
{
$data['title'] = 'List of Category';
$this->load->view('../admin/template/admin_header');
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/category/category', $data);
$this->load->view('../admin/template/admin_footer');
}
function get_subcategory()
{
if ($this->input->post('parent_id')) {
echo $this->Admin_model->get_subcategory($this->input->post('parent_id'));
}
}
View:
<div class="form-group">
<label for="" class="control-label">Category</label>
<select name="category" id="category" class="custom-select select2" required>
<option value="">- Select Category -</option>
<?php
foreach ($category as $row) {
echo '<option value="' . $row->id. '">' . $row->category . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Sub Category</label>
<select name="sub_category" id="sub_category_id" class="custom-select select2" required>
<option value="">- Select Sub Category -</option>
</select>
</div>
And script:
$(document).ready(function() {
$('#category').change(function() {
var parent_id = $('#category').val();
if (parent_id != '') {
$.ajax({
url: "<?php echo base_url(); ?>admin/get_subcategory",
method: "POST",
data: {parent_id:parent_id},
success: function(data) {
$('#sub_category_id').html(data);
}
});
} else {
$('#sub_category_id').html('<option value="">Select Sub Category</option>');
}
});
});
Your question doesn't mention it, but your CSS suggests your selects are actually using Select2. When you initialise a select as a Select2, it makes a copy of the initial HTML, and adds styling and JS to it, and it is the copy that you see and interact with. The original HTML is no longer visible or used at all.
So if you later come along and modify that original HTML, it will have no effect on the Select2 you already generated and can see an interact with on the page.
One solution is to reinitialise that Select2 after you modify it.
UPDATE
I've added a working snippet, with some hard-coded HTML to simulate what your AJAX returns. Click run to try it.
$(document).ready(function () {
// Initialise Select2s
$('.select2').select2();
// Fake HTML, simulate what your AJAX returns
let fakedHTMLResponse = '<option value="water">Water</option><option value="juice">Juice</option><option value="beer">Beer</option>';
$('#category').change(function () {
var parent_id = $('#category').val();
// console.log('parent_id', parent_id);
if (parent_id != '') {
// Your AJAX call happens here, let's simulate the success
// response it gets back, and handle it the same way.
$('#sub_category_id').select2('destroy')
.html(fakedHTMLResponse)
.select2();
} else {
$('#sub_category_id').html('<option value="">Select Sub Category</option>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="category" class="select2" name="food">
<option value="">- Select Category -</option>
<option value="fruits">Fruits</option>
<option value="vegetables">Vegetables</option>
<option value="cakes">Cakes</option>
</select>
<select id="sub_category_id" class="select2" name="drink">
<option value="">- Select Sub Category -</option>
</select>
Note:
Convention is to use GET when retrieving data, and POST for changing data. Your AJAX calls are just retrieving data to display, so really should be GET;
If you are going to use a jQuery selector more than once, it makes sense to cache them. Eg in the above code you should do something like:
let $category = $('#category');
let $sub = $('#sub_category_id');
// And then every time you need to use that selectors, use the variable, eg:
$category.select2();
$category.change(function ...
$sub.select2('destroy');
// etc
In your success response write this and remove the else from down there.
success: function(data) {
$('#sub_category_id').append('<option value=>Select Sub Category</option>');
for (var i=0; i<data.length; i++) {
$('#sub_category_id').append($('<option>', {
value: data[i].id,
text : data[i].sub_category
}));
}
}
get AJAX response in the array from your controller and then run this through javascript like this.
id is id from your db
and sub_category is sub_category coming from your db
with ajax response array.

How to retrieve selected option value?

Hi guys new to laravel here! i am using selected option drop down list The First Select contains the countries and the second one has the states, now When i try to store the in database i am not getting the proper selected state instead i am always getting the first state in the second select Option!! i am using query Builder.
This is How i am retrieving Countries and states
public function store(Request $request)
{
$country = DB::table("countries")->where("id",$request->daira);
$state = DB::table("states")->where("country_id",$request->daira);
$daira = $country->get()->first()->name;
$impact = $state->get()->first()->commune;
dd($impact);
}
Note: dd($impact); Should be retrieving the selected state, instead it's retrieving the first value on the Selection List
So my Question is How do i get it to retrieve The proper Selected state !? Hope my question is clear Thanks in Advance.
Updated:
In the First Select option I have Countries name and in the second option i have
states each country has maximum 3 states, let's say Country A has 3 States A1,A2 and A3 And i want to select State A2 from the select option Value and instead of getting A1 by default like my case in the Question
Updated: I Am using VueJs
This is The form code
<template>
<div class="modal-body">
<div class="form-group">
<select name="direction" class="form-control">
<option value="">Selctionner Direction</option>
<option value="ENERGIE">ENERGIE</option>
<option value="HYDRAULIQUE">HYDRAULIQUE</option>
<option value="ENVIRONNEMENT"> ENVIRONNEMENT</option>
<option value="AMENAGEMENT">AMENAGEMENT</option>
<option value="P.T.T">P.T.T</option>
<option value="TOURISME">TOURISME</option>
<option value="TRANSPORT">TRANSPORT</option>
<option value="TRAVAUX PUBLICS">TRAVAUX PUBLICS</option>
<option value="EDUCATION">EDUCATION</option>
<option value="ENSEIGNEMENT SUPERIEUR">ENSEIGNEMENT SUPERIEUR</option>
<option value="URBANISME">URBANISME</option>
<option value="FORMATION PROFESSIONNELLE">FORMATION PROFESSIONNELLE</option>
<option value="SANTE">SANTE</option>
<option value="JEUNESSE-SPORTS CULTURE">JEUNESSE-SPORTS CULTURE</option>
<option value="PROTECTION SOCIALE">PROTECTION SOCIALE</option>
<option value="INFRASTRUCTURES ADMINISTRATIVES">INFRASTRUCTURES ADMINISTRATIVES</option>
<option value="HABITAT">HABITAT</option>
<option value="COMMERCE">COMMERCE</option>
<option value="LOGEMENT">LOGEMENT</option>
<option value="LOCAUX A USAGE PROFESSIONNELE">LOCAUX A USAGE PROFESSIONNELE</option>
<option value="FORET">FORET</option>
</select>
</div>
<div class="form-group">
<label>Selctionner Daira:</label>
<select name="daira" class='form-control' v-model='country' #change='getStates()'>
<option value='0' >Select Country</option>
<option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
</select>
</div>
<div class="form-group">
<label>Selctionner Commune:</label>
<select name="impact" class='form-control' v-model='state'>
<option value='0' >Select State</option>
<option v-for='data in states' :value='data.id'>{{ data.commune }}</option>
</select>
</div>
<div class="form-group">
<label >Intitule :</label>
<input type="text" class="form-control" name="intitule" required>
</div>
</div>
</template>
And this is My Script
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data(){
return {
country: 0,
countries: [],
state: 0,
states: []
}
},
methods:{
getCountries: function(){
axios.get('/api/getCountries')
.then(function (response) {
this.countries = response.data;
}.bind(this));
},
getStates: function() {
axios.get('/api/getStates',{
params: {
country_id: this.country
}
}).then(function(response){
this.states = response.data;
}.bind(this));
}
},
created: function(){
this.getCountries()
}
}
</script>
can you post the result of dd($request->all()) ?
assuming your select name is daira and impact, you should be able to get the posted value with this:
public function store(Request $request)
{
$daira = $request->daira;
$impact = $request->impact;
}
I understand your issue first state returns because of when you passed country id it returns all the state related this country.
So that you need to pass state Id from state drop-down.
<select name="impact">
<option value="id">{{ STATE NAME }} </option>
</select>
And then you need to pass that state id in controller.
$state = DB::table("states")->where("id",$request->impact);
Hope you understand your queries
I assume $request->daira is country ID
public function store(Request $request)
{
//here you selected a country with provided country ID
//this returns Query Builder object
$country = DB::table("countries")->where("id",$request->daira);
//here you are returning all the states where the country_id is
//the provided country ID
//Note that this returns all the states (Query Builder object)
$state = DB::table("states")->where("country_id",$request->daira);
//You return `Illuminate\Support\Collection` then you got the first item
//from collection
$daira = $country->get()->first()->name;
//You returned all the states `Illuminate\Support\Collection`
//and you picked the first state from the collection,
//which is likely the first item in your
//form select field options
$impact = $state->get()->first()->commune;
dd($impact);
}
Because you didn't specify state_id, you will always get lists of all the states under the given country.
I assume table relationship is Country -> hasMany -> State
You need to add state_id as constraint, so only one state is picked
$state_id = $request->state
I assume you have state in your form
$state = DB::table("states")
->where("country_id",$request->daira)
->where('id', $state_id)
->first();
$impact = $state->commune

Laravel Ajax dropdown example

can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax.
i have done it without ajax, but i don't know how to do with ajax.
without ajax:
<select name="nation_id" class="custom-select" >
<option selected value=" ">Choose...</option>
#foreach($nations as $nations)
<option value="{{#$nation_id}}" {{#$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{#$nations->nation}}</option>
#endforeach
Controller:
$nations = nation::all();
<select class="form-control" name="nation_id" id="nation_id">
<option value="">Select nation</option>
#foreach($nations as $nation)
<option value="{{ $nation->nation_id }}">{{ $nation->nation_name }} </option>
#endforeach
</select>
<select class="form-control" name="teacher" id="teacher">
</select>
now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getTeacher)}}/"+nid,
success:function(res)
{
if(res)
{
$("#teacher").empty();
$("#state").append('<option>Select Teacher</option>');
$.each(res,function(key,value){
$("#teacher").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
</script>
now in controller file;
public function getTeacher($id)
{
$states = DB::table("teachers")
->where("nation_id",$id)
->pluck("teacher_name","teacher_id");
return response()->json($teachers);
}
And last for route file:
Route::get('/getTeacher/{id}','TeachersController#getTeacher');
Hope this will work..
Good Luck...
Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController#method');
Create a method in your controller for the above route-
public function method()
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations)
}
Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>
If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
And then add this script in your HTML to fetch the nation list on page load-
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id); // This will select the default value
});
});
</script>

Thymleaf <select><option> update using ajax

I've got two select option. I want to change the second select options value based on the first option value. I'm using thymleaf as template engine.
When the first select is being selected, I make an ajax call to the controller and get the value as a list. I'm getting the value from ajax call but couldn't able to append the value to the second select option. console.log() shows the option value correctly but it didn't update HTML code.
First Select option:
<select id="brand" th:onchange="changeBrand()" class="form-control">
<option th:selected="true" th:disabled="true"
th:text="'Please Select A Brand'"></option>
<option th:each="brand : ${Calculator}"
th:value="${brand}"
th:text="${brand}">Choose Brand</option>
</select>
Second Select:
<div class="input-group">
<select id="model" class="form-control">
<option th:selected="true" th:disabled="true"
th:text="'Please Select A Model'"></option>
</select>
</div>
Ajax:
<script th:inline="javascript">
/*<![CDATA[*/
function changeBrand() {
var selectedBrand = $( "#brand option:selected" ).text();
$.ajax({
url:"duty/getAllModel",
data:{brand:selectedBrand},
type:"POST",
success:function(data){
// Resetting select option
var select = document.getElementById("model");
select.options.length = 0;
options = data.options;
for (var i = 0; i < data.length; i++) {
select.options[select.options.length] = new Option(data[i],i);
}
for (var i = 0; i < select.childElementCount; i++) {
console.log(select.options[i]);
}
},error:function (error) {
console.log(error);
}
});
}
/*]]>*/
Console.log() value:`
Nokia
Samsung`

AJAX form executed by onblur OR change event

I have a form where the user will enter a number into a text field. Then, select another number from a dropdown menu. I want the AJAX to execute each time they go from field to field. This is so that it does a calculation in real-time.
I would imagine the text field would be using "onblur" and the dropdown using "change" or "onchange"... but how do I write the script to do EITHER depending on which field they are currently on? Can you set it to do both?
EDIT: New attempt with new variable labels.
<script type="text/javascript">
function postData(){
var widthX = $('#width_str').val();
var heightX = $('#height_str').val();
var prodidX = $('#prodid').val();
var roomX = $('#room_str').val();
$.post('db_query.php',{widthX:widthX, heightX:heightX, prodidX:prodidX, roomX:roomX},
function(data){
$("#search_results").html(data);
});
}
$(function() {
$("#lets_search").bind('submit',function() {postData()});
$("#room_str").bind('change', function() {postData()});
$("#width_str").bind('change', function() {postData()});
$("#height_str").bind('change',function() {postData()});
});
</script>
Part of the form here....
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
<input type="hidden" value="1" value="<?php echo stripslashes($_GET['prodid']); ?>" name="prodid" id="prodid">
room name:
<select name="room_str" id="room_str">
<option value="Dining">Dining</option>
<option value="Bathroom">Bathroom</option>
<option value="Kitchen">Kitchen</option>
</select>
height:
<select name="height_str" id="height_str">
<option value="30">30"</option>
<option value="31">31"</option>
<option value="32">32"</option>
<option value="33">33"</option>
<option value="34">34"</option>
<option value="35">35"</option>
<option value="36">36"</option>
<option value="37">37"</option>
</select>
<br>
width:
<select name="width_str" id="width_str">
<option value="30">30"</option>
<option value="31">31"</option>
<option value="32">32"</option>
<option value="33">33"</option>
<option value="34">34"</option>
<option value="35">35"</option>
<option value="36">36"</option>
<option value="37">37"</option>
</select>
<input type="submit" value="send" name="send" id="send">
</form>
The php page that processes the data...
<?php
include('db_pbconnection.php');
$tax = .06;
$tax2 = 1.06;
$grandtotal = 50;
$query = mysql_query(" SELECT * FROM price_dimensions WHERE prodid = '".$_POST['prodidX']."' AND height >= '".$_POST['heightX']."' AND width >= '".$_POST['widthX']."' ORDER BY height ASC, width ASC LIMIT 1 ");
echo '<div>';
while ($data = mysql_fetch_array($query)) {
echo '
<div style="background-color:pink;">
<div style="clear:both; font-size:18px;">height: '.$data["height"].'</div><br>
<div style="clear:both; font-size:18px;">width: '.$data["width"].'</div>
<div style="clear:both; font-size:18px;">unit price: '.$data["price"].'</div>
<div style="clear:both; font-size:18px;">tax: '.(($data["price"])*($tax)).'</div>
<div style="clear:both; font-size:18px;">grand total:'.(($data["price"])*($tax2)).'</div>
</div>';
}
echo '</div>';
?>
If I understand you correctly, you can call the AJAX from any area by moving the code into a separate function and binding any event to that function.
function postData(){
var value = $('#str').val();
var valueH = $('#strH').val();
var prodid = $('#prodid').val();
$.post('db_query.php',{valueH:valueH, value:value, prodid:prodid},
function(data){
$("#search_results").html(data);
});
return false;
}
$(function() {
$("#lets_search").bind('submit',function() {postData()});
$("#strH").bind('change', function() {postData()});
$("#str").bind('blur',function() {postData()});
});

Resources