Load 2 json output text object - javascript

Please help, I want to load 2 JSONs from 2 URLs, this loads questions for a survey. If I just load 1 JSON, the output still normal, but if 2 JSONs, the output is the text object, this survey is survey js from surveyjs.io, there is my code. Please help me.
var baris1,baris2 = [];
var url1='url_link';
var url2='url_link';
$.when($.getJSON('url_link'), $.getJSON('url_link')
).done(function(baris1,baris2){
//baris = data
baris1 = JSON.stringify(s.baris1)
baris2 = JSON.stringify(s.baris2);
//alert(baris1);
Survey.Survey.cssType = "bootstrap";
var surveyJSON = {pages:[{elements:[
{type:"matrix",columns:[
{value:1,text:"Strongly Disagree"},
{value:2,text:"Disagree"},
{value:3,text:"Neutral"},
{value:4,text:"Agree"},
{value:5,text:"Strongly Agree"}],
//name:"Pedagogik",rows:baris,
name:"Pedagogik",rows:baris1,
//title:"Silakan Jawab Dengan Sejujur-jujurnya"
},
{type:"matrix",columns:[
{value:1,text:"Strongly Disagree"},
{value:2,text:"Disagree"},
{value:3,text:"Neutral"},
{value:4,text:"Agree"},
{value:5,text:"Strongly Agree"}],
//name:"Pengetahuan Umum",rows:baris,
name:"Pengetahuan Umum",rows:baris2,
//title:"Silakan Jawab Dengan objektif"
}]}]}
function sendDataToServer(survey) {
//send Ajax request to your web server.
alert("The results are:" + JSON.stringify(s.data));}
var survey = new Survey.Model(surveyJSON);
$("#surveyContainer").Survey({
model: survey,
onComplete: sendDataToServer
});
});

Finally i found the answer, just declare the number of array for the output,
Row: baris1;
Change to
Row: baris1,[0];
Just it

Related

AJAX way of handling filters in a Django based ecommerce application is not working upon copy pasting the url in new tab

