jquery - getting all parameters passed instead of just one - javascript

The code below calls two functions when a pop up on my site loads. They are function callA and function callB. Both functions rely on getting the id to work. I am struggling to pass the id properly to function b. In function a this works great since it the getting of the id is inside the jQuery.each function.
However I need to have the id available outside of the .each so it can pass to callB. The way I had tried to do this was var r_id = jQuery(html).attr("id"); but as I suspected, it only gets a single id at a time. How do I get multiple ids and have them passed so that this works properly?
jQuery(document).on('popup/show', (event, popup_id) => {
if (popup_id === 123) {
function callA() {
jQuery.ajax({
data: {
action: 'list_count'
},
type: 'post',
url: my_ajax.ajax_url,
dataType: 'JSON',
success: function(data) {
var id = jQuery().data('id')
var html = '';
jQuery.each(data, function(key, value) {
html += '<div class="accordion-header ui-accordion-header ui-helper-reset ui-state-default ui-accordion-icons ui-corner-all" id="' + value.id + '" style="display:table-row">';
html += '<div class="image" style="display: table-cell";>' + value.img + '</div>';
html += '<div style="display: table-cell";>' + value.Name + '</div>';
html += '<div style="display: table-cell">' + value.Size + '</div>';
html += '<div style="display: table-cell"> ' + value.Number + ' </div>';
html += '<div class="tdid_' + value.id + '" style="display: table-cell">' + value.Status + '</div>';
html += '</div>';
html += '<div id="cid_' + value.id + '" class="bg_clear ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" style="display: table-cell">';
html += '<div class="bg_clear ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" style="display: table-cell"></div>';
html += ' </div>';
});
jQuery('#list').html(html);
var r_id = jQuery(html).attr("id"); //<<<<<<<<<<<<< gets the id from the .each and passes it
callB(r_id);
}
});
}
function callB(r_id) {
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
data: {
action: 'options_function',
cid: r_id
},
success: function(data) {
jQuery(data).insertAfter('#cid_' + r_id)
console.log(data);
console.log('#cid_' + r_id);
}
});
}
callA();
}
});

From the .each() loop, you can gather the ids in an array:
let id_array = [];
jQuery.each(data, function(key, value) {
id_array.push(value.id); // Add ids with this
// A couple lines of those... That is the rest of your actual loop
//html += ...
});
jQuery('#list').html(html);
callB(id_array); // <== Pass the array of ids

Related

Laravel & Ajax load data without refreshing page

I'm currently working on a code that displays users activity log. Ajax will call the route and gets the response (json) results. I need to be able to display the log records on admin dashboard without refreshing the page.
Ajax
$(document).ready(function() {
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
},error:function(){
console.log(data);
}
});
});
If I understood, you can do this:
$(document).ready(function() {
var requesting = false;
var request = function() {
requesting = true;
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
requesting = false;
});
});
},error:function(){
console.log(data);
}
});
};
if(!requesting){
setTimeout(request, 1000);
}
});
Every seconds it does a request to your users.activity route, so there is an update every second.
You need to send last record id in server. so you can get only new data.
my updated answer based on #stackedo answer .
$(document).ready(function () {
var lastId = 0; //Set id to 0 so you will get all records on page load.
var request = function () {
$.ajax({
type: 'get',
url: "{{ route('users.activity') }}",
data: { id: lastId }, //Add request data
dataType: 'json',
success: function (data) {
$.each(data, function () {
$.each(this, function (index, value) {
console.log(value);
lastId = value.id; //Change lastId when we get responce from ajax
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
}, error: function () {
console.log(data);
}
});
};
setInterval(request, 1000);
});
In controller add were condition to query :
UserActivity::where('id','>',$request->id)->get();

Adding django view result from ajax as table in template

I have a django model and I view i am aggregating few columns and filtering result and returning as below
def show_grid_summery(request):
id = request.GET.get('id', None)
context = {
"summery": [],
}
result = Records.objects.filter(grid_id_id = id).aggregate(Sum('house_count'), Sum('point_count'))
if len(result) != 0:
context["summery"].append([result['house_count__sum'], result['point_count__sum']])
return JsonResponse(context)
And on the template i am getting results using ajax
$.ajax({
url: 'ajax/summery/',
data: {
'id': ID
},
dataType: 'json',
success: function (data) {
alert(data);
var trHTML = '';
document.getElementById('summaryLabel').innerHTML = '';
$.each(data.summery , function (item) {
trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
});
$('#summaryLabel').append(trHTML);
}
Now I want to fill the results record (2 columns) as a table inside the #summaryLabel tag. (preferably with headers as well). But I am unable to sort it out after many different attempts.
html part is
<table id="summaryLabel">
<p>information.</p>
</table>
The jQuery $.each() function passes two parameters, the first is the array index, the second is the object. So it would seem that in your code, your item variable would contain the index, which is not what you want.
Try:
$.each(data['summery'] , function (i, item) {
trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
});
or just
$.each(data['summery'] , function () {
trHTML += '<tr><td>' + this[0] + '</td><td>' + this[1] + '</td></tr>';
});
jQuery $.each() is documented here: http://api.jquery.com/jquery.each/

Loading Ajax Data Dynamically

I have a bunch of jQuery functions which gets JSON data from a MySQL database and displays it on certain pages within my application.
i have about 15 of these functions that look similar to the below and i would like to tidy them up and convert them to one major function which returns data based on the variables passed to the function. IE getdata(subscriptions) would display the subscriptions.
My issue is i'm not sure how to pass the column names to the function from the ajax query and remove the value.column-name from the function.
Example function from application
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value+
'</td><td>' + value.subscription_name +
'</td><td>' + value.subscription_cycle +
'</td><td>' + value.subscription_cost +
'</td><td>' + value.subscription_retail +
'</td><td>' + value.subscription_profit +
'</td><td>' + value.subscription_margin +
'</td><td>' + value.subscription_markup +
'</td></tr>';
});
$('#subscription-results').html(trHTML);
},
});
}
Any help is very much appreciated as i'm fairly new to jQuery
You can refer to this code:
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
$('#subscription-results').html(parseColumns(response));
},
});
}
function parseColumns(columns) {
var html = '';
if (Object.prototype.toString.apply(columns) === '[object Array]') {
$.each(columns, function(key, value) {
html += parseColumn(value);
})
} else {
html += parseColumn(columns);
}
function parseColumn(column) {
var trHTML = '<tr><td>' + column + '</td>';
for (var key in column) {
trHTML += '<td>' + column[key] + '</td>'
}
trHTML += '</tr>';
return trHTML;
}
return html;
}

