I want to make the third drop down populated based on selection on second drop down refer value from first and second drop down.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
});
});
$("#sub_cat").change(function() {
$.get('loadsubelement.php?sub_cat=' + $(this).val() + $('#parent_cat').val(), function(data) {
$("#select_subelement").html(data);
});
});
});
</script>
loadsubelement.php
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$sub_cat = $_GET['sub_cat'];
$query = mysqli_query($connection, "SELECT * FROM maincategories WHERE categoryID = {$parent_cat}");
$query = mysqli_query($connection, "SELECT * FROM maincategories WHERE subcategoryID = {$sub_cat}");
echo '<option value="">Please select</option>';
while($row = mysqli_fetch_array($query)) {
echo '<option value="'.$row['subcategoryID'].'">' . $row['maincategory_name'] . "</option>";
}
?>
I think you have to change your query string like this:
$.get('loadsubelement.php?sub_cat=' + $(this).val() +
"&parent_cat" + $('#parent_cat').val()
You are missing this: "&parent_cat" in your second ajax call.
Or a better way of doing is to send the an object like this:
$("#sub_cat").change(function() {
var dataString = {
parent_cat : $('#parent_cat').val(),
sub_cat : $(this).val()
};
if($('#parent_cat').val() !== ""){ // check if value is selected or not i guessed default value as "".
alert("Please choose the parent value.");
$('#parent_cat').focus(); // apply focus on the element.
return false;
}else{
$.get('loadsubelement.php', dataString, function(data) {
$("#select_subelement").html(data);
});
}
});
jQuery(function($) {
jQuery("#office_id").change(function(){
var inputString=jQuery("#office_id").val();
$.post("?r=reports/summary/loademployees/", {office_id: ""+inputString+""}, function(data){
$('#employee_id').fadeIn();
$('#employee_id').html(data);
}
});
});
});
This is a program triggers when when u change a dropdown containing offices having id as office_id and load employees (another dropdown box having id employee_id) of that office.
Related
I have some <td name="puja"> elements I want to update every 5 seconds deppending on their id so they contain the greatest bid(puja) for it's auction(subasta). For that, I'm trying to use AJAX and PHP.
Html looks like this (relevant code):
<?php
foreach ($subastas as $subasta) { ?>
<td name="puja" id="<?php echo $subasta["oid_s"] ?>"> </td>
As I have multiple elements to update, I tried getting all the elements and then running my AJAX function for every one of them.
AJAX:
$(document).ready(function()
{
var ids = document.getElementsByName("puja");
for (var i=0; i<ids.length;i++){
var id = ids[i].id;
$.ajax({
url : 'includes/getPuja.php',
data:{"oid_s":id},
success: function(data){
$(`#${id}`).html(data);
}
});
};
});
Finally, in my php file I just make a database connection, get the desired value , and echo it.
getPuja.php (relevant code):
$puja = 0;
if(isset($_POST["oid_s"])) {
$oid_s = $_POST["oid_s"];
$consultaPuja='SELECT pujado from (SELECT * from pujas WHERE OID_S = :oid_s ORDER BY pujado DESC) where rownum = 1';
try {
$stmtPuja = $conexion->prepare($consultaPuja);
$stmtPuja -> bindParam(':oid_s', $oid_s);
$stmtPuja -> execute();
foreach ($stmtPuja as $fila) {
$puja = $fila["PUJADO"] ;
}
echo $puja;
} catch(PDOException $e) {
$_SESSION["excepcion"] = $e -> GetMessage();
header("Location: excepcion.php");
}
}
When I run it, the HTML is not modified.
I fixed my problem with the following code, now the values get updated every second:
$(document).ready(function(){
setInterval(getPuja, 1000);
function getPuja() {
$( '[name=puja]' ).each(function() {
var id = $( this ).attr('id');
$.ajax({
url : 'includes/getPuja.php',
method:"POST",
data:{oid_s:id},
success: function(data){
$(`#${id}`).html(data);
}
});
});
}
});
I want to make a dropdown list which is dependable on another dropdown list. Both dropdown list's values are retrieved from database. How can i do that?please help .
Also how can i pass the category name to database mysql query page (list.php).
I currently have this which list all subcategories..but i want to list only particular subcategory depending on category
<script>
$(document).ready(function(){
$.getJSON("getlist.php", function(return_data){
return_data.forEach(function(e,i){
$('#catn').append('<option value= "'+e.catname+'">'+e.catname+'</option>');
});
});
});
$(document).ready(function(){
$.getJSON("list2.php",{'catname':catname},function(return_data){
return_data.forEach(function(h,i){
$('#scatn').append('<option value= "'+h.subcatname+'">'+h.subcatname+'</option>');
});
});
});
list.php
<?php
$catname=$_GET['catname'];
$conn =mysqli_connect("localhost", "root", "", "project");
$sql = "SELECT * FROM catd where catname='$catname'";
$result = mysqli_query($conn, $sql);
$scat_arr = array();
while( $row = mysqli_fetch_array($result) )
{
$catid = $row['cid'];
$catname = $row['catname'];
$scat_arr[] = array("cid" => $catid, "catname" => $catname);
}
echo json_encode($scat_arr);
?>
You can use .change function in JS. While the first dropdown is changing it triggers the ajax with POST method to post to your file list.php(where your query runs).
jQuery(document).ready(function() {
$('#catname').change(function(){
var catname = $(this).val();
$.ajax({
url:list.php,
method:"POST",
data:{
catname:catname
},
dataType:"json",
success:function(data){
var $el = $("#subcatname");
$el.empty();
$el.append($("<option></option>")
.attr("value", '')
.attr("hidden",'')
.text('Select Sub Cat Name'));
$.each(data, function(index, value){
$el.append('<option
value="'+value.catid+'">'+value.catname+'</option>')
});
});
You must echo json_encode the output so that ajax recognize the returned value. And then you can append the values by casting it using append.
Hopes this helped.
I want to achieve this feature. That when users who want to post ads selects a category then an .change() JQUERY method tiggers an AJAX request which will request for sub categories from the SUB-CATEGORIES Table that belong to the selected CATEGORY and append the results on the the next SELECT FIELD. But so far its not getting the Results.
This are my code snippets.
subcat.php
<?php
include 'includes/config.php';
if (isset($_POST['category'])) {
$cat = mysqli_real_escape_string($link, $_GET['category']);
//select category id from categories table where Title = $cat
$catIdSel = "SELECT cat_id FROM categories WHERE catTitle = '$cat'";
$catIdSelKwary = mysqli_query($link, $catIdSel);
$catIdSelCount = mysqli_nums_row($catIdSelKwary);
if ($catIdSelCount == 1) {
$catIdRow = mysqli_fetch_array($catIdSelKwary);
$cat_id = $catIdRow['cat_id'];
}
//select from sub-categories table all the sub-categories that have the same cat_id with the returned cat_id from the dategories table
$subCatSel = "SELECT Title FROM sub_categories WHERE cat_id = '$cat_id'";
$subCatSelKwary = mysqli_query($link, $subCatSel);
$subCatSelCount = mysqli_nums_row($subCatSelKwary);
if ($catIdSelCount > 0) {
while ($subCatRow = mysqli_fetch_array($subCatSelKwary)) {
echo '<option value="'.$subCatRow['Title'].'">' .$subCatRow['Title']. '</option>';
}
}else{
echo "No Sub Category for this Category yet";
}
}
postad.php - where my Jquery is
<script type="text/javascript">
$(document).ready(function () {
$('#category').change(function () {
//display loading option
$('#sub-category').html('<option value="">Fetching Sub Categories...</option>');
//collect select value
var category = $('#category').val();
$.ajax({
URL: 'sel_subcat.php?cat' + category,
method: 'POST',
data: category,
success: function (data) {
//append the data to the select field
$('#sub-category').html(data);
},
error: function () {
console.log(xhr.status + " " + thrownError);
}
});
});
});
</script>
Below is the image of the page/form
This can help you
var category = $('#category').val();
$.ajax({
URL: 'sel_subcat.php',
method: 'POST',
data: {category:category},
success:function(data){
//append the data to the select field
$('#sub-category').html(data);
},
error:function () {
console.log(xhr.status + " " + thrownError);
}
});
And Use $_POST['category'] To Recieve the Data.
I'm trying to pass the value of the dropdown menu to the PHP variable $anno, so the print_r() function at the end can use the realtive $coefficiente variable (which depends on $anno).
<select name="anno">
<option>1940</option>
<option>1941</option>
<option>1942</option>
</select>
<?php
$importo = "100";
$anno = $_POST["anno"];
if ( $anno == "1940" ) { $coefficiente = "10"; } ;
if ( $anno == "1941" ) { $coefficiente = "20"; } ;
if ( $anno == "1942" ) { $coefficiente = "30"; } ;
print_r(($importo*$coefficiente)/1936.27); echo '€';
?>
Can this be "AJAXified"?
At this time when I choose the dropdown option, the print_r function isn't updated. Do I need a submit button?
If you want to calculate your formula in the same page, don't use PHP use Javascript
<select name="anno">
<option>1940</option>
<option>1941</option>
<option>1942</option>
</select>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("select[name='anno']").on('change', function(e) {
var importo = "100";
var anno = $(this).val();
var coef = "";
if (anno == 1940) { coef = 10; }
if (anno == 1941) { coef = 20; }
if (anno == 1942) { coef = 30; }
alert(importo*coef/1936.27 + "€");
})
});
For PHP handling, use AJAX (warning I couldn't test this!)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("select[name='anno']").on('change', function(e) {
$.ajax({
type: "POST",
url : "your_php_script.php",
data: { anno: $(this).val() },
})
.done(function(data) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Something went wrong!\n" + errorThrown);
});
})
});
I've got some JQuery which monitors a form. Basically, for every keyup it will call a php file to search the database.
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2) {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
});
This works fine, however it filters the results in #searchresultdata depending on the query. The only thing is, if nothing is in the form, I want it to load everything - the user should not have to click the form to do this, therefore a .blur would not work.
The PHP file is simply:
if(isset($_GET['keyword'])){}
you should handle a [*] search on your server
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
if (faq_search_input =='') faq_search_input ='*';
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2 || faq_search_input=='*') {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
$("#faq_search_input").trigger('keyup');
});
If you're loading all results initially, then could you not just store this in a JavaScript array and filter the results with JavaScript? This would save you a HTTP request on every key press, which can only be good for speed and resource usage of your site.
EDIT: Sample.
<?php
$sql = "SELECT `title` FROM `your_table`";
$res = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row['title'];
}
echo '<script>var data = ' . json_encode($rows) . ';</script>';
?>
<form method="post" action="">
<fieldset>
<input type="text" name="search" id="faq_search_input" />
</fieldset>
</form>
<script>
// I presume you're using jQuery
var searchInput = $('#faq_search_input');
var searchResults = $('#searchresultdata');
var tmpArray = data;
// add all results to results div
$.each(data, function(key, val) {
searchResults.append('<li>' + val + '</li>');
});
searchInput.attr('placeholder', 'Begin typing to search');
searchInput.keyup(function() {
// hide any <li> in your #searchresultdata that don't match input
});
</script>
I don't know what is in your serverresponse variable, so I can only guess what gets put into the searchresultdata <div>. You'll also need to modify the SQL query to match your table and column names.
Contents of searchdata.php
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%'";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$result=mysql_query($query, $database_connection) or die(mysql_error());
if($result){
if(mysql_affected_rows($database_connection)!=0){
while($row = mysql_fetch_object($result)){
?>
<div class="hold-cont">
<div class="holder">
<div class="image-hold" >
<img class="image-icon" src="<? echo $deviceimg.($row->Image); ?>"/>
</div>
</div>
<div class="device-name devicename-txt"><? echo($row->Manufacturer. ' ' .$row->Model); ?></div>
</div>
<?
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
}
}else {
echo 'Parameter Missing';
}