How i pass the dropdown value to ajax controller? - javascript

This is my dropdown box:
I am sending drop down value to ajax controller function to get some value.But the value is not passed correctly and i can't find the error;
My ajax code:
<script type="text/javascript">
$(function() {
$('.states').change(function(){
$id = $('.states').val();
$.ajax({
type : "POST",
url : "<?php echo base_url();?>Reports/Fetch_Item",
data :{id:$(this).val()},
success : function (data) {
alert(data);
var obj=jQuery.parseJSON(data);
}
});
});
});
</script>
My controller code;
public function Fetch_Item(){
$name = $this->input->post('id');
$result = $this->db->query("SELECT * FROM acc_master WHERE accName = '$name'")->row();
echo json_encode($result);
}
Front drop down box :
<div id="item3">
Party Name Selection:
<select multiple="multiple" style="width:400px;height:205px;" name="PName"id="Name" class="form-control states">
<option value=""></option>
</select>
<?php echo form_error('Area', '<div class="text-danger">', '</div>'); ?><br><br><br></div>
Dropdown ajax code:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "<?php echo base_url();?>Reports/get_countries1",
data:{id:$(this).val()},
beforeSend :function(){
$('.states').find("option:eq(0)").html("Please wait..");
},
success: function (data) {
$('.states').find("option:eq(0)").html("");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.states').append(option);
});
}});
});
</script>

Can you try this
<script type="text/javascript">
$(function() {
$('.states').change(function(){
var id = this.value;
$.ajax({
type : "POST",
url : "<?php echo base_url();?>Reports/Fetch_Item",
data :{'id':id,},
success : function (data) {
alert(data);
var obj=jQuery.parseJSON(data);
}
});
});
});
</script>

The $(this).val() returns an array, you have to change your backend code to handle the array.
Something like below.
public function Fetch_Item(){
$name = implode(",", $this->input->post('id'));
$result = $this->db->query("SELECT * FROM acc_master WHERE accName in ('$name')")->rows();
echo json_encode($result);
}
Note: Fetch_Item methon sql will return multiple results so you have to handle this as well.

Related

change function ajax call from php file

The following code consists of drop-down "(id=name" which populates from "listplace.php" through ajax call which works correctly.
Now I am trying to make another ajax call using the change function. when I select the particular item already populated on dropdown box it has to pass the selected item name1 in 'where' query to dataprod.php and has to display the products by clearing the existing products list available.
I am doubtful over the $name1 response from dataprod.php. Please help!!
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}else {
alert('No data found!');
}
}
});
</script>
ajax 2
$(document).ready(function(){
$("#name").change(function(){
var name1 = this.value;
$.ajax ({
url: "dataprod.php",
data: {place: '<?= $_GET['name1'] ?>'},
success: function (response) {
$('.products-wrp').html('')
$('.products-wrp').html(response);
}
}else {
$('.products-wrp').html('');
}
}
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
Since you are calling ajax event on element which is loaded via ajax action so the change event is not bind and nothing is happend.
For ajax 2 action use below code.
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
url: "dataprod.php",
data: {place: '<?= $_GET['name1'] ?>'},
success: function (response) {
$('.products-wrp').html('')
$('.products-wrp').html(response);
}
}else {
$('.products-wrp').html('');
}
}

Sent value and show output when select tag change

I new in term of using jQuery.
I practice using native php ajax, but for this time I need to learn jQuery for the current technology and demand.
I sent "types" value method POST to other page (ajaxInfo.php) when the tag change.
After the select tag change, it should show the result at <div id="showList"> that come from database (MySQL). But nothing happen.
Below are the source code.
Body
<select id="form-types" class="col-xs-10 col-sm-5" name="types">
<option value="">PLEASE CHOSE</option>
<option value="STATE">STATE</option>
<option value="FACULTY">FACULTY</option>
<option value="PROGRAME">PROGRAME</option>
</select>
<div id="showList"></div>
jQuery AJAX
<script type = "text/javascript" >
$(document).ready(function () {
$("select#form-types").change(function () {
var types = $("select#form-types").val();
if (types != null) {
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function (response) {
$("#showList").html(response);
}
}
});
});
});
</script>
Post Page (ajaxInfo.php)
<?php
if (isset($_POST["types"]) === TRUE){
$types = $_POST["types"];
}
else{
$types = null;
}
include '../dbco.php';
$query = $dbc -> query ("SELECT child FROM infobase WHERE parent='$types'");
if ($query -> num_rows > 0){
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc()){
echo "$count" . $result['child'] . "<br />";
count++;
}
}else{
echo "NO " . $types . " REGISTERED";
}
?>
Thank You.
You are using id (form-types) for your select input field. but your are tying to targeting another id (form-jenis).
use same named id for select input field and in your jquery selector.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(e){
e.preventDefault();
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'show.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
You have a missing bracket
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
}); // add this
</script>
I found out that my ajax jQuery function do not have close pair, so i decide to add it and it work.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}); // Add This
}
});
});
</script>
After the code running good, i also found out the error at ajaxInfo.php, the count inside the loop missing $ symbol
if ($query -> num_rows > 0)
{
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc())
{
echo "$count" . $result['child'] . "<br />";
$count++; //HERE
}
}
Thanks for the people that help.

