jQuery sending the name of the selected value as empty? AJAX - php

$.post(
"ajax",
{
addItem : username.val(),
price : price.val(),
desc : desc.val(),
thumb : thumb.val(),
cat : cat.find(":selected").text(),
id : id.val()
},
function(data) {
error.html(data);
}
);
$_POST['cat'] will be empty
That means cat.find(":selected").text() doesn't function in this case.
echo '<select class="field2" name="category">
<option>Select Category</option>';
echo $shop->loadAlLCategories();
echo '</select>';
What did I do wrong in this case? Why is POST cat always empty no matter what I select?
public function loadAlLCategories()
{
$this->items = $this->pdo->prepare("SELECT * FROM categories");
$this->items->execute();
while ($row = $this->items->fetch(PDO::FETCH_ASSOC))
{
echo '<option value="'.$row['category_name'].'">'.$row['category_name'].'</option>';
}
}

you can use :
jQuery('.field2 option:selected').text();

you should take the value of the select
$('.field2').val()

Related

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');
}
});

stuck on a PHP program. Need some idea

Want to make a php program, where there will be a drop down which will contain some name of brands .. after selecting the " first drop down/ brands" products of the selected brand will show on another drop down.. need help . anyone ?
What you looking for is called a dependent select. It have barely nothing to do with php (except populating select options). I've found a demo for your case. You will need to install jquery to implement it in your code.
var $city = $(".city").on('change', function() {
$city.not(this).get(0).selectedIndex = this.selectedIndex;
});
You need to read about jQuery or CSS.
Look at this example (jQuery): http://dev7studios.com/dropit/
so you have to use ajax to do this
$(document).on("change","first select box",function(){
var id = $("first select box").val();
$.ajax({
url: "path to your file where you should write db code",
type: "POST",
dataType: "HTML",
async: false,
data: {"id": id},
success: function(data) {
$("second select box").html(data);
// here directly manipulate the data in controller or get the data in success function and manipulate .
}
});
})
in the file where you write db code
$a = "";
foreach(rows fro db as $a){
$a .= "<select value='db id'><?= name ?></select>";
}
echo $a;
we are capturing $a to out normal file add making that as the value for our second select box.
Hope it hlps
Use javascript function onchange select element and fetch records according to selected first select element value.
<form name="product" method="post" >
<select id="category" name="category" onChange="relodme()">
<option value=''></option>
<?php
$qry = "select * from category order by name";
$res = mysql_query($qry) or die ("MYSQL ERROR:".mysql_error());
while ($arr = mysql_fetch_array($res))
{
?>
<option value="<?=$arr['category_id']?>" <? if($_POST['category'] == $arr['category_id']) { ?> selected="selected" <? } ?> ><?=$arr['name']?></option>
<?
}
?>
</select>
<select id="Type" name="Type" >
<option value=''></option>
<?php
$qry = "select * from subcategory where category_id = '".$_POST['category']."' order by name";
$res = mysql_query($qry) or die ("MYSQL ERROR:".mysql_error());
while ($arr = mysql_fetch_array($res))
{
?>
<option value="<?=$arr['sub_category_id']?>" <? if($_POST['Type'] == $arr['sub_category_id']) { ?> selected="selected" <? } ?> ><?=$arr['name']?></option>
<?
}
?>
</select>
</form>
Javascript function:
function relodme()
{
document.forms[0].action="test1.php"; //your page name give here....
document.forms[0].submit();
}

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.

Getting value from dynamically created pop up menu

I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>

Categories