i could not get the data in my showdata div - ajax

I want the list all the details from tow tables using single id without refreshing the Page using Ajax
This is my button and div:-
<button id="brand" data-b_id="21">brand</button>
<div id="#showdata"></div>##
This is my javascript:-
$('#brand').click(function() {
show_product();
function show_product() {
var b_id = $('#brand').data('b_id');
//alert(bid);
$.ajax({
type: 'POST',
url: '<?php echo base_url('index.php/Airtel/get_bdid')?>',
dataType: 'JSON',
data: {
b_id: b_id
},
success: function(data) {
var html = '';
var i;
for (i = 0; i < data; i++) {
html += '<tr>' +
'<td>' + data[i].b_name + '</td>' +
'<td>' + data[i].d_name + '</td>' +
'<td>' + data[i].d_id + '</td>';
};
$('#showdata').html(html);
}
});
}
});
This is my controller:-
public function get_bdid(){
$b_id=$this->input->post('b_id');
$data=$this->mymod->get_bdid($b_id);
echo json_encode($data);
}
This is my model:-
public function get_bdid($b_id){
$this->db->where('b_id',$b_id);
$this->db->select('*');
$this->db->from('brand');
$this->db->join('dth', 'dth.b_name = brand.b_name');
$query = $this->db->get();
return $query->result();
}

Perhaps, there are many errors in browser developer mode.
plz Check your javascript
success: function(data) {
console.log(data);
}
"get_bdid" controller is retrun "json" data type
success: function(data) {
var obj = JSON.parse(data);
console.log(obj);
// or loop
}

Related

Ajax POST request not working - in dependency dropdown menue in laravel blade

Here I have a dropdown menu is like - countryName->CityName->ThanaName (ThanaName depends on CityName and CityName depends on countryName)
First of all I fetch country name from database table.
I passed country name through ajax as like as below.
$(document).on('change', '[name=country]', function() {
var country = $(this).val();
get_city(country);
});
function get_city(country) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-city')}}",
type: 'POST',
data: {
country_name: country
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="city"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
And the route in web.php is like Route::post('/get-city', 'CityController#get_city')->name('get-city');
And in CityController , the get_city method is like
public function get_city(Request $request) {
$country_info = Country::where('status',1)->where('name', $request->country_name)->first();
$cities = City::where('country_id', $country_info->id)->get();
$html = '';
foreach ($cities as $row) {
// $val = $row->id . ' | ' . $row->name;
$html .= '<option value="' . $row->name . '">' . $row->getTranslation('name') . '</option>';
}
echo json_encode($html);
}
And this is working absolutely fine and it returns cityname according to its country name. But the problem is for thanaName that depends on cityName. For this my route is like Route::post('/get-thana', 'ThanaController#get_thana')->name('get-thana');
In ThanaController, the get_thana method is like
public function get_thana(Request $request) {
$city_info = City::where('name', $request->city_name)->first();
$thanas = Thana::where('city_id', $city_info->id)->get();
$html = '';
foreach ($thanas as $row) {
// $val = $row->id . ' | ' . $row->name;
$html .= '<option value="' . $row->name . '">' . $row->getTranslation('name') . '</option>';
}
echo json_encode($html);
}
and the ajax code is like
$(document).on('change', '[name=city]', function() {
var city = $(this).val();
console.log(city);
console.log('Here');
get_thana(city);
});
function get_thana(city) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-thana')}}",
type: 'POST',
data: {
city_name: city
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="thana"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
But it show
POST http://localhost/rul/ecom/get-thana 500 (Internal Server Error)
Here is my ajax full code.
<script type="text/javascript">
$(document).on('change', '[name=country]', function() {
var country = $(this).val();
console.log(country);
console.log('country');
get_city(country);
});
function get_city(country) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-city')}}",
type: 'POST',
data: {
country_name: country
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="city"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
//start another
$(document).on('change', '[name=city]', function() {
var city = $(this).val();
console.log(city);
console.log('Here');
get_thana(city);
});
function get_thana(city) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-thana')}}",
type: 'POST',
data: {
city_name: city
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="thana"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
</script>
In browser network tab the error show like the below image when I change city.
enter image description here
Browser console tab: enter image description here

how to use the same ajax call on the created dropdown list

dears , i have one table to show the list of category and i need to add unlimited drop down list which will be nested from the parent
like
category A
Category B , if selected B it will add another dropdown and added it into data base and will add another dropdown list sub b1 , sub 2 and if user select sub 2 will do the same
can anyone help
$(document).ready(function(){
//$('.form-control').change(function(){
$('select.form-control').on('change', function () {
var selectedCategory = $(this).children("option:selected").val();
var counter = 1;
//alert( $(this).find('option:selected').text());
//var deptid = $('#category option:selected').attr("id");
var name = "Sub "+ $(this).children("option:selected").text();
if(selectedCategory!=''){
$.ajax({
url: "<?php echo base_url(); ?>category/add_new",
type: 'POST',
data: {'category_parent':selectedCategory,'category_name':name},
dataType: 'json',
async: false ,
cache:false,
success:function(data){
alert(data);
if($('#category'+data).length)
return;
else{
$("#groupd").after('<div id="sub'+data+'" class="form-group">' +
'<label>' +name +' : </label>' +
'<select class="form-control" name="dropdown' + counter + '" id="category'+data+'">' +
// Add your options here...
'<option>Please Select</option>'+
'<option value="'+data+'">'+name +'1</option>'+
'<option value="'+data+'">'+name +'2</option>'+
'</select></div>');
counter++;
}
},
error:function(){
alert('error');
}
});
}
});
});
</script>

How to use for loop in ajax success function?

This is my alert output result:
The above picture array is my result that is get from table using ajax request.but i don't know how to use in for loop and i have tired in for loop the value is splitted one by one like
My code
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
alert(data);
var result = data;
var arr = result;
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
}
});
});
</script>
You can modify your script like this and then do whatever Logic you want for the response
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
myGoodFunctionToHandleResponse(data);
}
});
});
function myGoodFunctionToHandleResponse(data){
for(let i in data){
console.log(data[i]);
}
}
I have forgot to put JSON.parse() this function after success function and so i didn't get the correct result so far.
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
var result = JSON.parse(data)
var mycars = result;
for (i in mycars)
{
if( mycars[i].dc == "C"){
var credit = mycars[i].Amt;
}
else{
var debit = mycars[i].Amt;
}
if(credit > debit)
{
var bal = credit - debit;
}
else{
var bal = debit - credit;
}
}
$('#bal').val(bal);
}
});
});
</script>

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

