Grabbing Two Values Javascript - php

I am grabbing the values from a listbox and passing it on to another listbox, I had everything working with one value $Lid, but now I need two $Lid and $Cid, is this the correct way to do this?
$(document).ready(function()
{
$(".Doggie").change(function()
{
var LocationString = $(this).find(":selected").val();
var CityString = $(this).find(":selected").val();
$.ajax({
type: "POST",
url: "ajax_city.php",
data: {Lid : LocationString, Cid : CityString},
cache: false,
success: function (html) {
$(".Kitty").html(html);
}
});
});
$('.Kitty').live("change",function(){
var LocationString = $(this).find(":selected").val();
var CityString = $(this).find(":selected").val();
$.ajax({
type: "POST",
url: "ajax_area.php",
data: {Lid : LocationString, Cid : CityString},
cache: false,
success: function (html) {
$(".Pig").html(html);
}
});
});
});
</script>
</head>
<body>
<div id="frame1">
<label>Place :</label>
<select name="Doggie" class="Doggie" id="Doggie">
<option selected="selected">--Select Place--</option>
<?php
$sql = mysql_query("SELECT tblLocations.RestID as Lid, tblLocations.CityID as Cid, tblRestaurants.RestName as name
FROM tblRestaurants INNER JOIN tblLocations ON tblRestaurants.RestID = tblLocations.RestID
GROUP BY tblLocations.RestID, tblRestaurants.RestName
ORDER BY tblRestaurants.RestName ASC");
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
} ?>
</select>
<label>City :</label>
<select name="Kitty" class="Kitty" id="Kitty">
<option selected="selected">--Select City--</option>
</select>
<label>Area: :</label>
<select name="Pig" class="Pig" id="Pig">
<option selected="selected">--Select Area--</option>
</select>
</div>
</body>
</html>
And...
<?php
require ('config.php');
if ($_POST['Lid']) {
$Lid = $_POST['Lid'];
$sql = mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblCities.CityName as name
FROM tblLocations INNER JOIN tblCities ON tblLocations.CityID = tblCities.CityID
WHERE tblLocations.RestID = $Lid
GROUP BY tblLocations.RestID, tblCities.CityName
ORDER BY tblCities.CityName ASC");
echo '<option selected="selected">--Select City--</option>';
while ($row = mysql_fetch_array($sql)) {
echo '<option value="' . $row['Lid'] . '' . $row['Cid'] . '">' . $row['name'] . '</option>';
}
}
?>
Right now its not returning anything so I have to assume its wrong. Thank you.

I would recommend making the changes below:
var LocationString = $(this).find(":selected").val();
var CityString = $(this).find(":selected").val();
$.ajax({
type: "POST",
url: "ajax_city.php",
data: {Lid : LocationString, Cid : CityString},
cache: false,
success: function (html) {
$(".Kitty").html(html);
}
});
You were adding two data values, which is not the right way of doing it. Simply pass a single literal object with your desired key and values and allow JQuery to do the formatting for you.

I don't understand why you store the same value in two vars:
var LocationString = 'Lid=' + $(this).val();
var CityString = 'Cid=' + $(this).val();
It can be simplified to:
var LocationString = $(this).val();
And then you only have one value, so data should be the following format
data: {
'Lid': LocationString
}

data should be the format
data: {Lid : LocationString, Cid : CityString},
and also check what is the result of your query
check it by
print_r(mysql_fetch_array($sql))
if your query does not have any results , echo inside while loop wil not work

This did it.
$(document).ready(function()
{
$(".Doggie").change(function()
{
var LocationString ='Rid='+ $(this).val();
$.ajax({
type: "POST",
url: "place_city.php",
data: LocationString,
cache: false,
success: function (html) {
$(".Kitty").html(html);
}
});
});
$('.Kitty').live("change",function(){
var Rid = $('#Doggie').val(), // This is the value of the id="Doggie" selected option
Cid = $(this).val(); // This is the value of the id="Kitty" selected option
//alert("Rid = " + Rid + " Cid = " + Cid);
$.ajax({
type: "POST",
url: "place_area.php",
data: {"Rid":Rid,"Cid":Cid},
cache: false,
success: function (html) {
//alert('This is what is returned from the php script: ' + html);
$(".Pig").html(html);
}});});});

Related

Make 2 forms (Quote / Enrollment) work like an "Add to Cart" experience

