How to expand single statement for multiple statements in success function - javascript

I'm trying to turn the results of a route from my API into a searchable list the whole process of obtaining data via AJAX is completed, I can print data on my front end but only 1 result from my list in JSON is available to the client, how can I expand this list using statement?
Jquery
$('#sendSearchAddress').click(function() {
$.ajax({
type: "GET",
dataType: "JSON",
url: "https://****/api/itapetininga-street-last-three-searcheds?access_token=7Z***",
success: function (finalData) {
// Running test
console.log(finalData);
if (finalData) {
// var dd = JSON.parse(result);
// alert(finalData[0].addressStreet)
// name: finalData[0].addressStreet
// Print Results
var options = {
valueNames: ['name', 'born']
};
// Example One
var values = [{
name: finalData[0].addressStreet
}];
var userList = new List('users', options, values);
// Example Two
// userList.add(values);
// Print Varible Contain Data From Street
console.log(values);
}
}
});
});
Html
<div id="users">
<input class="search" placeholder="Search" />
<button class="sort" data-sort="name">
Sort by name
</button>
<button id="sendSearchAddress">
Atualizar
</button>
<ul class="list">
<li>
<h3 class="name">Jonny Stromberg</h3>
<p class="born">1986</p>
</li>
<li>
<h3 class="name">Jonas Arnklint</h3>
<p class="born">1985</p>
</li>
</ul>
</div>
My JSON Result

I'm not sure I fully understand what you're trying to do but as best as I can tell it looks like you need to change
var values = [{
name: finalData[0].addressStreet
}];
to
var values = finalData.map(function(finalDatum) {
return {
name: finalDatum.addressStreet
};
});

Related

Undefined (reading 'childNodes') List.js with my list being rendered by Ajax call

