Ajax concatenate select and total record query - php

I've a php page where there is a ajax concatenate select and a div with the total number of records in the table tb1
HTML
<p>
<select name="model" id="model">
<?php echo $myclass->selModel(); ?>
</select>
</p>
<br />
<p>
<select name="year" id="year">
<option value=""> </option>
</select>
</p>
<p>
<div id="total"><?php echo $myclass->recordNum();?></div>
</p>
JS
// VARS
var wait = '<option>Waiting</option>';
var select = '<option value="">Select</option>';
// CAT_1 //
$("select#model").change(function(){
var model = $("select#model option:selected").prop("value");
$("select#year").html(wait);
$.post("ajax-php/select-concat.php", {model:model}, function(data){
switch (data) {
case select:
$("select#year").html("");
return false;
default:
$("select#year").prop("disabled", false);
$("select#year").html(data);
return false;
}
});
});
PHP - select-concat.php
if(isset($_POST['model']))
{
echo $myclass->selYear();
die;
}
MY PHP CLASS
public function selYear() {
$result = $this->db->mysqli->query
("SELECT year FROM tb1 WHERE model='$_POST[model]");
$year = '<option value="">Select</option>';
while($row = $result->fetch_assoc()) {
$year .= '<option value="' . $row['year'] . '"';
$year .= '>' . $row['year'] . '</option>';
}
return $year;
}
private function recordNum(){
$result = $this->db->mysqli->query
("SELECT * FROM tb1 WHERE something ");
$numrec = $result->num_rows;
return $numrec;
}
My goal is to update the number of records with ajax every time I run a concatenate select. How could I do that? Thanks

You should use json_encode() on select-concat.php to return two results.
if(isset($_POST['model']))
{
$years = $myclass->selYear();
$total = $myclass->recordNum();
$arr = array('years' => $years, 'total' => $total);
echo json_encode($arr);
die;
}
You must add POST model value to recordNum() function (or pass it with an argument).
Then...
$("select#model").change(function(){
var model = $("select#model option:selected").prop("value");
$("select#year").html(wait);
$.post("ajax-php/select-concat.php", {model:model}, function(data){
var json_data = $.parseJSON(data);
switch (data) {
case select:
$("select#year").html("");
$("#total").html(0);
return false;
default:
$("select#year").prop("disabled", false);
$("select#year").html(json_data.years);
$("#total").html(json_data.total);
return false;
}
});
});

Related

Showing readily selected data in cascade drop-down list