I have a "Quote" form where the user selects a State, Manufacturer and Model from three SELECT inputs. There are 2 pricing columns that are associated with each Manufacturer that I need the values to show on screen when they hit "Add Device" (Submit Button).
If they are happy with the Quote, they will hit "Enroll Now". Besides needing the prices to show, I need those options they selected to populate the same fields on the Enroll form on a different page.
Here is my controller...
function action_mfr_data(){
$db = \Database::connection('esco_web_connection');
$quoteData = $db->GetAll('SELECT DISTINCT wpp_MfrName FROM Products_Premiums ORDER BY wpp_MfrName');
echo '<option value="">Select Manufacturer</option>';
foreach($quoteData as $data){
echo '<option value="'.$data['wpp_MfrName'].'">'.$data['wpp_MfrName'].'</option>';
}
die();
}
function action_mdl_data(){
$db = \Database::connection('esco_web_connection');
$quoteData = $db->GetAll('SELECT DISTINCT wpp_Model FROM Products_Premiums where wpp_MfrName= ? ORDER BY wpp_Model', array($_POST['manufacture']));
echo '<option value="">Select Model</option>';
foreach($quoteData as $data){
echo '<option value="'.$data['wpp_Model'].'">'.$data['wpp_Model'].'</option>';
}
die();
}
function action_annual_data(){
$db = \Database::connection('esco_web_connection');
$quoteData = $db->GetAll('SELECT DISTINCT wpp_StateDefaultAnnual FROM Products_Premiums where wpp_MfrName= ?', array($_POST['annual']));
//echo '<option value="">Annual Price</option>';
foreach($quoteData as $data){
echo '<div>'.$data['wpp_StateDefaultAnnual'].'</div>';
}
die();
}
And here is my AJAX in the view..
<script type="text/javascript">
$(document).ready(function () {
$('[name="select_manufacturer"]').addClass("disabled");
$.ajax({
type: "POST",
url: "<?php echo $this->action('mfr_data')?>",
success: function(result) {
$('[name="select_manufacturer"]').html(result).removeClass("disabled");
}
});
});
$('[name="select_manufacturer"]').change(function() {
var manufacture = $(this).val();
$('[name="select_model"]').addClass("disabled");
$.ajax({
type: "POST",
url: "<?php echo $this->action('mdl_data')?>",
data: 'manufacture=' + manufacture,
success: function(result) {
$('[name="select_model"]').html(result).removeClass("disabled");
}
});
});
$(document).ready(function () {
var annual = $(this).val();
$.ajax({
type: "POST",
url: "<?php echo $this->action('annual_data')?>",
data: 'annual=' + annual,
success: function(result) {
console.log('in annual success');
//console.log($result);
//alert(result);
}
});
});
</script>
Can someone help me get those values to show and to follow through to the other form PLEASE!?

Combining two dropdown selection to retrive one result ajax/php

