Not sure I have worded the title correctly, so apologies if it's confusing!
Here is my problem
I have a dynamic select that is populated via data on an ajax call. I have a function that runs with a "change" of the first select. This works perfectly fine if the user manually selects the first dropdown items, however I am stuck on how to get this to run properly when they are editing.
This is what I want to achieve:
Load the page based on the ProdID and populate other form fields (this is happening now, so don't need help with that ;-))
Check what's pulled in from getData.php
Populate the CatID select and the mark the current selection as "selected".
If the user changes either of the select boxes, the function runs as it does currently.
Here is my function:
$(function() {
$("#topcatid").change(function() {
$("#catid").load("getData.php?choice=" + $("#topcatid").val());
});
});
Here is my html:
<select name="topid" id="topid" data-placeholder="Choose a category...">
<option value="" <?php if (!(strcmp( "", ($rsProd->getColumnVal("topcatid"))))) {echo "selected=\"selected\"";} ?>>Select</option>
<?php while(!$rsCat->atEnd()) {?>
<option value="<?php echo($rsCats->getColumnVal(" topcatid ")); ?>"<?php if (!(strcmp($rsCat->getColumnVal("topid"), ($rsProd->getColumnVal("topid"))))) {echo "selected=\"selected\"";} ?>>
<?php echo($rsCat->getColumnVal("catName")); ?>
</option>
<?php $rsCat->moveNext(); } $rsCat->moveFirst(); ?>
</select>
<select name="catid" required class="chzn-select" id="catid" style="width:350px" tabindex="2" data-placeholder="Choose a sub-category...">
<option value="">Select from above...</option>
</select>
If the user manually changes the TopID select, the function runs, goes and gets the data and populates "catid". However this is on a page that is an edit/update page so I need the function to run as per my ideal scenario above.
Your comments and code edits would be very much appreciated.
Thanks
Nick
For me you should do this in a calback function that will be executed just after the load.
$("#topcatid").change(function() {
$("#catid").load("getData.php?choice=" + $("#topcatid").val(), function() {
// Manage the old and the new catid
});
});
You can also use the jquery.ajax function that will give you more options for functions before and after the query:
$.ajax({
url: ""getData.php?choice=" + $("#topcatid").val()",
beforeSend: function( xhr ) {
// Do something
}
})
.done(function( data ) {
// Do something with data
});
Related
I have a query to select data from table(database) to show in List-view (table), than I want make code search data in list-view(table) by select-box without button submit.
this is my code in select box
<select onchange="selectrun(this);">
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
And this is my scrip
function selectrun(sel){
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
//what I return in response is a query because I want it's execute at my main page,that why I want pass it to $querr_select in php code but I don know my solution is good or not because I never do with ajax
}
});
}
This is my code in main page
$query_select = "SELECT * FROM `table`";
$result=pg_query($query_select ) or die(pg_last_error());
while($row_info=pg_fetch_array($result)){
//code for display view
}
*Note: in tab.php,I just pass id from main page to page tab.php for write a query to select in condition in where; when I alert response I get SELECT * FROM table WHERE ID ='1' And I want pass it to $query_select, is my idea but not work yet :(
I think what you are asking is how to display the result of an Ajax query. Is that correct?
<select onchange="selectrun(this);">
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<!-- A new HTML div for displaying Ajax call response: -->
<div id="response-area"></div>
<script>
function selectrun(sel){
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//Jquery sends response to browser div by setting html.
$('#response-area').html(response);
}
});
}
</script>
tab.php:
A basic concept of how you might return HTML via Ajax. This isn't great programming in terms of mixing HTML and PHP, but it it probably does what you want.
Assuming that your database table contains fields called 'field1' and 'field2', you can iterate through the array using the field names as array keys. Note that pg_fetch_array has additional parameters to select an associative array rather than a numerically indexed one.
<?php
$query_select = "SELECT * FROM `table`";
$result=pg_query($query_select ) or die(pg_last_error());
echo "<table>";
while($row_info=pg_fetch_array($result, NULL, PGSQL_ASSOC)){
echo "<tr>
<td>
$row_info[field1]
</td>
<td>
$row_info[field2]
</td>
</tr>";
}
echo "</table>";
?>
The modified code above should show you the response returned from tab.php when you change the option selected.
This is my site. The idea is when you select a country from the dd, by on change events its calls a function using AJAX, execute a query and return a json. Im using Codeigniter framework. So my question how to improve this code in order to reduce the loading time of the cities, by selectin a country ? yes i know im a little stubborn and i dont want to use counties :)
here is html code in the view:
<div class="select_zones">
Country:
<select name="country" id = 'country' style="width:220px;">
<option value = "-1" selected="selected">Select a country</option>
<?php
foreach ($countries as $key => $value) {
echo '<option value = "'.$value->id.'-'.$value->country_type.'">'.trim($value->name).'</option>';
}
?>
</select>
</div>
<div class="select_zones">
<div class="city" style ="display:none;">
City:
<select name="city" id ="city" style="width:220px;">
</select>
</div>
</div>
this is the js code:
$("#country").select2();
$("#city").select2();
$("#country").change(function(){
$("#city option").remove();
value = $(this).val();
value = value.split("-");
$.post( "register/get_cities_from_dd", { country_type: value[1]})
.done(function( data ) {
obj = JSON.parse(data);
for(var i in obj) {
$('<option>', {
text : obj[i].name,
value : obj[i].id
}).prependTo('#city');
}
});
$(".city").show();
});
this is the function from the controller:
public function get_cities_from_dd(){
$country_type = $_POST['country_type'];
$cities = $this->register_model->get_cities($country_type);
echo json_encode($cities);
}
and finally the model:
public function get_cities($country_type){
return $this->db->query("SELECT id,name FROM cities WHERE city_type = '".$country_type."' ORDER BY `name` DESC ")->result();
}
You're loading way too much data, there is no way to improve this (other than changing it completely like suggested in the comments to your question). Also note that https://codereview.stackexchange.com/ would have been a better place for this question.
The best solution to your problem would be e.g. Elasticsearch or any equivalent software that was designed to auto-complete huge amounts of data. The user could simply start typing the name of the city and the software could complete it. I'd use a text field, wait for at least two characters and insert a e.g. 250ms timeout (request animation frame) between each key stroke before hitting the server again. But I'd still limit the number of results to e.g. 25 or 100 if you will.
If you still want to stick to your current implementation and don't want to listen to the many comments that were given to your question (like the serious SQL injection problem) go for prepared HTML files.
We have a directory countries that contains the options for each country, totally rendered, no need to do anything other than loading from the server:
/countries/at.html
/countries/us.html
Current HTML document:
<select id="country" name="country">
<option value="at">Austria</option>
<option value="us">United States</option>
</select>
<select id="cities" name="cities">
<option selected>Please Select a Country</option>
</select>
Our jQuery:
$("#country").change(function (event) {
$("#citites").load("/cities/" + this.value + ".html");
});
Still, way too much for the browser.
I am trying to get the values for the next drop-down from a database, which will be dependent on two previous drop-downs. The values for first two drop-downs are listed in the file itself. I want the second drop-down to be enable after selecting values from first, and similarly for third after second. Kindly help.
HTML code below:
<form>
<select id="branch" name="branch" class="form-control" onchange="showUser(this.value)">
<option value="">Select</option>
<option value="1">Civil</option>
<option value="2">Computer</option>
<option value="3">Mechanical</option>
<option value="4">Electronics and Telecommunications</option>
<option value="5">Electrical and Electronics</option>
<option value="6">Information Technology</option>
</select>
<select id="semester" name="semester" class="form-control" disabled>
<option value="1">I</option>
<option value="2">II</option>
<option value="3">III</option>
<option value="4">IV</option>
<option value="5">V</option>
<option value="6">VI</option>
<option value="7">VII</option>
<option value="8">VII</option>
</select>
</form>
jquery is:
<script>
$(document).ready(function(){
document.cookie = "s =hello" ;
console.log('hello');
$("#semester").attr("disabled", true);
$("#branch").change(function(){
$("#semester").attr("disabled", false);
$b = $('#branch').val();
$("#semester").change(function(){
$s = $('#semester').val();
$("#sub_code").attr("disabled", false);
console.log($s);
if($s!=1||$s!=2)
$s = $b+$s;
<?php
$s= $_COOKIE['s'];
$sql = "SELECT * FROM subjects WHERE sem_code=`$s`";
?>
});
});
});
</script>
I did not run the query since it is not assigned properly yet.
You can't include php code in javascript , the first is executed on the server side, the second is executed on the client side which means that you can't re-execute only if you resend a request to the server, obviously this is usually done by submitting forms, BUT sometimes -like in your case- we don't want to reload the whole page for each request ! and for this purpose we use AJAX
ajax sends post/get request to a specified php page which does the desired server-side tasks (updating data in the database, selecting some results from database, dealing with sessions maybe, etc...)
try something like this:
var pathurl='/path/to/your/php/file';
var params={}; //the parameters you want to send
params['semester']=$s;
var requestData= $.ajax({
type: 'POST',
url: pathurl,
cache: 'false',
data: params,
dataType: "json",
beforeSend: function () {
//here you can begin an animation or anything...
},
complete: function () {
//here you can stop animations ...
},
success: function (response) {
console.log(response); //check your console to verify the response
//loop other elements inside response
$.each(response, function (index, resultArray) {
//do something : in your case append to dropdown a new option
});
}
});
requestData.error(function () {
alert("error");
});
you should create a php file with the path specified in the above code, and there you can extract what you need from the database table, store values in an array and finally use:
echo json_encode($resultArray);
hope this was helpful
I have created a script which fills the second combobox with the value of the first one. But it is not quite what I want to do. I want to fill the second combobox with the result of a SQL query based on the item which was selected in the first combobox.
Here is my javascript:
<script type="text/javascript">
function selectDropdown(){
var dropdownValue=document.getElementById("dropdown").value;
$('option[value=st]').text(dropdownValue);
}
</script>
first combobox:
<select id="dropdown" name="dropdown" onchange="selectDropdown()">
<option value="dd">--take an option--</option>
<?
$standard = Env::value('standard');
if (!$status)
$statement = "select code from standard";
foreach ($db->query($statement )->fetchall() as $row)
echo "<option".($row == $standard ? ' selected ' : '').">$row[0]</option>";
?>
</select>
and the second one in which I want to show the result of the query: $q= select request.code from request inner join standard on ( request.standard_id=standard.id) where standard.code=$st.
<select name='st' class='txt'>
<option value="st"><? echo $st; ?></option>
</select>
Can anyone give me a hint where I should put query execution? Or just point me what I am doing wrong?
Use jQuery's ajax call to make a request to the server each time when first dropdown selection has been changed. On the server side create a script which will receive that request and return corresponding records for 2nd dropdown in JSON format, which then can be easily processed by javascript. For using ajax see this link: http://api.jquery.com/jQuery.ajax/
It will be like:
jQuery.ajax({
method: "POST",
url: "http://domain.com/path/to/script.php",
data: value_of_selected_item_from_first_dropdown,
success: function(response) {
// Set 2nd dropdown values to those received via response
}
dataType: "json",
});
i have two select boxes and a link.i select one value from the first select box and another from the second select box and click on the link.the values have to get stored in an array each time without the previous value getting replaced.how can i do this without using multiple select box?
<select name="sq" id="sq" >
<option value=""></option>
</select>
<select name="as" id="as" >
<option value=""></option>
</select>
sorry forgot to mention..its in codeigniter
You can use change event to store the selected values.
Html
<select name="sq" id="sq" >
<option value="1">1</option>
<option value="2">2</option>
</select>
Javascript
arrSelected = []
$("#sq").change(function(){
arrSelected.push($(this).val());
});
With the added info from the comments, here is my suggestion:
HTML:
<div class="selectLine">
<select name="sq[]" >
<option value=""></option>
</select>
<select name="as[]" >
<option value=""></option>
</select></div>
<a id="addOption">
JavaScript:
$('#addOption').click(function(){
$('.selectLine').last().after($('.selectLine').outerHtml());
$('.selectLine').last().prev().hide();
});
PHP receiving the post:
foreach($_POST['sq'] as $key=>$name){
//Make sure you stay consistent with the keys to make sure the 2 values were entered at the same time.
echo '<p>'.$name.' is a '.$_POST['as'][$key].'</p>';
}
Adding [] to the end of the name of inputs will place them in arrays. But you need more than one if you want more than one value...
You can remove $('.selectLine').last().prev().hide(); to keep the lines displayed to the user so he can change the values if you want.
This would send the data with AJAX without page refresh:
Use for the link Submit data
Then add the following jQuery script: (you need to include jQuery library first)
$('#submitlink').click(function(event) {
event.preventDefault(); // Stops default link behaviour on click
$.ajax({
url: "yourphp.php", // where to send
data: 'sq=' + $('#sq').val() + '&as=' + $('#as').val(), // select values
type: "POST",
success: function(data){
// If you want to confirm
alert('Added');
}
});
});
Then in your php script store the $_POST data in either a database or session...
Session example, storing:
<?php
session_start();
if (!isset($_SESSION['sq']) $_SESSION['sq'] = array();
$_SESSION['sq'][] = $_POST['sq'];
if (!isset($_SESSION['as']) $_SESSION['as'] = array();
$_SESSION['as'][] = $_POST['as'];
?>
To retrieve the results you could use:
<?php
session_start();
if (isset($_SESSION['sq']) print_r($_SESSION['sq']);
if (isset($_SESSION['as']) print_r($_SESSION['as']);
?>
But of course this could be elaborated.
If you wish to have persistence in your website, then I would recommend looking into PHP Cookies.
In your case, you want to store an array, persistently, so you have a few options.
Either implement a HTML Hidden Element or you can use Serialization to store the array inside a cookie.