So I ran into this problem two days back and still haven't got a proper solution. I would highly Appreciate any help in here.
Let me explain the scenario first, so the idea is I have one django based ecommerce site and I want to render the product showcase page through ajax call (without reloading) and same time also update the url as the selected filters for example (http://vps.vanijyam.com:8000/customerlist?category=category_1).
I want to achieve similar to this site - shutterstock.
My Scenario -
http://vps.vanijyam.com:8000/customerlist this page to showcase all the available products and also have the filters option and pagination.
Now when I change the page or apply some filter I am e.g. http://vps.vanijyam.com:8000/customerlist?category_slug=category_1 then it is working, but when I refresh the page it is not.. the reason behind this the way I am handling this ajax call in the backend.
def customer_categories(request):
# Get attributes from request url
current_page = request.GET.get('page' ,'1')
category_slug = request.GET.get('category_slug')
sortby_filter = request.GET.get('sortby_filter')
price_filter = request.GET.get('price_filter')
search_query= request.GET.get('term')
line_filter_min = request.GET.get('price_min')
line_filter_max = request.GET.get('price_max')
# Set limit and offset for queryset
limit = REQUEST_PER_PAGE * int(current_page)
offset = limit - REQUEST_PER_PAGE
categories = Category.objects.all()
# products = Product.objects.filter(available=True)[offset:limit] # limiting products based on current_page
# products_count = Product.objects.filter(available=True).count()
# Check product already in cartlist
cartlist_check = []
cart_item_count = cart_count(request)
cart_items = cart_list(request)
for cart in cart_items:
cartlist_check.append(cart['product'].id)
# Check product already in wishlist, only if user logged in
wishlist_check =[]
if request.user.is_authenticated:
wishlist_items_check = WishList.objects.filter(user=request.user)
for item in wishlist_items_check:
wishlist_check.append(item.product_id)
wishlist_count = wishlist_counts(request.user)
else:
wishlist_count = 0
# If category_slug True
if category_slug:
category = get_object_or_404(Category, slug=category_slug).\
get_descendants(include_self=True)
else:
category = None
time1 = time.time()
# Filters for multiselect, retun products and products_count
products, products_count, search_list = attribute_filter(category=category,
search_query=search_query,
sortby_filter=sortby_filter,
price_filter=price_filter,
line_filter_min=line_filter_min,
line_filter_max=line_filter_max,
offset=offset,
limit=limit)
time2= time.time()
print('Time Elapsed')
print(time2-time1)
if len(products) > 0:
# adding one more page if the last page will contains less products
total_pages = math.ceil(products_count / REQUEST_PER_PAGE )
cart_product_form = CartAddProductForm()
wish_list_form = WishListForm()
total_pages = math.ceil(products_count / REQUEST_PER_PAGE ) # adding one more page if the last page will contains less products
if not current_page == '1' or category_slug:
print('------------------------------')
return render(request, 'customer/products/products_by_category.html',\
{'products': products,
'wishlist_item_check': wishlist_check,
'cartlist_item_check': cartlist_check,
'current_page': current_page,
'total_products': products_count,
'request_per_page': REQUEST_PER_PAGE,
'total_pages':total_pages
})
else:
return render(request, 'customer/home/customer_showcase.html',\
{'products': products,
'categories':categories,
'cart_product_form': cart_product_form,
'wish_list_form': wish_list_form,
'wishlist_item_check': wishlist_check,
'wishlist_count': wishlist_count,
'cart':cart_items,
'items_count':cart_item_count,
'cartlist_item_check': cartlist_check,
'current_page': current_page,
'total_pages':total_pages,
'total_products': products_count,
'request_per_page': REQUEST_PER_PAGE,
})
Ajax part of the code is here
$('.selected_subcategory').on('click', function () {
send_data['selected_subcategory'] = $(this).attr('data-id');
getPopularProductsData($(this).attr('data-id'));
// getAPIData();
var params = window.location.search;
var path = window.location.pathname;
var old_url = path + params;
var url = old_url;
const state = {}
const title = ''
console.log('old urll', old_url)
let new_url=''
if(params){
new_url = removeDuplicate(old_url)
}
console.log('new url', new_url)
history.pushState(state, title, url)
$.ajax({
method: 'GET',
url: old_url,
data: {
category_slug: send_data['selected_subcategory']
},
beforeSend: function () {
$('#products').html('<div class="alert alert-success">Loading...</div>');
// $('#spinner3').addClass('d-block');
},
success: function (result) {
if (result['error']) {
let message =
'<div class="alert alert-danger">' +
result['error'] +
' <a class="" href="http://vps.vanijyam.com:8000/customerlist/" style="text-decoration: underline">click here</a>' +
'</div>';
$('#products').html(message);
} else {
document.getElementById('products').innerHTML = result;
}
const state = {}
const title = ''
const url = this.url
history.pushState(state, title, url)
},
error: function (response) {
$('html,body').animate({
scrollTop: 200,
});
$('#products').html(
'<div class="alert alert-danger">Something went wrong!!!</div>'
);
$('#list_data').hide();
// $('#spinner3').addClass('d-none');
},
});
});
My expectation is when I browse this http://vps.vanijyam.com:8000/customerlist?page=2&category_slug=category_1 link it would render the same which matches with the query params, but in a ajax way.
Sorry for the long explanation. Hope my point is clear through this explanation. Thanks in advance
Here in your Django part, you are returning two different HTML outputs when there is category_slug and not.
If there is category_slug in your request you returning 'customer/products/products_by_category.html'
But when there is no category slug you are returning 'customer/home/customer_showcase.html'.
Both HTML files are different in their layout. The first one doesn't provide the header or container elements. This is the central problem of your issue.
You can Fix this issue by
You can put a special parameter in ajax api call, by which Django can realize that is is an api call, this time it returns products_by_category.html.
And you want to make unique all other returns to customer_showcase.html, but if there is a category filter you can pass filtered content to the products list. If category_slug is None or empty you can pass all products without the filter to the same HTML file.
You can also differentiate ajax api call by making it a POST request and all other web requests remains GET requests. So you can easily identify the traffic.
Here is the changes in Django:
if request.method == "POST"::
print('------------------------------')
return render(request, 'customer/products/products_by_category.html',\
{'products': products,
'wishlist_item_check': wishlist_check,
'cartlist_item_check': cartlist_check,
'current_page': current_page,
'total_products': products_count,
'request_per_page': REQUEST_PER_PAGE,
'total_pages':total_pages
})
else:
return render(request, 'customer/home/customer_showcase.html',\
{'products': products,
'categories':categories,
'cart_product_form': cart_product_form,
'wish_list_form': wish_list_form,
'wishlist_item_check': wishlist_check,
'wishlist_count': wishlist_count,
'cart':cart_items,
'items_count':cart_item_count,
'cartlist_item_check': cartlist_check,
'current_page': current_page,
'total_pages':total_pages,
'total_products': products_count,
'request_per_page': REQUEST_PER_PAGE,
})
And make your ajax call to "POST", change in your front end code: method: 'POST',
Don't forget to add slash(/) at the end of url when you change to POST.

How can I dynamically insert dates in dncalendar?

I've got a problem using dncalendar, hope someone will help me!
I need a simple calendar in which being able to save and recover data from a db. dncalendar seemed good, but I have now problem in dynamically insert data into it.
I post some code for clarification. I recover the dates from some input fields called .date-smart and build an array (data_note). Problem is when I want to dynamically insert this dates into object notes, without knowing how many dates I have. If I do it like in below code, everything works fine, but I do not know how to do it with a for cycle or similar. Can someone help me?
var data_note =[];
var note = [];
$(".date-smart").each(function(){
data_note.push($(this).val())
note.push("SW");
})
var my_calendar = $("#dncalendar-container").dnCalendar({
dataTitles: { defaultDate: 'default', today : 'Today' },
startWeek:'monday',
});
my_calendar.build();
my_calendar.update({
notes: [{'date': data_note[0], 'note':note[0]}, {'date': data_note[1], 'note':note[1]}];
})
Why don't just make a variable feed all data in it and then pass it to notes
Like
var data_note =[];
var note = [];
var notesArr = [];
$(".date-smart").each(function(){
data_note.push($(this).val())
note.push("SW");
notesArr.push({'date': $(this).val(), 'note': 'SW'});
})
var my_calendar = $("#dncalendar-container").dnCalendar({
dataTitles: { defaultDate: 'default', today : 'Today' },
startWeek:'monday',
});
my_calendar.build();
my_calendar.update({
notes: notesArr
})

Change Google Sheet data based on user selection in Google Site (Web App)

I am making a google site which shows a drop down based on data coming from a Google Sheet. It works.
As next step, I want that when the user select a drop down choice from the list, the value which is selected is written in Google Sheet cell (in the example below, the selected value will be written in Sheet: "Dashboard", cell: B92).
For example, assume that the drop down list has the following values coming from the Sheet: "Item 1", "Item 2", "Item 3".
When the user select "Item 1" from the web site, the script should write "Item 1" in Google sheet cell B92. Similarly, if the user select "Item 2", the script will set "Item 2" in cell B92.
I tried with the code below, but I think something is wrong with:
fetch in the HTML file
doPost(e) because I am not sure how to pass the parameter
(I removed the entire code to focus on the pieces which are incorrect. I can add it back if needed)
function doPost(e) {
var ss=SpreadsheetApp.openById('XXXXXXXX');
var sh=ss.getSheetByName('Dashboard');
sh.getRange(92,2).setValues(e.parameter);
}
HTML file:
<script type="text/javascript">
var lastIndex = "";
const url = "https://script.google.com/a/google.com/macros/s/AKfycbxHX7cthji076OrqfY9ZpGa7jNDxKHUMf_ib7Ekmoo0Ir5DQF1Y/exec";
function listQ(){
var e = document.getElementById("sel1");
if(e.selectedIndex > 0){
lastIndex = e.selectedIndex;
console.log(lastIndex);
fetch(url, {
method: "POST"
, body: lastIndex
}).then(function (response) {
return response.json()
}).then(function (data) {
console.log(data);
})
}
}
document.getElementById("sel1").addEventListener("click",listQ);
I believe your goal as follows.
You want to put the selected value at select tab in HTML to the cell "B92" in the sheet Dashboard.
You want to send the value to Web Apps with the POST method.
For this, how about this answer?
Modification points:
At Google Apps Script side,
When you want to use the POST method, the request body is included in e.postData.contents.
sh.getRange(92,2).setValues(e.parameter); is not correct. In this case, please use setValue/
In your doPost, no values are returned. In this case, an error occurs at Javascript side when the value is sent.
At Javascript side,
lastIndex is returned. In the case of When the user select "Item 1" from the web site, the script should write "Item 1" in Google sheet cell B92. Similarly, if the user select "Item 2", the script will set "Item 2" in cell B92., the selected value is required to be retrieved and returned.
When above modification is reflected to your script, it becomes as follows.
Modified script:
Google Apps Script side:
function doPost(e) {
var value = JSON.parse(e.postData.contents).value;
var ss = SpreadsheetApp.openById('XXXXXXXX');
var sh = ss.getSheetByName('Dashboard');
sh.getRange(92, 2).setValue(value);
return ContentService.createTextOutput(JSON.stringify({message: "ok"})).setMimeType(ContentService.MimeType.JSON);
}
HTML and Javascript side:
From your question, I cannot understand about your options. So I used a sample options like below. Please replace this for your actual situation.
<select id="sel1">
<option value="sample1">sample1</option>
<option value="sample2">sample2</option>
<option value="sample3">sample3</option>
</select>
<script>
function listQ() {
const index = this.selectedIndex;
if (index > 0) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const url = "https://script.google.com/macros/s/###/exec"; // Please replace this for your Web Apps.
fetch(url, {
method: "POST",
body: JSON.stringify({index: index, value: value}),
})
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
}
}
document.getElementById("sel1").addEventListener("change", listQ);
</script>
In this modification, when the options of sample2 and sample3 are selected, the value is sent to Web Apps. And then, at the Web Apps, the retrieved value is put to the cell "B92".
Note:
When you modified the script of Web Apps, please redeploy it as new version. By this, the latest script is reflected to Web Apps. Please be careful this.
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script
In addition to Tanaike answer, I am posting an alternative using google.script.run which avoid the CORS issue which some users may experience.
The complete explanation is here: CORS block: WebApp POST to Sheet
in gs file:
function yourServerSideFunc(body) {
var value = body["value"];
var ss = SpreadsheetApp.openById('1ROvDcIQ9JCGxzLvCvTKIqSor576Uj9ZJv-n6hQ762XB');
var sh = ss.getSheetByName('Dashboard');
sh.getRange(92, 2).setValue(value);
return ContentService.createTextOutput(JSON.stringify({message: "ok"})).setMimeType(ContentService.MimeType.JSON);
}
and in HTML:
function listQ() {
const index = this.selectedIndex;
if (index > 0) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
}
}
document.getElementById("sel1").addEventListener("change",listQ);
function yourCallBack(response) {
}