I got two dropdowns and i need to get both values to get data from my database.
$(document).ready(function(){
$('.fabric').on('change',function(){
var fabricID = $(this).val();
console.log("fabric id_price is " + fabricID); //debugging
if(fabricID){
$.ajax({
type:'GET',
url:'cart_functions.php',
dataType: 'json',
data: {
fabric_id: fabricID
},
success:function(html){
$('.icms' + id).text(data.val);
}
});
//closing tags
$('.size').on('change',function(){
var sizeID = $(this).val();
if(sizeID){
$.ajax({
type:'GET',
url:'cart_functions.php',
dataType: 'json',
data:{
size_id: sizeID
},
success:function(html){
$('.icms' + id).text(data.val);
}
});
//closing tags
i'm sending these both values to my calculate.php
<?php header('Content-Type: application/json');
include_once '../incluedes/conn_cms.php';
if(isset($_GET["size_id"],$_GET["fabric_id"])){
$size_id=$_GET["size_id"] ;
$fabric_id=$_GET["fabric_id"] ;
$query3 =" SELECT * FROM valores_almofadas
WHERE size='$size_id'
AND price_id ='$fabric_id'";
$result = mysqli_query($conn,$query3);
while($rows = mysqli_fetch_assoc($result)){
if($_SESSION['estado'] == 'SP'){
$ICMS = $rows['icms_7'];
}else{
$ICMS = $rows['icms_12'];
}
$_SESSION['icms']=$ICMS;
} echo json_encode($_SESSION['icms']);
}
?>
So i select a fabric and then a size fabric value is my id and size is 50 or 45.
fabricid= 1 and size = 50 <-- i am sending this to my calculate.php
So i want to get back the value into a session.
and the result must be on a td..
<td class="icms'.$id.'">R$:'.$_SESSION['icms'] .'</td>
But its not working, i'm not good at ajax, can you tell me whats wrong and how can i fix these mess?
Make sure both values are always sent with the request
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
var fabricID = $('.fabric').val();
var sizeID = $('.size').val();
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'cart_functions.php',
dataType : 'json',
data : {
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(html) {
$('.icms' + this.id).text(data.val);
});
}
}
});
You are never sending both values in any ajax call, only one or the other. You need to additionally get the value for fabric_id in your .size change event and vice versa.

Ajax get value from php

Ajax
$(document).ready(function(){
$("#diklat").change(function(){
var diklat = $("#diklat").val();
$.ajax({
url: "function.php",
data: {'action': 'diklat'},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
$get_action = $_GET['action'];
if($get_action=='diklat'){
$diklat = $_GET['diklat'];
$angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan)){
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
The value didnt include in my ajax, ajax only read echo. how to get that value
You have written data: {'action': 'diklat'} but it should dilkat without quotes as its variable so in php you will get value in $_GET['action'].
Ajax
$(document).ready(function(){
$("#diklat").change(function(){
var diklat = $("#diklat").val();
$.ajax({
url: "function.php",
data: {'action': diklat},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
if($_GET['action'] == 'diklat'){
$diklat = $_GET['action'];
$angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan)){
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
You should pass 2 variables, one action and another id (diklat)
Ajax:
$(document).ready(function(){
$("#diklat").on('change', function(){
var diklat = $("#diklat").val();
$.ajax({
type: "POST",
url: "function.php",
data: {'action': 'diklat', 'diklat':diklat},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
$action = isset($_POST['action']) ? $_POST['action'] : '';
if ($action == 'diklat')
{
$diklat = isset($_POST['diklat']) ? $_POST['diklat'] : '';
$angkatan = mysql_query("SELECT id, name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan))
{
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
Two things:
For a GET request, to ask a PHP server, data should be URL-encoded (as you see here, query string is just appended to the URL...) So tell 'data' : '?action=diklat' ...
EDIT : Jquery automatically converts object to Url-encoded query string... So It work with array ! I'm confusing with angular's $http...
And also, the parameter will be in $_GET['action'] (because action is parameter name, and diklat the value... So PHP convert query string to associative array, with parameters names as keysn and values as values...

Ajax not being called by select

Hi I have a select box that when it is changed I want the value in a database to be updated via Ajax. Using the console I can see that my saveedit2.php file is not being called.
Select Box
<form><select id="workingpattern">
<?php
if(isset($workingpatterns) && !empty($workingpatterns)){
foreach($workingpatterns as $k4=>$v4) {
?>
<option value="<?php echo $workingpatterns[$k4]["workingpatternid"]; ?>">
<?php echo $workingpatterns[$k4]["text"]; ?></option>
<?php }}?>
</select></form>
Ajax:
<script>
$(document).ready(function(){
$('#workingpattern').change(function(){
var e = document.getElementById("workingpattern");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "saveedit2.php",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>
SaveEdit2.php
<?php
require_once("connect_db.php");
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
?>
There are a few issues that I see. First, I would use 'this' to get the element and use jQuery to get the value since you are using it already. Secondly, you need a name for the value in the data set:
$('#workingpattern').change(function(){
var value = $(this).val();
$.ajax({
url: "saveedit2.php",
type: "post",
data: 'value='+value,
success: function(data) {
console.log(data);
}
});
});
Try
Ajax
$('#workingpattern').change(function(){
var value = $("#workingpattern").val();
$.ajax({
dataType: "json",
url: "./saveedit2.php",
data: {'value':value},
success: function(data){
if(data['result']=="ok")
alert("Done");
else
alert("Error");
}
});
SaveEdit2.php
<?php
require_once("connect_db.php");
$ajax_result = "error";
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
if($result)
$ajax_result = "ok";
echo json_encode(array('result'=>$ajax_result));
?>

Getting the value of option chosen by the user

In my index file where the form and function are located, named:
index.php
$(function() {
$.ajax({
type: "POST",
url: "invtype.php",
data: "getrevenuetype=true",
success: function(b){
$("#revenueType").html(b)
}
})
})
<span name="revenueType" id="revenueType"></span><br/>
invtype.php
<?php
mysql_connect("","","") or die('Error: '.mysql_error());
mysql_select_db("dbname");
if(isset($_POST['getrevenuetype'])) {
$sql3 = mysql_query("SELECT * FROM chartofaccount WHERE accountnumber >= 4000 and accountnumber <= 4999");
$acct = '';
$acctrow = mysql_num_rows($sql3);
if($acctrow > 0) {
echo 'Revenue Type:<select name="rename">';
while($chartrow = mysql_fetch_array($sql3)) {
$revenueaccountname = $chartrow['accountname'];
$acct .= '<option value="$revenueaccountname"> '. $revenueaccountname .' </option>';
}
}
}
echo $acct;
echo '</select>';
My question is how will I get or what code should I put on to get the value of the option selected by the user? My purpose in getting the value is that I want to put it in another php where it will be used as var in inserting data into MySQL. already tried this code: $name = $_POST['rename']; then included 'invtype.php'; on the other php file (this is where I will use the value of option selected) but it doesn't seem to work. I know my code is all messed up and I'm really sorry about it, but guys if you can help I would really appreciate it.
you need to add , for example, ' for first time response
echo $acct;
echo '</select>';
echo '<input type="submit id="submit" value="" />';
than add js
$('#sumbit').click(function(){
var name = $('select[name=rename]').val();
$.ajax({
type: "POST",
url: "invtype.php",
data: "rename=1&name="+name,
success: function(b){
$("#revenueType").html(b)
}
})
});
than change invtype.php
if(isset($_POST['rename'])) {
$name = $_POST['name'];
//work with base
}
How's this?
Give your form an id attribute and replace the formid with it :)
$(function() {
$.ajax({
type: "POST",
url: "invtype.php",
data: "getrevenuetype=true&selectedoption=" + $('#formid option:selected').val(),
success: function(b){
$("#revenueType").html(b)
}
})
})
After the select tag is added to the page and an option is selected by the user, you can then send the selected value with a button click like this:
$("#btn").click(function(){
$.ajax({
type: "POST",
url: "server.php",
data: "value=" + $('option:selected').val(),
success: function(b){
alert('Sent successfully!');
}
})
})
$('select[name="rename"] option:select').val()

Categories