Codeigniter Ajax Dependent Dropdown doesn't work inside foreach statement - php

I made 2 dependent dropdown in the same page.
One of them is inside foreach statement and it doesn't work at all. Meanwhile the other one works well. The name of id are totally different. Both of dependent dropdown lists refer to the same function in controller. I thought its the main problem and tried to make a different function, but it didn't change anything.
VIEW :
<tr>
<td><label>Category</label></td>
<td>
<div class="form-group">
<select id="edit_category" class="form-control" name="edit_category">
<option value="">Select Category</option>
<?php foreach ($categories as $cat) : ?>
<option <?php ?> value="<?php echo $cat->id; ?>"><?php echo $cat->name
</option>
<?php endforeach; ?>
</select>
</div>
</td>
</tr>
<tr>
<td><label>Product</label></td>
<td>
<div class="form-group">
<select name="edit_product" id="edit_product" class="form-control" style="width:350px">
<option value="">Select Product</option>
</select>
</div>
</td>
</tr>
SCRIPT :
<script type="text/javascript">
$(document).ready(function() {
//DEPENDENT DROPDOWN - ADD ITEM :
$('#add_category').on('change', function() {
$('#add_product').html('<option value="">Select Product</option>');
var catID = $(this).val();
$.ajax({
url: "<?php echo site_url('admin/item/dependentDL') ?>",
method: "POST",
data: {
id_p_category: catID
},
async: true,
dataType: "json",
success: function(data) {
$('#add_product').html(data);
},
error: function(error) {
alert(error);
}
});
return false;
}); //END - DROPDOWN - ADD ITEM
//DEPENDENT DROPDOWN - EDIT ITEM :
$('#edit_category').on('change', function() {
$('#edit_product').html('<option value="">Select Product</option>');
var edit_catID = $(this).val();
$.ajax({
url: "<?php echo site_url('admin/item/dependentDL') ?>",
method: "POST",
data: {
id_p_category: edit_catID
},
async: true,
dataType: "json",
success: function(data) {
$('#edit_product').html(data);
},
error: function(error) {
alert(error);
}
});
return false;
});
});
</script>

You should try with class instead of id because id is unique and your dropdown in the foreach loop so please try with class like below
$('.add_category').on('change', function() {
$('#add_product').html('<option value="">Select Product</option>');
var catID = $(this).val();
$.ajax({
url: "<?php echo site_url('admin/item/dependentDL') ?>",
method: "POST",
data: {
id_p_category: catID
},
async: true,
dataType: "json",
success: function(data) {
$('#add_product').html(data);
},
error: function(error) {
alert(error);
}
});
return false;
}); //END - DROPDOWN - ADD ITEM
//DEPENDENT DROPDOWN - EDIT ITEM :
$('.edit_category').on('change', function() {
$('#edit_product').html('<option value="">Select Product</option>');
var edit_catID = $(this).val();
$.ajax({
url: "<?php echo site_url('admin/item/dependentDL') ?>",
method: "POST",
data: {
id_p_category: edit_catID
},
async: true,
dataType: "json",
success: function(data) {
$('#edit_product').html(data);
},
error: function(error) {
alert(error);
}
});
return false;
});

Related

Problem to recover variable passed by ajax to php

