I created 2 files:
1. post.php
2. ajax.php
i want to select 2 select box to show the related chart. the select box is coded in post.php. The data query is in the ajax.php file. i want to code the select box logic in ajax.php so that the chosen select box data will be sent to post.php using ajax call.
but, I don't know how to call the variable selected value of select boxes in ajax.php to run the function there.
Anyone can help me?
this is the code from post.php
//combo box options to select post filter
echo 'Posts of : ';
echo '<select id="post-filter">';
echo '<option value="0" selected="selected"> Select </option>';
echo '<option value="1">Job</option>';
echo '<option value="2">Internship</option>';
echo '</select>';
echo ' ';
//combo box options to select group filter
echo 'Category : ';
echo '<select id="field-filter">';
echo '<option value="0" selected="selected"> Select </option>';
echo '<option value="1">Company</option>';
echo '<option value="2">Location</option>';
echo '<option value="3">Jobs Category</option>';
echo '<option value="4">Salary</option>';
echo '<option value="5">Experience</option>';
echo '<option value="6">Level of Education</option>';
echo '</select>';
?>
function change1() {
var listbox1 = document.getElementById("post-filter");
var selIndex1 = listbox.selectedIndex;
var selValue1 = listbox.options[selIndex1].value;
var selText1 = listbox.options[selIndex1].text;
}
function change2() {
var listbox2 = document.getElementById("post-filter");
var selIndex2 = listbox.selectedIndex;
var selValue2 = listbox.options[selIndex2].value;
var selText2 = listbox.options[selIndex2].text;
}
this is the ajax.php file to get the chosen data value
if (selValue1 == '1') {
if (selValue2 == '1') {
x = CompanyData;
y = optionsCompany;
}
if (selValue2 == '2') {
x = LocationData;
y = optionsLocation;
}
if (selValue2 == '3') {
x = CategoryData;
y = optionsCategory;
}
if (selValue2 == '4') {
x = SalaryData;
y = optionsSalary;
}
if (selValue2 == '5') {
x = ExperienceData;
y = optionsExperience;
}
if (selValue2 == '6') {
x = LevelData;
y = optionsLevel;
}
}
elseif (selValue1 == '2') {
if (selValue2 == '1') {
x = CompanyData;
y = optionsCompany;
}
if (selValue2 == '2') {
x = LocationData;
y = optionsLocation;
}
if (selValue2 == '3') {
x = CategoryData;
y = optionsCategory;
}
if (selValue2 == '4') {
x = SalaryData;
y = optionsSalary;
}
if (selValue2 == '5') {
x = ExperienceData;
y = optionsExperience;
}
if (selValue2 == '6') {
x = LevelData;
y = optionsLevel;
}
}
can i use this?
$(document).ready(function() {
$('select[name="post-filter"]').change(function(){
var select1 = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {select1: select1},
dataType: 'php'
});
});
});
Post.php
<?php
//combo box options to select post filter
echo 'Posts of : ';
echo '<select id="post-filter">';
echo '<option value="0" selected="selected"> Select </option>';
echo '<option value="1">Job</option>';
echo '<option value="2">Internship</option>';
echo '</select>';
echo ' ';
//combo box options to select group filter
echo 'Category : ';
echo '<select id="field-filter">';
echo '<option value="0" selected="selected"> Select </option>';
echo '<option value="1">Company</option>';
echo '<option value="2">Location</option>';
echo '<option value="3">Jobs Category</option>';
echo '<option value="4">Salary</option>';
echo '<option value="5">Experience</option>';
echo '<option value="6">Level of Education</option>';
echo '</select>';
?>
<script>
$(document).ready(function() {
// for post-filter
$('#post-filter').on('change',function(){
var select1 = $(this).val(); // Post filter value
var select2 = $("#field-filter").val(); // Field Filter value
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {selValue1 : select1,selValue2 :select2 },
success: function(result){
console.log(result); // what ever the ajax call response we got from ajax.php
}
});
});
// we need to do the same for field filter value.
$('#filed-filter').on('change',function(){
var select2 = $(this).val(); // Field filter value
var select1 = $("#post-filter").val(); // post Filter value
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {selValue1 : select1,selValue2 :select2 },
success: function(result){
console.log(result); // what ever the ajax call response we got from ajax.php
}
});
});
</script>
ajax.php will be the same as you have done.
Related
I'm new here and I need help with a PHP code.
I want to transform a radio button into a checkbox, make it calculate the fee depending on how much checkboxes are checked, and to transmit the checked values to the predefined database.
My code only takes the one predefined value for fee an doesn't actually adds them up when I click on the other checkbox. I tried everything but with no success. Here is the original unchanged code:
<script src="<?php echo URL_FRONT_JS;?>jquery.js"></script>
<script>
function get_tutor_course_details()
{
course_slug = $('#course_slug option:selected').val();
selected_date = $('#start_date').val();
if(!course_slug || !selected_date) {
$('#fee').text('');
$('#duration').text('');
$('#days_off').text('');
$('#content_li').remove();
$('#time_slot_div').text('<?php echo get_languageword("please_select_course_and_date_first"); ?>');
return;
}
$.ajax({
type: "POST",
url: "<?php echo URL_HOME_AJAX_GET_TUTOR_COURSE_DETAILS; ?>",
data: { "course_slug" : course_slug, "tutor_id" : <?php echo $row->id; ?>, "selected_date" : selected_date },
cache: false,
beforeSend: function() {
$('#time_slot_div').html('<font color="#5bc0de" size="6"> Loading...</font>');
},
success: function(response) {
if(response == "") {
$('#fee').text('');
$('#duration').text('');
$('#days_off').text('');
$('#content_li').remove();
$('#time_slot_div').html('<?php echo get_languageword("no_slots_available."); ?> <?php echo get_languageword("click_here_to_send_me_your_message"); ?>');
$('#request_tutor_btn').slideUp();
} else {
var fee_duration = response.split('~');
var fee = fee_duration[0];
var duration = fee_duration[1];
var content = fee_duration[2];
var time_slots = fee_duration[3];
var days_off = fee_duration[4];
$('#fee').text(fee +'€');
$('#duration').text('EUR');
if(content) {
$('#content_li').remove();
$('#course_li').after('<li id="content_li"><?php echo get_languageword("course_content"); ?><p>'+content+'</p></li>');
}
time_slot_html = "";
if(time_slots != "")
time_slots = time_slots.split(',');
total_available_timeslots = time_slots.length;
if(total_available_timeslots > 0) {
for(i=0;i<total_available_timeslots;i++) {
check_radio = "";
if(i == 0)
check_radio = 'checked = "checked"';
time_slot_html += '<li><div><input id="radio1'+i+'" type="radio" name="time_slot" value="'+time_slots[i]+'" '+check_radio+' ><label for="radio1'+i+'"><span><span></span></span>'+time_slots[i]+'</label></div></li>';
}
$('#time_slot_div').html(time_slot_html);
$('#request_tutor_btn').slideDown();
} else {
$('#time_slot_div').html('<?php echo get_languageword("no_slots_available."); ?> <?php echo get_languageword("click_here_to_send_me_your_message"); ?>');
$('#request_tutor_btn').slideUp();
}
}
}
});
}
I would like my PHP query to update dynamically the data displayed without a refresh.
I have these two select option choices.
<select name="d">
<option <?php if ( $d == '50' ) { echo 'value="50" selected="selected" >50 km '; } else { echo 'value="50" >50 km '; } ?></option>
<option <?php if ( $d == '100' ) { echo 'value="100" selected="selected" >100 km '; } else { echo 'value="100" >100 km '; } ?></option>
</select>
<select name="o">
<option <?php if ( $o == '1' ) { echo 'value="1" selected="selected" >from nearest to furthest '; }
else { echo 'value="1" >from nearest to furthest '; } ?>
</option>
<option <?php if ( $o == '2' ) { echo 'value="2" selected="selected" >from furthest to nearest '; }
else { echo 'value="2" >from furthest to nearest '; } ?>
</option>
</select>
Here is the PHP part with the 3 variables a (from a text input), d and o.
$a = isset($_GET['a']) ? $_GET['a'] : '';
$d = isset($_GET['d']) ? $_GET['d'] : '';
$o = isset($_GET['o']) ? $_GET['o'] : '';
if ( !empty($_GET['a']) )
{
$request = mysqli_query($sql,"
SELECT *
FROM adresses
WHERE adress = '".$a."' HAVING distance <= ".$d." order by ".$o."");
}
Here is the final result :
echo '<div id="result">';
while ( $row = mysqli_fetch_array($request) )
{
echo '<p>'.$row['shop'].' | '.$row['adress'].' | '.echo $row['town'].'</p>';
}
echo '</div>';
I've never used AJAX before and I would like to know how to run a query like this one above.
Here is my attempt for the AJAX part (not sure about the syntax) :
<script src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#result").change(function(){
var a = $(this).val();
var d = $(this).val();
var o = $(this).val();
$.ajax({
type: "GET",
url: "test.php",
data: { a: $a, d: $d, o: $o } ,
success: function(result){
$("#result").html(result);
}
});
});
});
</script>
Please, could you tell me what am I supposed to put in the test.php file ?
In test.php you should gather data from the server, ie, MySQL.
$a = isset($_GET['a']) ? $_GET['a'] : '';
$d = isset($_GET['d']) ? $_GET['d'] : '';
$o = isset($_GET['o']) ? $_GET['o'] : '';
if ( !empty($_GET['a']) )
{
$request = mysqli_query($sql,"
SELECT *
FROM adresses
WHERE adress = '".$a."' HAVING distance <= ".$d." order by ".$o."");
}
echo '<div id="result">';
while ( $row = mysqli_fetch_array($request) )
{
echo '<p>'.$row['shop'].' | '.$row['adress'].' | '.echo $row['town'].'</p>';
}
echo '</div>';
Whatever php script returns (echo in case above) it will be in your result variable here:
success: function(result){
$("#result").html(result);
}
Few more things.
You are defining variables incorrectly, it should be:
var a = $('#a').val();
var d = $('#d').val();
var o = $('#o').val();
For this to work you need to assign id to your select's
<select name="d" id="d">
JS variable don't have $ sign, so the variable you sending to test.php should be:
data: { a: a, d: d, o: o }
Note: None of above is tested, just copy/paste of your code to get you on the right track.
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'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 the following select list:
SELECT LIST 1:
<select name="productcolor" id="productcolor" onChange="GetAvailProductSizes();">
<option value=""><? echo $langdata['oneprodpage_selectcolor']; ?>...</option>
<? foreach ($thisproduct['availcolors'] as $color) { ?>
<option value="<? echo $color['id']; ?>"><? echo $color['name']; ?></option>
<? }; ?>
</select>
SELECT LIST 2:
<select name="productsize" id="productsize" style="width: 120px;">
<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>
</select>
If in LIST 1 no options where selected, LIST 2 will be empty. It's like LIST 2 depends of LIST 1.
This is made with this function:
<script type="text/javascript"><!--
function GetAvailProductSizes() {
$('select#productsize option').remove();
$('select#productsize').append('<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>');
var color = $('#productcolor').val();
if (color > 0) {
var availsizes;
var http_request = new XMLHttpRequest();
http_request.open( "GET", '<? echo ROOT; ?>/autocompleteavailsizes/?productid=<? echo $thisproduct['id']; ?>&color=' + color, true );
http_request.send(null);
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
availsizes = eval( "(" + http_request.responseText + ")" );
for (var i = 0; i < availsizes.length; i++) {
$('select#productsize').append('<option value="' + availsizes[i].id + '">' + availsizes[i].name + '</option>');
};
} else {
alert( "There was a problem with the URL." );
}
http_request = null;
}
};
};
}
//-->
</script>
Now, I want the SELECT LIST 2 to be hidden until SELECT LIST 1 was not touched. Any help please with PHP or jQuery. Thank you!
Simply add display:none to the style attribute of the second list and use $('select#productsize').show(); inside your function to let it appear,