I am trying to populate an initial customer select box with results from PDO MySql via PHP. Then I would like the second contact select box to update with additional information related to what was chosen in the first box. I can't get the second script to work. I think the problem is in my ajax script because the PHP scripts work fine when ran on there own.
The Primary Script
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact").change(function(){
var cid = $("#cid").val();
$.ajax({
type:"post",
url:"contact.php",
data:"cid="+cid,
success: function(data) {
$("#contact").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="customer" id="customer">
<option>-Select a Customer-</option>
<?php
include ("function.php");
include("connect.php");
$id = $_SESSION['profile']['id'];
foreach($db->query("SELECT * FROM customers WHERE pid = '$id'") as $row) {
echo "<option value=" . $row['id'] . ">" . $row['name'] . "</option>";
}
?>
</select>
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
</body>
</html>
The Contact script
include("connect.php");
$cid = $_POST["cid"];
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
Maybe your second function should start on #customer change
I see you used the contact select in ajax not customer as you described. However the code you wrote, you used the contact selector with change event, But the contact select box contain only one value, How can it change ??
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
The previous select should has more than option to can change. Or I think you mean the #customer instead contact as following:-
$("#customer").change(function(){
// your code;
});
Why not just encode a JSON response with the ids and names?
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
$arr[] = array("id" => $row['id'], "name" => $row['name']);
}
echo json_encode($arr);
Then in your ajax response, you could do
$(document).ready(function () {
$("#customer").change(function () {
var cid = $("#customer").val();
$.ajax({
type: "post",
url: "contact.php",
data: {cid: cid},
success: function (data) {
var options = [];
$.each(data, function () {
options.push('<option value="' + this.id + '">' + this.name + '</option>');
});
$("#contact").html(options.join(""));
}
});
});
});
Related
I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.
OK so I have been for 2 days trying to do this but for some reason, doesn't matter in what way I do it, it doesn't work (I tried different way with json_encode and then taking care of creating the elements with javascript, I've tried to echo the in the php itself, I've tried to return it, nothing really works)
What I'm trying to do is use AJAX to ask the server for a specific script (right now test.php) and then return the <option>'s so I can populate a <select>, so I'm trying to populate a comboBox, what seems to be happening is that the AJAX response is coming out empty, I tried to output the result and it was outputting an empty value. Can anyone please help me, I'm really desperate at this point, it should have been easy, I've spent hours on stack overflow trying to find the problem, I've debugged the code to the best of my ability, I've read everything relevant in the jquery documentation. well anyways my setting my suffering aside, here's the code:
comboStaging.php :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form id="testForm">
<select name="states" id="states">
<?php
$odb = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "SELECT id, name FROM `database`.pt_state";
$data = $odb->prepare($query);
$data->execute();
while ($row = $data->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
//print_r($row);
}
?>
</select>
<select name="cities" id="cities">
</select>
</form>
<script type="text/javascript">
$(document).ready(function () {
console.warn("test");
function loadFirst() {
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data: "id=1",
dataType: "html",
success: function (data) {
console.warn("test2")
console.warn(data);
}
});
}
console.warn("test3");
loadFirst();
});
$("#states").change(function () {
var ID = document.getElementById("states").valueOf().value;
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data: "id=" + ID,
success: function (r) {
document.getElementById("cities").innerHTML = r;
}
});
});
</script>
</body>
</html>
Test.php:
<?php
header('Content-Type: text/html');
require_once $_SERVER['DOCUMENT_ROOT'] . "/resources/scripts/php/conn/dal.php";
$stmt = $DB_con->prepare('SELECT id, name FROM `database`.pt_city WHERE state_id=:state');
$stmt->bindParam(':state', $_GET['ID']);
$stmt->execute();
if($stmt->rowCount() > 0 ) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$test = $test . '<option value="' . $row['id'] . '"id="optionTest">' . $row['name'] . '</option>';
}
}
return $test;
?>
Dev console:
I am building a form that will have three related drop down menus. First one is store locations, second Equipment at this location, third is components at this location.
So when I pick a location the page sends an AJAX request to load the select values for the equipment at this location. And when I pick the equipment it should load the components that belong to that equipment.
The third drop down for components is what's not appearing.
So my first drop down goes like this off the main file with the divs where the drop downs are added via AJAX calls:
<div class="input-group">
<strong>Select A Store Location:</strong>
<select class="form-control selectDesk" name="Location_ID" id="Location_ID">
<option value=1>HT1</option>
<option value=2>HT2</option>
<option value=3>HT3</option>
<option value=4>HT4</option>
<option value=5>HT5</option>
<option value=6>HT6</option>
</select>
</div>
<div id="equipment">
</div>
<div id="component">
</div>
The second drop down is dynamic loaded off a different file and inserted in a div via Jquery and AJAX. This is the code to make that happen
<?php
include('DBConnect.php');
$locID = $_POST['loc_id'];
$equipSQL ="SELECT Equipment_ID, Equipment_Name FROM Equipment WHERE Location_ID = $locID";
$equipResult = $my_dbhandle->query($equipSQL);
$numResults = $equipResult->num_rows;
?>
<strong>Select Equipment:</strong>
<div class="input-group">
<select class="form-control" name="Equipment_ID" id="Equipment_ID" style="min-width: 375px;">
<option value="0">No Equipment Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $equipResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Equipment_ID'] . ">" . $row['Equipment_Name'] . "</option>\n";
}
?>
</select>
</div>
And my third drop down is also loaded off another file via Jquery and AJAX
<?php
include('DBConnect.php');
$equipID = $_POST['equip_id'];
$compSQL ="SELECT Component_ID, Component_Name FROM Components WHERE Equipment_ID = $equipID";
$compResult = $my_dbhandle->query($compSQL);
$numResults = $compResult->num_rows;
?>
<strong>Select Component:</strong>
<div class="input-group">
<select class="form-control" name="Component_ID" id="Component_ID" style="min-width: 375px;">
<option value="0">No Component Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $compResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Component_ID'] . ">" . $row['Component_Name'] . "</option>\n";
}
?>
</select>
</div>
The Jquery is as follows:
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
}
});
}).change();
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
</script>
So again, the first AJAX request for the second equipment drop down is loaded just fine. But the third drop down for the component select is not.
Thank you in advance for your help!
Hi I have modified your code please use this.
If this will work then I will explain the script
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
initSecond();
}
});
}).change();
function initSecond(){
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
}
</script>
Try to execute this javascript :
$("#Equipment_ID").change(function(){ ....
... after the first ajax call, like this:
success: function (r) {
$('#equipment').html(r);
$("#Equipment_ID").change(function(){
...
...
}
}
Also the third dropdown should be:
<select name="Component_ID" and id="Component_ID" ...
I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work
I want to load a page with variables from a form and it seems it doesn't get my select value. I'm new to JavaScript and I need this instead doing a serialize to get values and then use .load().
Here is my code:
<?php
include('dbconfig.php');
$id=$_GET['id'];
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function filtreaza_tip () {
var tip = document.getElementById("tip").value;
var id_local= document.getElementById("id_local").value;
$( "#tipuri_rezervare" ).load("select_tip_rezervare.php?id="+id_local+"&tip="+tip);
}
</script>
</head>
<body>
<form id="tip" method="post">
<input type="hidden" name="id_local" id="id_local" value="<?php echo $id;?>">
<select name="tip" id="tip" onchange="filtreaza_tip();">
<option value="0">Selectati Tipul</option>
<?php
$stmt = $dbh->prepare("SELECT *
FROM Tip_Rezervare
INNER JOIN Local ON Local.ID_Local=:id_local
INNER JOIN Leg_Tip_Local ON Tip_Rezervare.ID_Tip=Leg_Tip_Local.ID_Tip and Leg_Tip_Local.ID_Local=:id_local");
$stmt->bindParam(':id_local', $id, PDO::PARAM_INT);
$stmt->execute() ;
while ($row = $stmt->fetch()) {
$local=$row['Denumire_Local'];
echo '<option value="'.$row['ID_Tip'].'">'.$row['Nume'].'</option>';
}
echo'</select>';
?>
<div id="tipuri_rezervare">
</div>
</body>
</html>
I have a working one with serialize but I don't want that. Here is the working code:
function filtreaza_tip ()
{
var datastring = $("#tip").serialize();
$.ajax({
type: "POST",
url: "tip_rezervare.php",
data: datastring,
success: function(data) {
$( "#tipuri_rezervare" ).load('select_tip_rezervare.php?',data);
}
});
}
Your form id and dropdown id are same.
Thats the reason you are getting the issue.
Change the ids it will work fine.
Load uses POST method so you can just do this:
var tip = document.getElementById("tip").value;
var id_local= document.getElementById("id_local").value;
$( "#tipuri_rezervare" ).load("select_tip_rezervare.php, {tip: tip, id: id_local});
Then you can get your values on your select_tip_rezervare.php page with $_POST['tip'] and $_POST['id'].
Use the jquery method $.val() like that :
$("#tip").val(); // Return the input / select value of the selector
Check the jQuery Api : http://api.jquery.com/val/