I'm creating a form where the users have to select their country and city from a select field, which is dynamically updated corresponding to the actual country selected. However when the form is submitted everything is getting saved successfully except the city.
I'm using jquery select2 and jquery validation plugin, I think those could cause the problem.
Here is the main code:
$('#country').select2().change(function() {
$("#city").select2('data', null);
$.ajax({
type: 'post',
url: 'search_city.php',
data: 'country=' + $(this).val(),
dataType: 'html',
success: function(response) {
$('#city').html(response);
}
});
});
and
<label>* City:</label>
<select id="city" name="property_city" required>
<option></option>
</select>
and this is search_city.php
echo '<option></option>';
while($city = mysqli_fetch_object($cities)) {
if($_SESSION['property_city'] == $city->id) {
echo '<option selected value="'.$city->id.'">'.$city->name.'</option>';
} else {
echo '<option value="'.$city->id.'">'.$city->name.'</option>';
}
}
When the form is submitted a validation php runs where I save the data to session variables. There are more inputs, not just the country and the city, and they are saved successfully except the city I mentioned.
I can't figure out what the problem is. I did't include all the code, maybe something else could cause the problem, however if someone could find it here I would be relieved.
You need to write,
$html = '<option value=""></option>';
while($city = mysqli_fetch_object($cities)) {
if($_SESSION['property_city'] == $city->id) {
$html .= '<option selected value="'.$city->id.'">'.$city->name.'</option>';
} else {
$html .= '<option value="'.$city->id.'">'.$city->name.'</option>';
}
}
echo $html;
Related
I'm trying to auto populate some text fields (rate1 and rate2) based on a dropdown selection (instid and instfirstname). The values are all in one mysql table called tbl_insts. I'm trying the solution found in How to Get Content in text field dynamically, based on dropdown selection in php, but can't get it to work. Does anyone have any suggestions? Thanks in advance.
This is my mysql table called tbl_insts
instid instfirstname rate1 rate2
1 john 50 45
2 eric 25 45
This is my html form. I'm able to populate the dropdown correctly but not the text fields.
<select name="instfilter" id="instfilter">
<?php
if ($stmt = $conn->prepare("select instid, instfirstname from tbl_insts order by instid")) {
$stmt->execute();
$stmt->bind_result($instid, $instfirstname);
echo '<option value="-1" selected="selected">Please select...</option>';
while ($stmt->fetch()) {
echo '<option value="'.$instid.'">'.$instfirstname.'</option>';
}
$stmt->close();
}
?>
</select>
<!-- Fields that I want to populate based on the selection on top -->
<input type="text" name="rate1" id="rate1" />
<input type="text" name="rate2" id="rate2" />
This is my code before the tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$('#instfilter').change(function(){
var inst = $(this).val();
$.ajax({
type:'POST',
data:{inst:inst},
url:'getrates.php',
success:function(data){
$('#rate1').val(data);
$('#rate2').val(data);
}
});
});
</script>
This is my code in getrates.php in the same directory as the html file above.
<?php
if (isset($_POST['inst'])) {
$qry = "select rate1, rate2 from tbl_insts where instid = ".
$_POST['inst'];
$rec = mysql_query($qry);
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1'];
echo $res['rate2'];
}
}
}
die();
?>
try change data:{inst:inst} to data:{'inst':inst}
now you returning a string from getrates.php. From you code structure, you can do like this:
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1']."|".$res['rate2'];
}
}
..and
success:function(data){
var inputs = data.split('|');
$('#rate1').val(inputs[0]);
$('#rate2').val(inputs[1]);
}
hope this helps.
Untested, but I think these changes should do the job.
while ($res = mysql_fetch_array($rec)) {
$result = [
'rate1' => $res['rate1'],
'rate2' => $res['rate2']
];
}
.......
die(json_encode($result));
and
success: function(data){
data = $.parseJSON(data);
$('#rate1').val(data.rate1);
$('#rate2').val(data.rate2);
}
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');
}
});
I want to create a dropdown list that populated by another dropdown list. I'm using AJAX and PHP.
I have created my AJAX file like this:
<?php
if(isset($_POST['selname']))
{
include('config.php');
$clientId = $_POST['selname'];
$query = "SELECT tv.*, v.* FROM t_vorder tv LEFT JOIN m_vehicle v ON tv.tv_vehicleid = v.v_id WHERE tv_orderid = '$clientId'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$namek = "";
$namek .= $row['v_id'];
if($row['v_jenis'] != "" || !empty($row['v_jenis']))
{
$namek .= ' - '.$row['v_jenis'];
}
if($row['v_platno'] != "" || !empty($row['v_platno']))
{
$namek .= ' - '.$row['v_platno'];
}
if($row['v_merk'] != "" || !empty($row['v_merk']))
{
$namek .= ' - '.$row['v_merk'];
}
$xx .= "<option value='$row[v_id]'>$namek</option>";
}
return $xx;
exit;
}
?>
After that, I called this AJAX file to my main program, here's my JQuery code:
function getVehicle()
{
var selname = $("select[name=noorder]").val();
$('#combobox2').html('');
$.ajax({ url: "getVehicle.php",
data: {"selname":selname},
type: 'post',
dataType: "json",
success: function(output) {
console.log(output);
$('#combobox2').append(output);
}
});
}
And last is my HTML code:
<select name="noorder" id="combobox" class="form-control">
//get my vehicle from database
<?php
$querycon = mysqli_query($conn, "SELECT * FROM m_order WHERE o_status='1' ORDER BY o_id");
while($rowcon = mysqli_fetch_array($querycon, MYSQLI_ASSOC))
{
$invoice = sprintf("%s%"."04d", $rowcon['o_code'], $rowcon['o_id']);
?>
<option value="<?php echo $rowcon['o_id']; ?>"><?php echo $invoice; ?></option>
<?php
}
?>
</select>
<select name="kendaraan" class="form-control" id="combobox2" onclick="getVechile();">
</select>
My Ajax works fine, my console log return that the file finished load. But my dropdown list not appended by Jquery. Anyone know where's my mistakes?
You did't request for json obj/data into ajax success callback, then no need for dataType: "json", inside ajax properties. Remove that and change return $xx; into echo $xx;
AJAX request gets data from PHP file only when its printed out on the page.
Returning and data from PHP (AJAX backend) to jQuery/Javascript does not mean anything.
Change
return $xx;
to
echo $xx;
You use the dataType: "json" in your ajax call, so it get response in JSON. First remove dataType: "json" line from ajax call. Then replace return $xx; with echo $xx; in your php script.
Hope this solution may works for you, Thanks!
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.
I have some code which populates like so:
<select class="form-control" name="accommodation_ID" id="accommodation_ID">
<option value="-1">-- Please Select --</option>
<?php
$AccomodationID = 13; //For testing purposes
$accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName,
ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint
FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID =
ACCOMMODATION.Entity_ID")
or die("Error: ".mysqli_error($conn));
while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
if($accommodation_Results['AccomodationID'] == $AccomodationID){
echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
$PUPoint = $accommodation_Results['PUPoint'];
}
else{
echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
}
}
?>
</select>
<label>Pick Up Point</label>
<input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">
This code works no problem, it checks the database and looks for a match, if it does, set is as the selected option, grab the PUPoint (Pickup point) variable and store it in the input field.
My problem now, is when I go to select a different option from the dropdown list, the pickup point input field doesn't update anymore. This is what I had, working before I implemented the above:
j$('select[name=accommodation_ID]').change(function(event) {
event.preventDefault();
var accommodationID = j$(this).val();
post_data = {'accommodation_ID':accommodationID};
var data = {
"action": "Accommodation_Details"
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
j$('input[name=PUPoint]').val( data["PUPoint"] );
},
error: function (request) {
console.log(request.responseText);
}
});
});
booking_Modify.php
//checks and switch statement related code
$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);
I've done some echoing/console.log and noticed that it's always passing the same Accommodation ID number (13) into booking_Modify.php. It doesn't change when I select a different option now. I don't know if it's because of the "selected" attribute applied to the option element now. Any ideas would be greatly appreciated
You have defined your $AccomodationID = 13; //For testing purposes before which is printed in every iteration of the while loop instead of the current ID. Probably you want to write $accommodation_Results['AccomodationID'] as the option value.