I have made a cascade dropdown list for choosing country and city (depending on the country chosen) for users to update their profiles.
In the earlier version where users choose country and city works ok. But since this will be a update profile page, I want to show already selected data if the data is not null.
It works ok for the country selection but couldn't figure out how to implement this already selected data to trigger the javascript because second dropbox only triggered with a selection on the first dropdown.
Any help is appreciated!
Here is the javascript part
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(countryId) {
var strURL="findCountry.php?country="+countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Here is the php part:
<?php
$username = $_SESSION[ 'username' ];
$sql = $conn->query( "SELECT * FROM users WHERE username='$username' " );
if ( $sql->num_rows > 0 ) {
// output data of each row
while ( $info = $sql->fetch_assoc() ) {
echo '
<select id="country" name="country" onchange="getCity(this.value)" required>
<option value="" selected disabled hidden>Country</option>';
$sql2 = $conn->query( "SELECT * FROM world_countries ORDER BY country_name ASC" );
// output data of each row
if ( $info[ 'country' ] != null ) {
echo '<option value="' . $info[ "country" ] . '" selected>' . $info[ "country" ] . '</option>';
}
while ( $row = $sql2->fetch_assoc() ) {
echo '<option value="' . $row[ "cc_iso" ] . '">' . $row[ "country_name" ] . '</option>';
}
echo '<div id="citydiv"><select name="city"><option>Select Country First</option></select></div>';
}}
?>
And here is the findCountry.php:
<?
require_once("config.php");
$country=$_GET['country'];
$sql=$conn->query("SELECT * FROM world_cities WHERE id='$country' ORDER BY full_name_nd ASC");
if ( $sql->num_rows > 0 ) {
echo '
<select name="cities">
<option>Select City</option>';
while($row=$sql->fetch_assoc()) {
echo '<option value="'.$row['full_name_nd'].'">'.$row['full_name_nd'].'</option>';
}
echo '</select>';
} else {
echo 'error';
}
$conn->close();
?>
You should add a second GET parameter to your ajax request to get the options with one already selected, like:
function getCity(countryId, selected = "none") {
var strURL="findCountry.php?country="+countryId+"&selected="+selected;
var req = getXMLHTTP();
//...
In your PHP add selected to the correct option:
<?
require_once("config.php");
$country=$_GET['country'];
$selected = $_GET['selected'];
$sql=$conn->query("SELECT * FROM world_cities WHERE id='$country' ORDER BY full_name_nd ASC");
if ( $sql->num_rows > 0 ) {
echo '
<select name="cities">
<option>Select City</option>';
while($row=$sql->fetch_assoc()) {
$status = "";
if($selected!="none" && $row['full_name_nd'] == $selected) //apply selection
$status = "selected";
echo '<option value="'.$row['full_name_nd'].'" '.$status.'>'.$row['full_name_nd'].'</option>';
}
echo '</select>';
} else {
echo 'error';
}
$conn->close();
Now you should be able to call your function passing the selected city at page load

I have three selects on my form. Each depends on the values of the previous one

I have three selects on my form.
Each depends on the values of the previous one.
I mean there is drop-down list with categories, car brand and car model.
The list with car brand must show the brands of chosen category. Also car model have consist of models of chosen brand.
The form HTML, the server language is PHP, I want to use Ajax JQUERY to get the value of the select.
Help please how it should be?
You should do something like this:
jQuery(function($) {
var brands = {
'Trucks': ['Ford', 'Chevrolet'],
'Cars': ['Honda', 'Volkzwagen'],
}
var models = {
'Ford': ['Model1', 'Model2'],
'Chevrolet': ['Model3', 'Model4'],
'Honda': ['Model5', 'Model6'],
'Volkzwagen': ['Model7', 'Model8'],
}
var $brands = $('#brand');
var $models = $('#model');
$('#category').change(function () {
var category = $(this).val(), brnds = brands[category] || [];
var html = $.map(brnds, function(brnd){
return '<option value="' + brnd + '">' + brnd + '</option>'
}).join('');
$brands.html('<option>Select</option>'+html)
$models.html('');
});
$('#brand').change(function () {
var brand = $(this).val(), mdls = models[brand] || [];
var html = $.map(mdls, function(mdl){
return '<option value="' + mdl + '">' + mdl + '</option>'
}).join('');
$models.html(html)
});
});
Check this JSFiddle: http://jsfiddle.net/minijavi19/2pza5/1908/
Of course if you want to use Ajax you should set your variables with it.
Thanks to everybody who paid attention to my question!!! But I want share with you with my solution. There ara 3 files: index.php, ajax-queries.js, php-funcs.php.
//index.php
$categories = $mysqli->query("SELECT category_id, category_name FROM
categories") or die($mysqli->error);
<form action="../../php/admin_funcs.php" method="post">
<select id="cat_slc" class="lists" name="category" >
<option disabled selected>Выберите категорию</option>
<?php
while ($crow = $categories->fetch_assoc())
{
echo "<option
value='".$crow['category_id']."'>".$crow['category_name']."
</option>";
}
?>
</select>
<select id="marka_slc" class="lists marka-select" name="marka" >
<option disabled selected>Выберите марку</option>
</select>
<select id="model_slc" class="lists model-select" name="mode">
<option disabled selected>Выберите модель</option>
</select>
</form>
//ajax-queries.js
$('#cat_slc').change(function () {
var cat_id = $(this).val();
var url = '../../php/data_functions.php';
$('#marka_slc').load(url + '#mark-block', {cat_id: cat_id}, function () {
$('.marka-select').fadeIn('slow');
});
});
$('#marka_slc').change(function(){
var mark_id = $(this).val();
var url = '../../php/data_functions.php';
$('#model_slc').load(url + '#model-block', {mark_id: mark_id}, function (){
$('.model-select').fadeIn('slow');
});
});
//php-funcs.php
<?php
require_once "db_connect.php";
function GetMarkas(){
global $mysqli;
$category_id = $_POST['cat_id'];
$query = "SELECT marka_id, marka_name FROM marka WHERE category_id =
'".$category_id."'";
$result = $mysqli->query($query);
$data = '';
while ($row = $result->fetch_assoc()){
$data .= "<option value='".$row['marka_id']."'>".$row['marka_name']."
</option>";
}
return $data;
}
function GetModels(){
global $mysqli;
$mark_id = $_POST['mark_id'];
$query = "SELECT model_id, model_name FROM model WHERE marka_id=
'".$mark_id."'";
$result = $mysqli->query($query);
$data = '';
while ($row = $result->fetch_assoc()){
$data .= "<option value='".$row['model_id']."'>".$row['model_name']."
</option>";
}
return $data;
}
if(isset($_POST['mark_id'])){
echo"<div id='model-block'>" . GetModels() . "</div>";
}
else if(isset($_POST['cat_id'])){
echo"<div id='mark-block'>" . GetMarkas() . "</div>";
}

Dropdown Options Based on Previous Selection

I'm hoping this is a simple solution. I am trying to make the first drop down determine the options available for the second. In my database, each flavor for the drink type has "type_id" column set as an integer (i.e. 1,2,3). The integers are meant to reflect the category in which they belong. Is it possible/make sense to base the available options for the second drop down off of the "type_id" that I determined?
I was hoping to accomplish this by using PHP, but I am not opposed to jQuery. I am not very well versed in one over the other. Thank you for your help in advance!
<?php
require "db-connect.php";
$dtype = "SELECT name FROM drinktype";
$typedata = mysqli_query($connection, $dtype);
echo "<select id='slctType'>";
if (mysqli_num_rows($typedata) > 0) {
while($row = mysqli_fetch_assoc($typedata)) {
echo "<option value='{".$row['name']."}'>".$row['name']."</option>";
}
}
echo "</select>";
$dflavor = "SELECT type_id,name FROM drinkflavor";
$flavordata = mysqli_query($connection, $dflavor);
echo "<select id='slctFlavor' ";
if (mysqli_num_rows($flavordata) > 0) {
while($row = mysqli_fetch_assoc($flavordata)) {
echo "<option value='{".$row['name']."}'>".$row['name']."</option>";
}
}
echo "</select>";
mysqli_close($connection);
?>
I have sample code for fetching the city according to their state. I have do that code with ajax, jquery and php. I think you have similar type of requirement. Please try below code concept for your requirement.
$(document).on('change','#state',function () {
$('#city').remove();
if($(this).val() != 'none')
{
var state_id = $(this).val();
$.ajax({
type: 'POST',
url: 'page.php',
data: { state_id: state_id },
success: function (city_response) {
if(city_response == '')
{
return false;
}
else
{
var city = '<select name="city" id="city" class="form-control">';
city += '<option value="-----">Please select any City</option>';
$.each(city_response, function (ck, cv) {
city += '<option value="' + cv['city_id'] + '">' + cv['city_name'] + '</option>';
});
city += '</select>';
$("#city_div").css('display', 'block');
$('#cities').append(city);
}
}
})
}
else
{
$("#city_div").css('display', 'none');
}
});

Autofill a select after submission via jQuery

I've got a form where users can choose a car brand. After that I send an SQL-query with Ajax to fill the next select with all the models of the selected brand.
When the form is submited I check it via PHP and if there is any error I return to the previous form with an error-message and fields filled.
The problem is that the 'model' field has the "trigger" set on brand change.
How can I fix this: call the jquery again (to show the models in the select) and display the previous model as selected?
Ajax.php
if ($_POST['brand_car']) {
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $_POST['brand_car']);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
echo json_encode($model);
}
jQuery
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
}}
});
});
XHTML + PHP
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
There are various ways you can fix it.
jQuery Approach
I think the simplest way is to refractor your change() and seperate the ajax call from the change event, like so:
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
getModels(id, 0);
}
function getModels(id, select) {
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="0">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
$('#model_car').val(select);
}}
});
}
This allows you to make an AJAX call by calling getModels(). So all you have to do is call it:
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
Tag this at the end:
<?php
echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>
This way the code is also more testable. This isn't a perfect solution and you should definitely consider using $(function(){}); to make sure the document is ready. AJAX request also needs time to complete, so that models won't be there instantaneously when the page loads.
PHP Approach
Alternatively, you could consider reusing your AJAX code. Wrap it into a function:
function getModels($dbh, $brand_car) {
// I know nothing about your design, but globals are no good
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $brand_car);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
return $model;
}
AJAX.php
if ($_POST['brand_car']) {
echo json_encode(getModels($dbh, $_POST['brand_car']));
}
In your XHTML + PHP
<select id="model_car" name="model_car">
<?php
foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
}
?>
</select>
PS. It looks like your $_SESSION['brand_car'] is never updated.