How to initialize jquery easy slider plugin to my plugin?

I have a plugin which retrieves JSON data from external file and appends it to the "div#slider", the data is retrieved and is working fine but the easySlider is not initialized after retrieving the data successfully . and the slide does not starts.
I have codes on http://lkamal.com.np/r3dImage
my plugin code is as follows:
(function($) {
$.fn.r3dImage = function(options){
var defaults = {
url: 'ajax/test.txt',
pause: 2000,
};
var options = $.extend(defaults, options);
//retrive json file
return this.each(function() {
obj = $(this);
var body = obj.html();
getJson();
});
function getJson(){
$.ajax({
type: "POST",
url: options.url,
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
//alert("Success");
$.each(data.dashboard, function(i,post){
obj.html('<li><img src="' + post.ImageUrl + '" title="' + post.OverlayText +'" /></li>');
});
$(obj).easySlider({
pause: options.pause
});
},
error: function(xhr, status, error) {
alert(xhr.status);
}
});
};
/* this.each(function() {
$(options.container).easySlider({
pause: options.pause
});
});*/
};
})(jQuery);
and another is easy slider 1.7.
or
can i do it inside the easyslider plugin.
How Can i merge this two plugin and make one.
I got solution for this also.
$(function() {
$.fn.r3dImage = function(param) {
var options = {
url : "",
pause : 2000,
feedFetchDelay : 10
};
this.each(function() {
var element = $(this);
//alert(element.attr('id'));
element.html("<ul></ul>");
options = $.extend(options,param);
if(options.url=="") { console.log("URL is not specified"); }
else {
getJsonFeed(element); //retrives json feed and appends to respective div
setInterval(getJsonFeed, options.feedFetchDelay*1000*60); //Time interval in milli seconds converted to minute using delay*1000*60
}
});
function getJsonFeed(element){
//function to retrive json feed start using post of json data
$.post(
options.url,
function(data) {
//alert(data.dashboard);
html = '';
$.each(data.dashboard, function(k,v) {
html += '<li>';
html += '<a href="'+v.TargetUrl+'" target="'+v.Target+'">';
html += '<img src="' + v.ImageUrl + '" alt="' + v.Alt +'" title="' + v.OverlayText +'" />';
html += '</a><p>'+v.OverlayText+'</p></li>';
});
//alert(html);
$("ul", element).append(html); //appending the json data with respective div
//initialize the slider to easy slider
$(element).easySlider({
auto: true,
continuous: true
});
},
"json"
);
}
}
});

Resources