I have a "POST" ajax call to getSegnalazioniMappa.php.
When I try to recover the passed variable I have notice: undefined variable.
JavaScript code:
$(document).ready(function(){
$('#gravita').change(function(){
var index = document.getElementById("gravita").value;
$.ajax({
method: "POST",
data:{index:index},
url: "getSegnalazioniMappa.php",
processData: false,
success: function(data){
console.log(data);
},
error: function(e) {
alert(e.responseText);
},
dataType: "JSON"//set to JSON
});
});
});
This is getSegnalazioniMappa.php
<?php
require('../../../setup/database_connection.php');
if(isset($_POST['index'])){ //this one is always false
$index = $_POST['index'];
}
?>
HTML
<select name="gravita" onchange="updateTable(this.value)" style="width: 130px;" class="form-control" id="gravita" required>
<option value="all" selected>Tutto</option>
<option value="bassa">Bassa</option>
<option value="media">Media</option>
<option value="alta">Alta</option>
</select>
You got undefined in error because you did not get any response from the server. you can see in console.
also where is onchange="updateTable(this.value)" defined ???
$(document).ready(function(){
$('#gravita').change(function(){
var index = $(this).val();
$.ajax({
method: "POST",
data:{index:index},
dataType: "JSON",
url: "getSegnalazioniMappa.php",
processData: false,
success: function(data){
console.log(data);
},
error: function(xhr,textStatus,err) {
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="gravita" style="width: 130px;" class="form-control" id="gravita" required>
<option value="all" selected>Tutto</option>
<option value="bassa">Bassa</option>
<option value="media">Media</option>
<option value="alta">Alta</option>
</select>
Your PHP code should be like this:-
<?php
if(isset($_POST['index'])){
echo $index = $_POST['index'];
}
?>
ajax request should be :-
<script type="text/javascript">
$(document).ready(function(){
$('#gravita').change(function(){
var index = document.getElementById("gravita").value;
$.ajax({
method: "POST",
data:{index:index},
url: "getSegnalazioniMappa.php",
processData: true,
success: function(data){
alert(data);
console.log(data);
},
error: function(e) {
alert(e.responseText);
},
dataType: "JSON"//set to JSON
});
});
});
</script>
processData should be true.

Unable to send POST value using AJAX

I have two seperate files, one bargraph.html, and the other data.php.
Bargraph.html is as follows:
<form method="POST" name="dataform" action="">
<select name="data1" id="data1-value">
<option value="DateRecorded">DateRecorded</option>
<option value="InletVoltage">InletVoltage</option>
<option value="InletCurrent">InletCurrent</option>
<option value="ActivePower">ActivePower</option>
<option value="PowerFactor">PowerFactor</option>
<option value="SystemID">SystemID</option>
</select>
<select name="data2" id ="data2-value">
<option value="DateRecorded">DateRecorded</option>
<option value="InletVoltage">InletVoltage</option>
<option value="InletCurrent">InletCurrent</option>
<option value="ActivePower">ActivePower</option>
<option value="PowerFactor">PowerFactor</option>
<option value="SystemID">SystemID</option>
</select>
</form>
<script type="text/javascript">
$('#data1-value').change(function(){
var data1Value = $(this).val();
$('#data2-value').change(function(){
var data2Value = $(this).val();
$.ajax({
type: 'post',
url: 'data.php',
dataType: 'html',
data: {data1, data2: data1Value, data2Value},
success:function(data){
alert(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
},
complete: function(){
}
});
})});
</script>
A section of data.php is as follows:
if (isset($_POST['data1'])) {
$opp1 = $_POST['data1'];
$opp2 = $_POST['data2'];
} else {
$opp1 = 'SystemID';
$opp2 = 'ApparentPower';
}
$sql = "SELECT $opp1, $opp2 FROM RaritanMachineDataa";
In my bargraph.html I have two drop down menus. I want the options selected from the drop down menu to be sent using AJAX to my data.php file to perform a select statement on my database.
Currently when I run my code, it's returning an error
Uncaught ReferenceError: data1 is not defined
And this is pointing to line 53:
url: 'data.php',
Could someone give me some assistance on this please as I do not know how to fix this.
UPDATE: (Code below):
<script type="text/javascript">
$('#dataform').submit(function(e){
var data1Value = $("#data1").val();
var data2Value = $("#data2").val();
$.ajax({
type: 'post',
url: 'data.php',
dataType: 'html',
data: {data1, data1Value, data2: data2Value},
success:function(data){
alert(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
},
complete: function(){
}
});
})});
</script>
Returning error:
Uncaught SyntaxError: Unexpected token }
On line (at the 2nd last line)
})});
I have tried removing the bracket, and curly bracket but cannot seem to get it to run. What have I done wrong? Thanks for the assistance
UPDATE (Submit button not POSTING data):
<option value="PowerFactor">PowerFactor</option>
<option value="SystemID">SystemID</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<script type="text/javascript">
$('#dataform').submit(function(e){
var data1Value = $("#data1").val();
var data2Value = $("#data2").val();
$.ajax({
type: 'post',
url: 'data.php',
dataType: 'html',
data: {data1, data1Value, data2: data2Value},
success:function(data){
alert(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
},
complete: function(){
}
});
e.preventDefault();
});
Your Error is here:
$.ajax({
type: 'post',
url: 'data.php',
dataType: 'html',
data: {data1, data2: data1Value, data2Value}, <-- Your error is here
Change this line to:
data: {data1: data1Value, data2: data2Value}
Also I've just noticed that you are doing this
('#data1-value').change(function(){
var data1Value = $(this).val();
$('#data2-value').change(function(){
var data2Value = $(this).val();
I don't believe that $('#data2-value').change is ever getting called. I suggest you handle the submission of the form after both values have been set!!!
With #Devpro comment, your dropdown menus now need to have an assigned id in order for this submit function to work
HTML
<select name="data1" id="data1-value"> to <select id="data1" name="data1" id="data1-value">
<select name="data2" id ="data2-value"> to <select id="data2" name="data2" id ="data2-value">
JQuery
$('#dataform').submit(function(e) {
var data1Value = $("#data1").val();
var data2Value = $("#data2").val();
//ajax submit with my edits
$.ajax....
e.preventDefault(); //prevent page refresh.
});

How to post one variable in ajax call to multiple php file's?

How to post one variable in ajax call to multiple php file's using URL method..
My data is as follow..
<select name="districts" id="district_list" class="update" onChange="getDist(this.value)" >
<option value="d1">east</option>
<option value="d2">west</option>
</select>
I want to pass these id value to another two php files using ajax and i tried as follow..
function getState(val) {
$.ajax({
type: "POST",
url: "get_dist.php",
url: "get_city.php",
data:'states_id='+val,
success: function(data){
$("#district_list").html(data);
}
});
}
Please try this
<select name="districts" id="district_list" class="update" onChange="getDist(this.value) ; getCity(this.value)" >
<option value="d1">east</option>
<option value="d2">west</option>
</select>
<script>
function getDist(val){
$.ajax({
type: "POST",
url: "get_dist.php",
data:'states_id='+val,
success: function(data){
$("#district_list").html(data);
}
});
}
function getCity(val){
$.ajax({
type: "POST",
url: "get_city.php",
data:'states_id='+val,
success: function(data){
$("#city_list").html(data);
}
});
}
</script>

can i fetch and populate different fields using function(data) jquery?

i want to populate two fields when some one fill up card no.
<input type="text" id="name" name="name" class="form-control" Value="<?php echo $grow['name']; ?>">
<input type="text" id="address" name="address" class="form-control" Value="<?php echo $grow['address']; ?>">
but this code populate field one by one. can any one suggest be better code for populating two fields from database. Thank you
jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k=$(this).val();
var q="name";
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q='+q,
cache: false,
success: function(data)
{
if(data){
$("#name").val(data);
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
$("#address").val(data);
}
}
});
}else
$("#name").val("");
$("#address").val("");
}
});
});
});
</script>
getresult.php
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select * from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
echo $row[$q];
?>
Try to extract both name and address from database and json them
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select address,name from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
$result = array(
'name'=>$row['name'],
'address'=>$row['address']);
echo json_encode($result);
After that parse them via jquery
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
var parsedData = jQuery.parseJSON(data);
$("#name").val(parsedData.name);
$("#address").val(parsedData.address);
}
}
});
Javascript Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k = $(this).val();
var q = "name";
$.ajax({
type: 'POST',
url: "getresult.php",
data: 'k='+k,
cache: false,
success: function(data)
{
var jsonArr = $.parseJSON(data);
if(typeof response =='object')
{
$("#name").val(jsonArr.name);
$("#address").val(jsonArr.address);
}
else
{
$("#name").val("");
$("#address").val("");
}
}
});
});
});
</script>
PHP Code:
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k = $_POST['k'];
$sql = mysql_query("select * from inward where krishi='$k'");
$row = mysql_fetch_assoc($sql);
echo json_encode(array('name' => $row['name'], 'address' => $row['address']);
?>

How to populate 2 selectbox from database using php and ajax

I have a problem, how to pass an argument with ajax in url: <?php echo base_url() . 'user_m/getAdministrator'; ?>" argument,
Because I tried to populate a selectbox based on another but I didn't have success.
html:
<div class="form-group">
<label>Denumirea intreprinderii:</label>
<select class="form-control marg-left-10" id="firm">
<?php if($all_firms): ?>
<?php foreach($all_firms as $firm): ?>
<option value="<?php echo $firm['id_firm']; ?>"><?php echo $firm['name_firm']; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</div>
<div class="form-group">
<label>Administrator</label>
<select class="form-control marg-left-10" id="admin">
</select>
</div>
php:
public function getAdministrator()
{
$id_firm = $_POST['id_firm'];
$this->load->database();
$sql = $this->db->query("SELECT * FROM users,firms WHERE firms.id_firm = users.fk_firm and users.id = ");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
return $this;
}
script:
$(document).ready(function()
{
$("#firm").change(function()
{
var id_firm=$(this).val();
var dataString = 'id_firm='+ id_firm;
$.ajax
({
type: "POST",
url: "<?php echo base_url() . 'user_m/getAdministrator'; ?>",
data: dataString,
cache: false,
success: function(html)
{
$("#admin").html(html);
}
});
});
});
Help me please.The first select box gets populated but the second doesn't.Please Help me.Exist a method to pass an argument to user_m/getAdministrator method? HELP ME PLEASE GUYS!!!!!
Php in js is not a good practice, try to write this on your main php file before calling the script
<script>
var base_url = "<?=base_url()?>";
</script>
and then in your js file:
$.ajax
({
type: "POST",
url: base_url+"user_m/getAdministrator",
data: dataString,
cache: false,
success: function(html)
{
$("#admin").html(html);
}
});
also, you can send data this way:
data: { id_firm: id_firm },

Categories