Getting the data from database using a drop down

here i have written the code for a functionality using jquery-ajax in CODEIGNITER where i need to pass the value of the drop down to the database using 'ajax post method' execute a query and get and display the results/data in the same view page using onChange, but the problem is onChange no change is visible.
Please help me out on this.
view.php
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" name="ProductCategoryID" id="item_code" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="'.$row->ItemCode.'">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group" id="description">
</div>
<script src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>" type="text/javascript"></script>
<script type="text/javascript">
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#item_code').append('<textarea value="' + id + '">' + name + '</textarea>');
}
});
$('#item_code').trigger('chosen:updated');
});
</script>
Controller.php
<?php
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('Gst_model');
$this->load->model('User_model');
$this->load->model('Report_model');
$this->load->helper('url');
}
function get_description()
{
$id = $this->input->post('id');
echo(json_encode($this->Report_model->get_description($id)));
}
}
Model.php
function get_description($item_code)
{
$result = $this->db->where('ItemCode', $item_code)->get('gst_itemmaster')->result();
$id = array('0');
$name = array('0');
for ($i=0; $i<count($result); $i++)
{
array_push($id, $result[$i]->ItemDescription);
array_push($name, $result[$i]->ItemDescription);
}
return array_combine($id, $name);
}
Your problem is that updating chosen-select dropdowns is a bit tricky. After you've updated your option list you have to call something like $('.my_select_box').trigger('chosen:updated'); Take a look at the chosen-select docs here.
Just put this after your ajax call at the end of your change() function:
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#state').append('<textarea value="' + id + '">' + name + '</option>');
}
});
$('#item_code').trigger('chosen:updated');
});

Dynamically created select list makes mutilple calls to javascript function

I have created dynamically multiple select list. On click of channel name it should get its type. The problem is once click on select list its repetitively calls java script function causing ajax to load multiple times.
HTML CODE:
<td>
<SELECT name="channel_name[]" onclick ="get_type(this)"; required class='channelname'>
<option value="">Select...</option>
<?php foreach($channel_list as $row) {
$channelid = $row['channelid'];
$channelname = $row['channelname'];
if($U_channelid==$channelid)
{
$s = "selected = selected";
}
else
{
$s = "";
}
echo "<option value='$channelid' $s>".$channelname."</option>";
?>
<!-- <OPTION value='<?php echo $channelid ?>' $s ><?php echo $channelname?></OPTION> -->
<?php } ?>
</SELECT>
</td>
Javascipt code:
function get_type()
{
$(".channelname").live("change", function() {
var channel_id = $(this).find("option:selected").attr("value");
var _this = $(this); //Save current object
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});
}
remove onclick ="get_type(this)" from select tag // because you already using $(".channelname").live("change", function() { in javascript
put this
<SELECT name="channel_name[]" required class='channelname'>
and javascript
$(".channelname").change(function() {
var channel_id = $('.channelname').find("option:selected").attr("value");
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});

