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.
Related
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
});
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.
I am populating the options in dropdown list using mySQL output. These output values are ranked and I want to keep only top 20 values out of 100 in it. Most of the users are interested in only one of these top 20 items. Occasionally a user may want to look something which is low ranked (21st, 22nd ... item).
I remember that I saw this in some website where if the desired option is not present, an option was there "not in the list". Selecting this option creates an input box where a user can write their value.
How this functionality can be acheived? Suggestion of any article pointing to similar problem will be highly appreciated.
Using javascript you can do this fairly easily. Since no HTML was provided, I made a sample:
HTML:
<select id="test">
<option value="0">Sample</option>
<option value="other">Other</option>
</select>
<input type="text" id="test2" style="display:none;"/>
JS:
document.getElementById("test").onchange = function() {
var textbox = document.getElementById("test2");
if (this.value == "other") {
textbox.style.display = "block";
} else {
textbox.style.display = "none";
}
}
Demo: http://jsfiddle.net/DtRhk/
I need to load the content of a PHP file using jquery based on what is selected by the user in one or more select fields.
I can use...
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice").val() );
});
...to create the variable 'choice' and when the 'first-choice' field is set by the user.
However, what if I want to use 2 variables based on two drop down selectors, to set the variable 'choice' (based on the selection of #first-choice) and choice2 (based on the selection of #second-choice).
So I would want to load a PHP file something like getter.php?choice=first-choice&choice2=second-choice
here's how i would handle this situation..
don't treat your selects as ids. use a single class for all select options, then bind .change() to all selects using a class-based selector. if you do this, you can iterate over X number of selects, use their ids as the query argument variable and their values as each query value. I created a quick demo for you on jsfiddle. I also posted the code for you below....
Here is my demo on jsfiddle
<div>
<select class="php-options" id='first-choice' name='first-choice'>
<option value='1-0'>choose</option>
<option value='1-1'>1-1</option>
<option value='1-2'>1-2</option>
<option value='1-3'>1-3</option>
<option value='1-4'>1-4</option>
<option value='1-5'>1-5</option>
</select>
</div>
<div>
<select class="php-options" id='second-choice' name='second-choice'>
<option value='2-0'>choose</option>
<option value='2-1'>2-1</option>
<option value='2-2'>2-2</option>
<option value='2-3'>2-3</option>
<option value='2-4'>2-4</option>
<option value='2-5'>2-5</option>
</select>
</div>
<div id="request-url"></div>
$(document).ready(function(){
//treat your select options with classes,
//bind change event on each select
$('.php-options').change(function(e){
var urlValues = [],
parameterArgs = "";
//loop selects to build parameters
$('.php-options').each(function(i,v){
var optValue = $(this).val(),
optId=$(this).attr('id'),
parameter = ""+optId+"="+optValue;
urlValues.push(parameter);
});
//build parameter string
parameterArgs =urlValues.join("&");
//output query
$('#request-url').text('getter.php?'+parameterArgs);
});
});
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.