I can't figure out why it's throwing me an error but when I check if my list is being rendered it is there.
Front end
<div id="calendar-events-list" class="events-listing">
foreach(sample_arr) {
echo '<ul class="events-by-date list"></div>';
}
<nav class="events-calendar-pager events-pager" data-value="">
<a class="page-prev disabled" href="#"></i></a>
<ul class="pagination"></ul>
<a class="page-next" href="#"></i></a>
</nav>';
</div>
Js file
$.ajax({
method: 'post',
url: path+'js/ajax/get-events.php',
data: {
// 'current_month': instance.month,
'current_year': instance.year,
'current_period': instance.current_period,
'action': action,
'views': views,
'limit': instance.limit,
'xid': c_xid
},dataType: 'json'
}).done(function(data){
if($('ul.list li').length){
var events_calendar_options = {
valueNames: ['side'],
pagination: true,
page: 3,
innerWindow: 2,
};
var eventList = eventsPagination('calendar-list', options);
eventList.update();
}
} // close ajax
...
// when user clicked a date from a calendar, the events (my list array) on that date should show
$container.on('click', $element, function(){
if($('ul.list li').length){
var options = {
valueNames: ['side'],
pagination: true,
page: 3,
innerWindow: 2,
};
var eventList = eventsPagination('calendar-list', options);
eventList.update();
}
}
There's nothing wrong with my eventsPagination() function as the other ones are working properly. It just this one is throwing me an error once I change the date and pass thru ajax and then return my new events array. And my list of events array will only show once they click a specific date in the calendar.
Really appreacite your help!

Meteor - Trying to automate using data attributes and ReactiveDict

I'm trying to automate naming conventions used for a reactive dictionary, but I'm stuck not knowing how to access the reactive dictionary key based on the data attribute I fetched on click.
Expected: Use same naming convention for both ReactiveDict keys and data-attribute names on HTML elements so I can fetch the name on the element clicked, take its data-attribute name and automatically know which ReactiveDict key it is because they use the same name.
Result: It's not recognizing the naming convention when trying to set or get from the ReactiveDict because... I don't know. I'm guessing it's because when you create a ReactiveDict, you use this convention template.search.set('generic_name', data) but it won't work if I replace 'generic_name' with the data-attribute name (that doesn't include the single quotes) on click.
Please see example code below and advise if you have any questions, request for more info, or funny jokes since we're all trapped at home avoiding the COVID-19 virus :slight_smile:
home-template.html
<template name="home_template">
<section class="home-template">
<div class="content">
<div class="filter-box">
<ul>
<legend class="sui-category__title">CATEGORY 1</legend>
{{#each option in category_one}}
<li data-filter-value="{{option.value}}" data-category-name="category_one">
<div class="circle">{{formatToNumberWithComma(option.count)}}</div>
<h4>{{option.value}}</h4><input id="filter-1-{{get_this(option)}}" type="checkbox" /><label for="filter-1-{{get_this(option)}}"><i class="fa fa-check"></i></label>
</li>
{{/each}}
</ul>
<span class="more-options">+ More</span>
</div>
<div class="filter-box">
<ul>
<legend class="sui-category__title">CATEGORY 2</legend>
{{#each option in category_two}}
<li data-filter-value="{{option.value}}" data-category-name="category_two">
<div class="circle">{{formatToNumberWithComma(option.count)}}</div>
<h4>{{option.value}}</h4><input id="filter-2-{{get_this(option)}}" type="checkbox" /><label for="filter-2-{{get_this(option)}}"><i class="fa fa-check"></i></label>
</li>
{{/each}}
</ul>
<span class="more-options">+ More</span>
</div>
<div class="filter-box">
<ul>
<legend class="sui-category__title">CATEGORY 3</legend>
{{#each option in category_three}}
<li data-filter-value="{{option.value}}" data-category-name="category_three">
<div class="circle">{{formatToNumberWithComma(option.count)}}</div>
<h4>{{option.value}}</h4><input id="filter-3-{{get_this(option)}}" type="checkbox" /><label for="filter-3-{{get_this(option)}}"><i class="fa fa-check"></i></label>
</li>
{{/each}}
</ul>
<span class="more-options">+ More</span>
</div>
</div>
</section>
</template>
home-template.js
Template.home_template.onCreated(() => {
const template = Template.instance();
template.search = new ReactiveDict();
template.search.set('category_one');
template.search.set('category_two');
template.search.set('category_three');
template.search.set('filter_parameters');
});
Template.home_template.helpers({
formatToNumberWithComma(number) {
return format_w_comma(number);
},
category_one() {
const template = Template.instance();
return template.search.get('category_one')[0].data;
},
category_two() {
const template = Template.instance();
return template.search.get('category_two')[0].data;
},
category_three() {
const template = Template.instance();
return template.search.get('category_three')[0].data;
},
get_this(option) {
const query_to_array = [];
const search_query_word_array = option.value.split(' ');
const search_query_word_array_count = search_query_word_array.length;
for (let i = 0; i < search_query_word_array_count; i++) {
query_to_array[i] = `${search_query_word_array[i]}`;
}
const search_query = query_to_array.join('-');
return search_query;
},
});
Template.home_template.events({
'click .home-template label': function (event, template) {
$(event.currentTarget).parent('li').toggleClass('active');
const category_clicked = $(event.currentTarget).parent('li')[0].dataset.categoryName;
const filter_selected = $(event.currentTarget).parent('li')[0].dataset.filterValue;
const array = template.search.get(category_clicked);
array.indexOf(filter_selected) === -1 ? array.push(filter_selected) : array.splice(array.indexOf(filter_selected), 1);
template.search.set(category_clicked, array);
const filter_parameters = {
filters: {
all: [{
category_one: template.search.get('category_one'),
},
{
category_two: template.search.get('category_two'),
},
{
category_three: template.search.get('category_three'),
},
],
},
};
template.search.set('filter_parameters', filter_parameters);
},
});
Thank you!
You data keys are working, you actually set the data here:
const category_clicked = $(event.currentTarget).parent('li')[0].dataset.categoryName
const filter_selected = $(event.currentTarget).parent('li')[0].dataset.filterValue
const array = template.search.get(category_clicked)
array.indexOf(filter_selected) === -1
? array.push(filter_selected)
: array.splice(array.indexOf(filter_selected), 1)
template.search.set(category_clicked, array)
Consider the following data:
template.search.set('category_one', [
{
data: [
{
value: 'some value here',
count: 100
}
]
}
])
and category_clicked to be category_one and filter_selected to be some value here then the code above will result in the following data:
[
{
data: [
{
value: 'some value here',
count: 100
}
]
},
'some value here'
]
I am not sure how you further process this data but this shows your reactive data is working. The data updated in the helper right after your clicked the label.

Vue loop list - append the ajax returned data into the list?

How can I append vue list after ajax call?
This is my HTML with Vue:
Load More
<div id="news-posts">
<!-- item -->
<template v-for="item in items">
<div class="cell large-4 medium-6">
<!-- image has no padding -->
<div class="card grid-item">
<div class="card-divider">
<h4 class="heading heading-card"><a :href=item.url><span v-html=item.title></span></a></h4>
</div>
<div class="card-date">
<span v-html=item.date></span>
</div>
<div class="card-section"><p v-html=item.excerpt></p></div>
<div class="text-right">
<a :href=item.url class="button button-more"><i class="material-icons">chevron_right</i></a>
</div>
</div>
</div>
<!-- item -->
</template>
<!-- vue - loop -->
</div>
Js:
// Render template with Vue.
// Get json of catering menu.
var element = document.getElementById('news-posts')
var buttonLoad = document.getElementById('button-load')
if (element !== null) {
// var endpoint = $('#button-load').data('posts-endpoint') // jQuery
var endpoint = buttonLoad.getAttribute('data-posts-endpoint') // Vanilla JS
var getData = await axios.get(endpoint)
var cateringMenu = new Vue({
el: '#news-posts',
data: {
items: getData.data
}
})
}
$("#button-load").click(function(){
var endpoint = buttonLoad.getAttribute('data-posts-endpoint') // Vanilla JS
$.get(endpoint, function(data, status){
var cateringMenu = new Vue({
el: '#news-posts',
data: {
items: data
}
})
})
return false
})
Of course, it does not append the ajax returned data into the list.
Any idea?
EDIT:
Got it working with:
methods: {
fetch: function (event) {
var self = this
// `this` inside methods points to the Vue instance
$.ajax({
url: endpoint,
method: 'GET',
success: function (data) {
data.map(function(item) {
self.items.push(item)
})
},
error: function (error) {
console.log(error)
}
})
}
}
Have you tried to make your button execute a method that is defined in Vue, so you have access to the instance and can set the items with this, something like this;
methods: {
fetch: function(){
var endpoint = buttonLoad.getAttribute('data-posts-endpoint');
$.get(endpoint, function(data, status){
this.items = data; //set items.
})
}
}
and then add the fecth method to your button (needs to be in the vue wrapper, its outside at the moment it looks like) v-on:click.prevent="this.fecth"

I want to filter in the list if the text box value is changed using knockout

I want to filter in the list if the text box value is changed if the
JSON Returned in Ajax call is as I am using two different model.
Filteration should show hide or just filter the data I am providing you the JSON data what I am getting from the ajax call. Thanks
Data = [{"code":"Grand Financial","cls":"Branch","Chk":true},{"code":"Joan Group","cls":"Branch","Chk":true}]
var searchModel, advisorGroupModel;
$(document).ready(function () {
$.ajax({
type: "GET",
url: '/ASPNET/Reports/GetAdvisorGroups',
dataType: "json",
success: function (data) {
advisorGroupModel = {
advisorGroup: ko.observableArray(data)
};
ko.applyBindings(advisorGroupModel, document.getElementById("advisorGroupModel"));
}
})
var searchModel = {
searchQuery: ko.observable('')
};
searchModel.searchHandle= ko.dependentObservable(function () {
var code = this.searchQuery().toLowerCase();
return ko.utils.arrayFilter(advisorGroupModel, function (beer) {
debugger;
return beer.code.toLowerCase().indexOf(code) >= 0;
});
console.log(search);
}, searchModel)
ko.applyBindings(searchModel, document.getElementById("searchModel"));
});
<div id="searchModel">
<input data-bind="value: searchQuery, valueUpdate: 'keyup'" />
<h6 data-bind="text: searchQuery"></h6>
</div>
<div class="CheckBoxListGroup" id="advisorGroupModel">
<ul data-bind="template: { name: 'advisorGroupTemplate', foreach: advisorGroup, as: 'singleAdvisorGroup' }"></ul>
<script type="text/html" id="advisorGroupTemplate">
<li>
<input type="checkbox" data-bind="attr: { value: code, id: code, checked: Chk }" name="GroupsSel">
<label data-bind="attr: { for: code }, text: '' + code + ' (' + cls + ')' "></label>
</li>
</script>
</div>
don't bind your display to the entire list, bind your display to a computed function that returns the filtered list or returns all items when there are no filters.
then on your keyup call your filterlist function that filters the list removing the ones that do not match your filter

Send custom parameter in x-editable

I am using x-editable to populate select list in popup. Now I want to send my key to server, my code is something like that
<a href="#" id="status" data-type="select" data-pk="1" data-url="${g.createLink(controller: 'someController', action: 'someAction')}" data-title="Select CV" class="btn btn-primary">
<image src="${resource(dir: 'images/template', file: 'logo11.png')}"/> ${session.someList?.size()} CV(s) Created
</a>
<script>
$(function () {
$('#status').editable({
value: 1,
source: [
<g:each in="${session.someList}" var="xyz" status="idx">
{value: ${xyz?.id}, text: "${xyz.title}", srsSelected: ${xyz.id}, updateXyz: "updateXyz"},
</g:each>
]
});
});
</script>
I want to send my srsSelected key to server, I did google but not getting the point...
Edit:
Now I am able to send my key to server(after long research) using
params: function (params) { //params already contain `name`, `value` and `pk`
var data = {};
data['cvSelected'] = params.pk;
return data;
}
therefore my updated code is:
<a href="#" id="status" data-type="select" data-pk="1" data-url="${g.createLink(controller: 'someController', action: 'someAction')}" data-title="Select CV" class="btn btn-primary">
<image src="${resource(dir: 'images/template', file: 'logo11.png')}"/>
${session.someList?.size()} CV(s) Created
</a>
<script>
$(function () {
$('#status').editable({
value: 1,
source: [
<g:each in="${session.someList}" var="xyz" status="idx">
{value: ${xyz?.id}, text: "${xyz.title}", srsSelected: ${xyz.id}, updateXyz: "updateXyz"},
</g:each>
],
params: function (params) { //params already contain `name`, `value` and `pk`
var data = {};
data['srsSelected'] = params.pk;
return data;
}
});
});
</script>
I am able to send value of pk in srsSelected key but this time I need to set value of srsSelected dynamically.
And Now I found the method to set the value of srsSelected dynamically as
params: function (params) {
params.srsSelected = params.pk
return params;
}
and setting the value of data-pk attribute in anchor tag dynamic, we can get srsSelected at controller action.

Categories

Resources