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.
Related
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.
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');
}
});
After I created an if inside a SELECT tag (HTML) my browser keeps refreshing.
The purpose of this if is to make an OPTION selected when the condition appear.
I also have done this earlier on the same page and it worked.
My guess is that having the 2 SELECT dropdowns on the same page, having this code is making them to refresh each other (I have a jQuery to do onchange actions).
the code is this:
<select name="ddequipamento" id="ddequipamento" class="cliente" <? if (!$_GET['id']) echo "disabled" ?> >
<option value="---">---</option>
<?
if ($_GET['id'])
{
for ($i = 0; $i < $count_equipamento; $i++)
{
$idequipamento = mysql_result($result_equipamento,$i,"idequipamento");
$marca = mysql_result($result_equipamento,$i,"marca");
$tipo_equipamento = mysql_result($result_equipamento,$i,"tipo_equipamento.tipo_equipamento");
$num_serie = mysql_result($result_equipamento,$i,"num_serie");
echo (' <option value="'.$idequipamento .'" ');
if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}
echo (' >'.$tipo_equipamento. ' - '. $marca . ' - '. $num_serie .'</option>');
}
}
?>
<option value="0" >Novo</option>
</select>
and the jQuery:
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val();
});
});
Please pass "eq" through URL , Please change it in script,
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val()+"&eq=<?php echo $_GET['eq'];?>";
});
});
If you want to "id" only then change in PHP part,
if ($_GET['id'] = $idequipamento){ //OLD if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}
IF TWO DROPDOWNS WITH DIFFERENT ID "eq" and "id"
if you have 2 drop-downs use,
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val()+"&eq=<?php echo $_GET['eq'];?>";
});
$('#ddcliente2').change(function () { //CHANGE THE ID OF SECOND DROPDOWN
window.location.href = "index.php?eq="+ $(this).val()+"&id=<?php echo $_GET['id'];?>";
});
});
and also change the PHP part for 2 drop-downs
// FIRST DROP DOWN
if ($_GET['id'] = $idequipamento){ //OLD if ($_GET['id'] = $idequipamento){
echo (' selected="true" ');
}
// SECOND DROP DOWN , CHANGE VARIABLE NAME of $idequipamento2
if ($_GET['eg'] = $idequipamento2){ //OLD if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}
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,
Here's the issue: I have a JS dropdown for country and state that runs in a PHP form for users to update their profiles.
The user selects country for ex 'USA', then state 'Colorado', and submits. What happens is that these values are saved OK on my database, but when the page refreshes, only the country dropdown remains selected with the user's choice. The state shows as 'Select State', although the value 'Colorado' is in the DB.
I just can't manage to have PHP and JS talk to each other so that if the user chose Colorado, it should be pulled from the DB and shown as selected whenever they refresh or come back to the page.
Any ideas how to do this? I tried the suggestion at the top of the JS code but was unsuccessful.
Here is the JS (some code trimmed for brevity):
// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
var postState = '';
var postCountry = '';
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:Alaska:Alaska|\
US:Alabama:Alabama|\
';
var country = '\
US:United States|\
CA:Canada|\
';
function TrimString(sInString) {
if ( sInString ) {
sInString = sInString.replace( /^\s+/g, "" );// strip leading
return sInString.replace( /\s+$/g, "" );// strip trailing
}
}
// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry) {
if ( postCountry != '' ) {
defaultCountry = postCountry;
}
var countryLineArray = country.split('|'); // Split into lines
var selObj = document.getElementById('countrySelect');
selObj.options[0] = new Option('Select Country','');
selObj.selectedIndex = 0;
for (var loop = 0; loop < countryLineArray.length; loop++) {
lineArray = countryLineArray[loop].split(':');
countryCode = TrimString(lineArray[0]);
countryName = TrimString(lineArray[1]);
if ( countryCode != '' ) {
selObj.options[loop + 1] = new Option(countryName, countryCode);
}
if ( defaultCountry == countryCode ) {
selObj.selectedIndex = loop + 1;
}
}
}
function populateState() {
var selObj = document.getElementById('stateSelect');
var foundState = false;
// Empty options just in case new drop down is shorter
if ( selObj.type == 'select-one' ) {
for (var i = 0; i < selObj.options.length; i++) {
selObj.options[i] = null;
}
selObj.options.length=null;
selObj.options[0] = new Option('Select State','');
selObj.selectedIndex = 0;
}
// Populate the drop down with states from the selected country
var stateLineArray = state.split("|"); // Split into lines
var optionCntr = 1;
for (var loop = 0; loop < stateLineArray.length; loop++) {
lineArray = stateLineArray[loop].split(":");
countryCode = TrimString(lineArray[0]);
stateCode = TrimString(lineArray[1]);
stateName = TrimString(lineArray[2]);
if (document.getElementById('countrySelect').value == countryCode && countryCode != '' ) {
// If it's a input element, change it to a select
if ( selObj.type == 'text' ) {
parentObj = document.getElementById('stateSelect').parentNode;
parentObj.removeChild(selObj);
var inputSel = document.createElement("SELECT");
inputSel.setAttribute("name","state");
inputSel.setAttribute("id","stateSelect");
parentObj.appendChild(inputSel) ;
selObj = document.getElementById('stateSelect');
selObj.options[0] = new Option('Select State','');
selObj.selectedIndex = 0;
}
if ( stateCode != '' ) {
selObj.options[optionCntr] = new Option(stateName, stateCode);
}
// See if it's selected from a previous post
if ( stateCode == postState && countryCode == postCountry ) {
selObj.selectedIndex = optionCntr;
}
foundState = true;
optionCntr++
}
}
// If the country has no states, change the select to a text box
if ( ! foundState ) {
parentObj = document.getElementById('stateSelect').parentNode;
parentObj.removeChild(selObj);
// Create the Input Field
var inputEl = document.createElement("INPUT");
inputEl.setAttribute("id", "stateSelect");
inputEl.setAttribute("type", "text");
inputEl.setAttribute("name", "state");
inputEl.setAttribute("size", 30);
inputEl.setAttribute("value", postState);
parentObj.appendChild(inputEl) ;
}
}
function initCountry(country) {
populateCountry(country);
populateState();
}
and here is the PHP/HTML (trimmed a bit):
<?php
include 'dbc.php';
page_protect();
$err = array();
$msg = array();
if ($_POST['doUpdate'] == 'Update') {
foreach ($_POST as $key => $value) {
$data[$key] = filter($value);
}
$country = $data['country'];
$state = $data['state'];
mysql_query("UPDATE users SET
`country` = '$data[country]',
`state` = '$data[state]'
WHERE id='$_SESSION[user_id]'
") or die(mysql_error());
$msg[] = "Your Profile has been updated";
//header("Location: mysettings.php?msg=Your new password is updated");
}
$rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'");
?>
<html>
<body>
<form name="profile_form" id="profile_form" method="post" action="">
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
<input name="doUpdate" type="submit" id="doUpdate" value="Update">
<table>
<tr>
<th>Country:</th>
<td><select id='countrySelect' name='country' onchange='populateState()'>
</select></td>
</tr>
<tr>
<th>State:</th>
<td>
<select id='stateSelect' name='state'>
</select>
<script type="text/javascript">
initCountry('<?php echo $row_settings['country']; ?>');
</script>
</td>
</tr>
</table>
</form>
</body>
</html>
One of the issues i often run into with Javascript is the load order.
You appear to be running and calling populateCountry and populateState at the same time, thereby not having much opportunity for the State list to be populated once the country list has been determined.
Consider moving "populateState()" to the last line of "populateCountry()" so it calls it at the end of the function processing.
There are multiple ways to do this, but this is the simplest to illustrate the point.
Change the top lines
// If you have PHP you can set the post values like this
//var postState = '<?php echo $_POST["state"] ?>';
//var postCountry = '<?php echo $_POST["country"] ?>';
var postState = '';
var postCountry = '';
to
// If you have PHP you can set the post values like this
var postState = '<?= $_POST["state"] ?>';
var postCountry = '<?= $_POST["country"] ?>';
//var postState = '';
//var postCountry = '';
Does that not work?
PHP Short tags, ie "<?=" are not enabled by default anymore i believe in some of the newer php versions. I've stopped using it, i know it looks pretty but it can be a pain if you migrate to a server that doesn't support them.