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('');
}
}
Related
I have a problem wherein I cannot put the data inside select element and make an option using the ID to append on what is inside my ajax. I got the data and it is showing in an input element but when I switched it into select element it doesn't work.
Here is the image of my form
JQuery / Ajax code
function ToolsChange(element) {
let tools_id = $(element).val();
if (tools_id) {
$.ajax({
type: "post",
url: "form_JSON_approach.php",
data: {
"tools_id": tools_id
},
success: function(response) {
var dataSplit = response;
console.log(response);
var shouldSplit = dataSplit.split("#");
var shouldNotSplit = dataSplit.split();
console.log(shouldSplit);
console.log(shouldSplit[0]);
console.log(shouldSplit[1]);
console.log(shouldSplit[2]);
$("#sel_control_num").val(shouldSplit[0]);
var specs = [];
for (i = 1; i < shouldSplit.length; i += 3) {
specs.push(shouldSplit[i])
}
$("#sel_tools_spec").val(specs.join(', '));
$("#sel_tools_id").val(shouldSplit[2]);
}
});
}
}
HTML code(I had to comment select element because it is not showing the data)
<div class="form-group">
<label> Tools Specification: </label>
<input id="sel_tools_spec" class="form-control" name="tools_specification"
data-live-search="true" readonly>
<!-- <select id="sel_tools_spec" class="form-control selectpicker" data-live-search="true">
</select> -->
</div>
PHP code
<?php
include("../include/connect.php");
if(isset($_POST['tools_id'])){
$ID = $_POST['tools_id'];
$query = "SELECT tools_masterlist.control_no, tools_masterlist.tools_id,
tools_masterlist.tools_name,
tools_spec.model_num,tools_spec.model_num_val, tools_spec.status
FROM tools_masterlist LEFT JOIN tools_spec ON tools_masterlist.tools_id = tools_spec.tools_id
LEFT JOIN tools_registration ON tools_masterlist.control_no = tools_registration.reg_input
WHERE status = 1 AND tools_name = '$ID'";
$con->next_result();
// $result=mysqli_query($con, "CALL GetAjaxForToolsRegistration('$ID')");
$result=mysqli_query($con, $query);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
// echo $row['control_no'] . "#" . $row['model_num'] . "#" . $row['tools_id'] ."#";
echo $row['control_no'] . "#" . '<option value="'.$row['tools_id'].'">'.
$row['model_num'] .'</option>' . "#" . $row['tools_id'] ."#";
}
}
else
{
}
}
?>
Don't need to split() or even return your response using echo ... #... #... .. Ok here is what you should do
The main idea in my code is: returning all the data from php/database
then control it in js/ajax and this will happen by using dataType : 'json' and echo json_encode($data)
in php
$return_result = [];
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
$return_result[] = $row;
}
}
else
{
$return_result['error'] = 'error';
}
echo json_encode($return_result);
in javascript (ajax)
$.ajax({
type: "post",
url: "form_JSON_approach.php",
dataType : 'json', // <<<<<<<<<<< here
data: {
"tools_id": tools_id
},
success: function(response) {
if(!response.error){
//console.log(response);
$.each(response , function(index , val){
// here you can start do your stuff append() or anything you want
console.log(val.control_no);
console.log(val.tools_id);
});
}else{
console.log('You Have Error , There is Zero data');
}
}
});
You are appending all datas at onces instead inside for-loop you can directly append options inside your selectpicker and refresh it.
Demo Code :
$("#sel_tools_spec").selectpicker() //intialize on load
ToolsChange() //just for demo..
function ToolsChange(element) {
/*let tools_id = $(element).val();
if (tools_id) {
$.ajax({
type: "post",
url: "form_JSON_approach.php",
data: {
"tools_id": tools_id
},
success: function(response) {*/
//other codes....
$("#sel_tools_spec").html('');
//suppose data look like this...
var shouldSplit = ["1", "<option>A</option>", "1001", "2", "<option>B</option>", "1001"]
for (i = 1; i < shouldSplit.length; i += 3) {
//append options inside select-box
$("#sel_tools_spec").append(shouldSplit[i]);
}
$("#sel_tools_spec").selectpicker('refresh'); //refresh it
/* }
});*/
}
<link rel="stylesheet " type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<div class="form-group">
<label> Tools Specification: </label>
<select id="sel_tools_spec" class="form-control selectpicker" data-live-search="true">
</select>
</div>
Since you are using bootstrap. Just do the following
$("#sel_tools_spec").empty().append('<option value="ID">LABEL</option>').selectpicker('refresh');
Source: how to append options in select bootstrap?
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.
This is my product.php file which include the following php function
<?php
function getOfferName($conn,$companyID){
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['offer_name'] ?></option>
<?php
}
}
}
?>
This product.php file include the custom-js.js file in which i am creating a html element dynamically (Select dropdown).
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$(this).parent().parent().append('<select name="" id=""><?php getOfferName($conn,$companyID) ?></select>');
}
});
Here i call php function getOfferName but it is showing me output like this
enter image description here
<select name="" id=""><!--?php getOfferName($conn,$companyID) ?--></select>
You can do by below code
getdata.php
if($_POST['action'] == 1){
$companyID = $_POST['id'];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
$html = '';
while ($row=mysqli_fetch_assoc($result)) {
$html .= '<option value="'.$row['id'].'">'.$row['offer_name'].'</option>';
}
}
echo json_encode($html);
exit(0);
}
?>
Ajax Call to Get Data
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$.ajax({
url: "getdata.php",
type: 'POST',
data: {id:id,action:1},
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if (response) {
$(this).parent().parent().append('<select name="" id="">'+response+'</select>');
} else {
//Error
}
return true;
}
});
}
});
the JavaScript file is on the client side writing code in this file will not will not create a server call that runs the PHP file.
if you want to combine JavaScript with a server call you should use ajax.
JavaScript:
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
} else {
let fd = new FormData();
let companyID = $(this).val();
fd.append('companyID', companyID);
$.ajax
({
url: "getOffer.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
let response = JSON.parse(results.responseText);
my_function.call(this, response);
}
});
}
});
// in this function you will put the append of the select box that php has created
function my_function(response) {
console.log("response", response);
}
PHP code (the file name is : getOffer.php)
<?php
$companyID = $_REQUEST['companyID'];
$options = array[];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
$options[$row['id']] = $row['offer_name'];
}
}
$resBack = (json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo ($resBack);
?>
Now in the callback function my_function as we wrote above you have an array of key value pair from the PHP.
iterate on this array in JavaScript build your option select items and append them to the select box.
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("");
}
});
});
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);
}
});