Zimlets in zimbra, how to make a simple SearchRequest?

I'm a little desperate because I can not perform a simple search on my zimlet.
I just want to make a search in the custom folder.
The search should only display messages that are within my custom folder.
Like when I click on the custom folder in the left pane. exactly the same.
this is what shows the html header by pressing the icon of my custom folder in the left pane.
{"Header":{"context":{"_jsns":"urn:zimbra","userAgent":{"name":"ZimbraWebClient - FF39 (Linux)","version":"8.6.0_GA_1153"},"session":{"_content":150,"id":150},"account":{"_content":"admin#localhost.local","by":"name"},"csrfToken":"0_a3050edfdf238eadfdfdfdff2f14b4968e3"}},"Body":{"SearchRequest":{"_jsns":"urn:zimbraMail","sortBy":"dateDesc","header":[{"n":"List-ID"},{"n":"X-Zimbra-DL"},{"n":"IN-REPLY-TO"}],"tz":{"id":"America/Mexico_City"},"locale":{"_content":"es_MX"},"offset":0,"limit":100,"query":"in:\\"mycustomfolder\\"","types":"conversation","recip":"0","fullConversation":1,"needExp":1}}}
I'm trying with this code, within my com_zimbra_myzimlet.js
com_zimbra_myzimlet_HandlerObject.prototype._getShowResultFolderId =
function(t) {
var e=AjxSoapDoc.create("SearchRequest","urn:zimbraMail");
var cuery="raulicci";
e.setMethodAttribute("types","conversation");
e.setMethodAttribute("limit",100);
e.setMethodAttribute("offset",0);
e.set("query",cuery);
t.response=appCtxt.getAppController().sendRequest({
soapDoc:e,noBusyOverlay:false}
);
this.handleSearchResponse(t)
};
so far I can not find a way to make the consultation, although I imagine it is something easy as already implemented in zimbra comes when one gives click on the icon in my custom folder in the left pane.
I would like to use the default template that has zimbra to show INBOX, or the current folders.
When you click on the icon of the current folder in the left pane, us a list of emails appears as INBOX
I'm doing with my little zimlet one query with soap and json and I answered a JSON string.
This string json is a mailing list that are in the folder where you perform the query.
For request use:
var jsonObj = {SearchRequest:{_jsns:"urn:zimbraMail"}};
var request = jsonObj.SearchRequest;
request.sortBy = "dateDesc";
request.offset = 0;
request.limit = 100;
request.query = 'in:\"MYCURRENTFOLDER\"';
request.types = "conversation";
request.recips = "0";
request.fullConversation = 1;
request.needExp = 1;
var params = {
jsonObj:jsonObj,
asyncMode:true,
callback: (new AjxCallback(this, this._handleSOAPResponseJSON)),
errorCallback: (new AjxCallback(this, this._handleSOAPErrorResponseJSON)),
};
return appCtxt.getAppController().sendRequest(params);
For response use:
if (result.isException()) {
// do something with exception
var exception = result.getException();
return;
}
else {
response = { _jsns: "urn:zimbraMail", more: false };
}
// do something with response (in JSON format)
var response = result.getResponse();
var name = response.name;
var soapURL = response.publicURL;
var soapURL = response.soapURL;
var aller = result.getResponse();
var searchResult = new ZmSearchResult(this);
appCtxt.setStatusMsg("Response (JSON) success - "+name);
alert(aller.toSource());
JSON response to be displayed in the default template of INBOX integrated zimbra
({SearchResponse:{sortBy:"dateDesc", offset:0, c:[{id:"314", u:0, n:2, f:"s", d:1438663876000, su:"lokitox", fr:"lex", e:[{a:"admin#localhost.local", d:"admin", t:"f"}], m:[{id:"313", l:"300"}, {id:"312", l:"5", f:"s"}], sf:"1438663876000"}, {id:"-309", u:0, n:1, d:1438662639000, su:"Daily mail report for 2015-08-03", fr:"Grand Totals -- messages 91 received 117 delivered 0 forwarded 134 deferred (134 deferrals) 169 bounced 0 rejected (0%) 0 reject warnings 0 held 0 ...", e:[{a:"admin#localhost.local", d:"admin", t:"f"}], m:[{id:"309", s:"7232", l:"300"}], sf:"1438662639000"}], more:false, _jsns:"urn:zimbraMail"}})
Thankz, I hope someone has knowledge of how to do it