How to get the returned value from Ajax Request and assigned it into an element?

I need a little help here. I am creating a dynamic dropdown list but I don't know how to display the ajax result in an element.
Here's my scenario:
The user will choose a state in the dropdown.
After choosing the code will send an ajax request
After sending, display the result in a select option named 'cities'
So there are 2 select box. One is 'state' and second is 'cities'.
Here's my code:
Here's my jquery for accessing the controller
$('#state').on('change',function(){
var state_code = $('#state').val();
var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';
$.ajax({
type: 'POST',
url: city_url,
data: '',
dataType: 'json',
success: function(){
//
}
});
});
Here's my function in the model
public function getCity($code){
$sql = "SELECT id,name FROM ref_cities WHERE province_code = '".$code."'";
$result = $this->db->query($sql);
return json_encode($result->result_array());
}
Here's the controller part
public function displayCity($code){
$x = json_decode($this->locations_model->getCity($code));
return print_r($x);
}
Here's the code in my selecting the city code
<select id="state" name="state">
<option value="">---Select State---</option>
<?php
$decode_city = json_decode($city,true);
foreach($decode_city as $m){
echo "<option value='".$m['code']."' ".set_select('state',$m['code']).">".$m['name']."</option>";
}
?>
</select>
Here's the part where should I put the ajax result
<select id="city" name="city">
<option value="">---Select City---</option>
<!-- INCLUDE LOOP TO DISPLAY cities -->
</select>
Try this,
jQuery.ajax({
type: 'POST',
url: city_url,
data: '',
dataType: 'json',
success: function(data){
//you will get the result in data
//jQuery("#someDiv").html(data);
//The parsed data is something like below
jQuery.each(jQuery.parseJSON(data), function(key,value){
jQuery("#city").append('<option value ="'+value+'">'+value+'</option>');
});
}
});
Hope its get fixed.
your success function must be something like this
$.each($.parseJSON(data), function(key,value){
$('<option/>','{value:'+value+'}').appendTo('#yourparent');
});
$('#state').on('change',function(){
var cityList = '';
var state_code = $('#state').val();
var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';
$.ajax({
type: 'POST',
url: city_url,
data: '',
dataType: 'String',
success: function(data){
$('#city').html(data);
}
});
});
you can rewrite your code like this. it will work
or you can try this
public function getCity($code){
$sql = "SELECT id,name FROM ref_cities WHERE province_code = '".$code."'";
$result = $this->db->query($sql);
$cities = $result->result_array();
$options = '';
foreach($cities as $city){
$options .= '<option value="'.$city["id"].'">'.$city["name"].'</option>';
}
return $options;
}
this should work try this
Do something like this
$('#state').on('change',function(){
var state_code = $('#state').val();
var city_url = 'controller_file.php?state_code=<?php echo state_code; ?>';
$.ajax({
type: 'GET',
url: city_url,
data: '',
dataType: 'json',
success: function (response) {
var response_arr = JSON.parse(response);
$.each(response_arr ,function(index,value)
{
$("#city").append("<option value="+value.id+">"+value.name+"</option>");
});
}
});
});
in controller_file.php file write this
displayCity($_GET['state_code']);
I manage to answer my question. Here's what I did
In my Controller I removed the json_decode(). And now I have this
public function displayCity($code){
$x = $this->locations_model->getCity($code);
echo $x;
}
Then I can access it in console.
$.ajax({
type: 'POST',
url: city_url,
data: '',
dataType: 'json',
async: false,
success: function(i){
console.log(i);
}
});

Categories

Resources