Loop through JSON and populate data dynamically

I'm trying to iterate through JSON data and populate the content dynamically using jQuery.
First I do an Ajax request
Then I loop through the data and create the HTML tags dynamically
I create a div container with a class of "product-wrapper" for each JSON object (in this case 2 divs product-wrapper). As you can see on the example of my JSON data, each object has an array of objects "details".
From my second foreach loop - how can I populate the data of "details" within its appropriate "product-wrapper" div?
JavaScript
myApp.init = function(){
var rates = {
products: $('.products-container'),
init: function(){
rates.showRates();
},
showRates: function(){
$.each(utils.rates, function(index, value){
rates.products.append(
'<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div class="product-details"></div>' +
'</div>'
);
$.each(value.details, function(i,val){
$('.product-details').append('<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>');
});
});
}
};
var utils = {
rates: '',
url: $('.business-interest-rates').attr('data-rates-json'),
init: function(){
utils.ajaxRequest();
},
ajaxRequest: function(){
$.ajax({
url: utils.url,
dataType: 'json',
success:function(data){
utils.rates = data;
if($('#interest-rates').length > 0){
rates.init();
}
},
error: function(e){
console.log(e.message);
}
});
}
};
utils.init();
};
JSON
[
{
"name":"Australian dollar (AUD)",
"currency":"AUD",
"details":[
{
"balance": "1+",
"grossRate": "1.700",
"aer": "0.5"
},
{
"balance": "500,000+",
"grossRate": "2.100",
"aer": "2.00"
},
{
"balance": "1,500,000+",
"grossRate": "2.450",
"aer": "1.00"
}
]
},
{
"name":"EURO (EU)",
"currency":"EU",
"details":[
{
"balance": "1+",
"grossRate": "1.700",
"aer": "1.50"
},
{
"balance": "500,000+",
"grossRate": "2.100",
"aer": "2.20"
}
]
}
]
Either don't use a CSS class to append your stuff but unique ids, or first generate the whole HTML code (wrapper and details all together) in one step and then append it.
// use unique IDs for appending
function () {
$.each(utils.rates, function (index, value) {
rates.products.append(
'<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div id="product-details-' + value.name + '"></div>' +
'</div>'
);
$.each(value.details, function (i, val) {
$('#product-details-' + value.name).append('<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>');
});
});
}
// first generate all html code, then append
function () {
$.each(utils.rates, function (index, value) {
var html = '<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div class="product-details">';
$.each(value.details, function (i, val) {
html += '<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>';
});
html += '</div>' +
'</div>';
rates.products.append(
html
);
});
}

How to limit the results of codepen rss feed

I am working on my codepen rss feed for my website. I am having small issue limiting the results.
Currently displays over 10 results in the rss feed. But I would like to know the best way to limit results to 5
Question: How could I limit the results of my rss feed to 5 only.
Codepen Example
<script type="text/javascript">
$(document).ready(function(){
url = 'http://codepen.io/riwakawebsitedesigns/public/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(xml){
var postlist = xml.responseData.feed.entries;
var html = '<ul class="list-unstyled">';
$.each(postlist, function(idx, data) {
html += '<li>';
html += '<h3 class="codepen_feed_title">' + data.title + '</h3>';
html += '<a href="' + data.link + '" target="_blank">';
html += '<span class="codepen_feed_content">Click Here To View It!</div>';
html += '</a>';
html += '</li>';
});
html += '</ul>';
$(".codepen_feed").append(html);
}
});
});
</script>
Use a return value for your each loop
$.each(postlist, function(idx, data) {
var title = data.title;
html += '<li>';
html += '<h3 class="codepen_feed_title">' + data.title + '</h3>';
html += '<a href="' + data.link + '" target="_blank">';
html += '<span class="codepen_feed_content">Click Here To View It!</div>';
html += '</a>';
html += '</li>';
return idx < 4;
});

Categories

Resources