How to go trough JavaScript array?

I have this output from ajax call:
"total":"3",
"data":[{ "id":"4242",
"title":"Yeah Lets Go!",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah"
}]
So there is three that kind of items in that array and I would need to go that through and print actual html out of it. So on page it would be:
Yeah Lets Go! (which is a link to http:www.domain.com/yeah)
Created: 2010-07-24 13:19:24
I'm clueles with this one.
Edit 1:
Also atm I get that raw output after clicking link. How can I get it to show on page load? Or it does that ajax call when I click link atm.
Edit 2:
I got it to output everything at once. But still I have a prolem with putting it actual html. The output atm is:
"total":"3",
"data":[{
"id":"4242",
"title":"Yeah Lets Go!",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah"
}
{
"id":"4242",
"title":"Yeah Lets Go!222",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah222"
}
{
"id":"4242",
"title":"Yeah Lets Go!333",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah333"
}
]}
I would like to get that into list with title and link and creation day.
Edit 3 after answer from Luca Matteis:
Hmm, now im even more confused.
That JSON string comes out of this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true',
null,
function(data, status, xhr) {
$('#contentCell').html(data);
}
);
So I would need to do for that is something like:
var html = eval(data);
and then I would do what Luca Matteis suggest?
First off, that's a JSON string, you need to un-serialize the string into a real JavaScript object (look at json.org for this).
Once you have the native JavaScript data, something like this should work:
var html = '';
for(var i=0; i < obj.data.length; i++) {
html += ''+obj.data[i].title+'<br>';
html += 'Created: '+ obj.data[i].created;
}
Hmm, now im even more confused.
That JSON string comes out of this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', null, function(data, status, xhr) {
$('#contentCell').html(data);
});
So I would need to do for that is something like:
var html = eval(data);
and then I would do what Luca Matteis suggest?

Categories