AJAX request causes change function unbind

I want to implement simple functionality to allow users to save their message text as template to be used in the future.
php:
echo '<div id="container">';
$sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates
WHERE member_id = {$member_id}");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$confName = get_conference_name($confID);
$confName = formatText_safe($confName);
echo "<label>" . $lang['my_template'] . "</label><select id='tempchoose' name='templates'>";
if ($num_rows == 0) {
echo '<option value=""> ' . $lang['no_saved'] . '</option>';
} else {
for ($i = 0; $i < $num_rows; $i++) {
//$template_id = mysql_result($result, $i, 0);
$temp_text = mysql_result($result, $i, 1);
$temp_name = mysql_result($result, $i, 2);
echo '<option value="' . $temp_text . '">' . $temp_name . '</option>';
}
}
echo "</select></div>";
echo '<input id="send" name="Message" value="send" disabled="disabled" type="submit" />
<input id="temp" name="temp" type="button" value="save as template" />"
<textarea style="width: 99%;" id="textarea" name="TextBox" rows="8" disabled="disabled" type="text" value=""/></textarea>';
javascript:
$("#temp").bind("click", function(){
name=prompt("template name?");
temp_text = $("#textarea").val();
if (name!=null && name!="" && name!="null") {
$.ajax ({
data: {temp_text:temp_text, name:name},
type: 'POST',
url: 'save_template.php',
success: function(response) {
if(response == "1") {
alert("template saved successfully");
} else {
alert(response);
}
}
});
} else {
alert("invalid template name");
}
$.ajax ({
url: 'update_templates.php',
success: function(response) {
$("#container").html(response);
}
});
});
$("select").change(function () {
$("select option:selected").each(function () {
$("#textarea").removeAttr("disabled");
$("#send").removeAttr("disabled");
});
$("#textarea").val($(this).val());
})
.trigger('change');
update_temp.php
$sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates
WHERE member_id = {$member_id}");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$confName = get_conference_name($confID);
$confName = formatText_safe($confName);
echo "<label>".$lang['my_template']."</label><select id='tempchoose' name='templates'>";
if ($num_rows == 0) {
echo '<option value=""> '.$lang['no_saved'].'</option>';
} else {
for ($i = 0; $i < $num_rows; $i++) {
//$template_id = mysql_result($result, $i, 0);
$temp_text = mysql_result($result, $i, 1);
$temp_name = mysql_result($result, $i, 2);
echo '<option value="' . $temp_text . '">' . $temp_name . '</option>';
}
}
echo "</select>";
the last ajax request in #temp click function is used to updated the droplist with the newly created template, the problem is that when i click save template; ajax request is performed successfully and droplist is updated, however something wired happen which is that the change function of select is not working anymore! anyone knows where's the problem?
Because ajax will inject new elements to your DOM and those elements don't know about the binding you already defined.
Solution : use jQuery on
Change
$("select").change(function () {
to
$(document).on("change","select", function(){
jQuery on is available from 1.7+ version onwards, if you are using a previous version of jQuery, consider using delegate.
If you are rewriting the select with Ajax you should use .delegate() rather than simply .change, like:
$("someSelector").delegate("select", "change", function() {
// do stuff...
});
where someSelector is an element that contains your select.
Yes, because you have replaced the drop down inside of container, which will unhook all of the events on the drop down. The solution would be to modify the code as below:
$.ajax ({
url: 'update_templates.php',
success: function(response) {
$("#container").html(response);
$("#container select").change(
// your drop down change functionality here //
);
}
});
What this is doing is saying, "After the drop down has been refreshed, also refresh the event."
I hope this helps.

Categories