ExtJS Set simple array to store - codeigniter

I have a codeigniter service that returns this:
{data: ["CEDULA-1723822761.pdf", "CROQUIS-1723822761.pdf", "PENSION-1723822761.pdf"], success: "true"}
And on my ExtJS App I'm trying to process it like this:
var responseData = opts.result.data;
var documentos = Ext.ComponentQuery.query("#docsTest")[0];
documentos.setValue(responseData); //This is just to check that the data is correct
var store = new Ext.data.SimpleStore({
fields:[
{name: 'name'}//I'm pretty sure my problem is here
]
});
store.loadData(responseData);
console.log('store:' + store);
var grid = Ext.ComponentQuery.query("#FldDocumentos")[0];
grid.setStore(store);
I want to show each one of the three results given by the service in a row in the grid but since the array doesn't specify a field name, the store just creates three empty objects. How can I correctly store each of the array strings in the store?

Create an Array and store the data with name attribute. So when you add this to store, grid can display data correctly.
var responseData = opts.result.data;
var documentos = Ext.ComponentQuery.query("#docsTest")[0];
documentos.setValue(responseData); //This is just to check that the data is correct
var store = new Ext.data.SimpleStore({
fields:[
{name: 'name'}//I'm pretty sure my problem is here
]
});
var nameList = [];
for(var i = 0 ; i < responseData.length ; i++){
nameList.push({ name = responseData[i]});
}
store.loadData(nameList);
console.log('store:' + store);
var grid = Ext.ComponentQuery.query("#FldDocumentos")[0];
grid.setStore(store);

Related

Submitting data to google sheet with multiple tab sheets

I'm referencing this article "How to Submit an HTML Form to Google Sheets…without Google Forms", it worked perfectly for me for only a Google Sheet with one tab.
Need help how to dynamically select what sheet tab the data should be written in the case the google sheet has multiple tabs. I'm using Ajax to submit google sheet btw.
Here's the call by the Ajax:
var $form = $('form#test-form'),
url = 'https://script.google.com/macros/s/MyScript/exec'
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(
// do something
);
})
The code on google sheet web app
function doGet(e){
return handleResponse(e);
}
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
If there is a way to change the variable SHEET_NAME dynamically then I think it will be good. Thanks

How do I access every index of a specific Array inside an AJAX object

I'm calling an ajax for giphy, with this code:
$.ajax({
url: queryURL,
method: "GET"
}). then(function(response) {
console.log(response);
when I look at the console log there's an object with the first property being data. Each index of data is another object, inside this object are two properties i'm trying to pull, rating and url. I want to be able to list the rating and url not just of a specific index, but every index in that data array. What would be the best way to do that? Currently I've tried a for loop
for (var i = 0; i<response.data.length;i++){
var dataIndex = response.data[i];
}
then <creating a variable something like>
var imgURL = response.data[dataIndex].url
but its not working.
Here's the entire code
function displayTopicGif() {
var topic = $(this).attr("data-name");
// query url
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&limit=20&rating=r&api_key=";
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
// for loop to create a variable for the index of the objects data
for (var i = 0; i < response.data.length; i++) {
var dataIndex = response.data[i];
}
// where the gif's will be dumped
var topicDiv = $("<div class='topic'>");
// rating of gif
var rating = response.data[0].rating;
console.log(rating);
// Creating an element to have the rating displayed
var pOne = $("<p>").text("Rating: " + rating);
// add to the rating element
topicDiv.append(pOne);
// retrieve the IMG of the gif
var imgURL = response.data[0].url;
var image = $("<img>").attr("src", imgURL);
topicDiv.append(image);
// put gif into topic-view div
$("#topic-view").prepend(topicDiv);
});
}
You can check that something is an object using $.isPlainObject and then read through its properties via:
for (key in object) {
var value = object[key];
//log
}
Or you can get the keys using Object.getOwnPropertyNames();. See this sample excerpt from MDN:
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

How to use ajax in dropdown to select items, when I am working with the django framework?

I am working on a Django framework and I am very much new to both Django and Ajax. I have used a drop down list and I need to select an item from that and accordingly display its details in a table like format. Can someone help me with an Ajax code for this. Also, it would be great if you could suggest how should I build the corresponding view for it.
The code that I tried to write is something like below:
<script type="text/javascript">
$(function() {
$('#profession').change(function() {
$.ajax({
url: '/fdp/instance_creation/(\d+)',
dataType: 'json',
type: 'GET',
// This is query string i.e. country_id=123
data: {instance_id : $('#profession').val()},
success: function(data) {
if(data == null || data ==""){
}
else{
document.getElementById("mytablebody").innerHTML="";
var srno=1;
for (var i = 0; i < data.length; i++) {
var table = document.getElementsByName("tablebody")[0];
var row = document.createElement('tr');
var cell1 = document.createElement('td');
var cell2 = document.createElement('td');
var cell3 = document.createElement('td');
var cell4 = document.createElement('td');
// var cell5 = document.createElement('td');
var text1 = document.createTextNode({{forloop.counter}});
var text2 = document.createTextNode(data[i].{{workshopid}});
var text3 = document.createTextNode(data[i].{{startdate}});
var text4 = document.createTextNode(data[i].{{enddate}});
// var text5 = document.createTextNode("");
cell1.appendChild(text1);
cell2.appendChild(text2);
cell3.appendChild(text3);
cell4.appendChild(text4);
//cell5.appendChild(text5);
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
row.appendChild(cell4);
//row.appendChild(cell5);
table.appendChild(row);
srno++;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
I am completely new in this field so it would be nice if you could pardon me for small mistakes.
What do you want to happen with this URL?
url: '/fdp/instance_creation/(\d+)',
Do you want something to be substituted at the end? You will have to do that beforehand. Do you want this:
url: '/fdp/instance_creation/' + $('#profession').val(),
Also, what did you mean by this code:
var text1 = document.createTextNode({{forloop.counter}});
var text2 = document.createTextNode(data[i].{{workshopid}});
var text3 = document.createTextNode(data[i].{{startdate}});
var text4 = document.createTextNode(data[i].{{enddate}});
The {{}} would be filled in on the Django side as templates. It really feels like you'd at least want:
var text1 = document.createTextNode(i);
The other ones could work if they resolve to field names in the JSON.
As for a view, you just need to respond with JSON data. To test, just make a view function that returns a hard-coded string like "[{'fld': 'val', 'fld2': 'val2'}]" (I don't know your real field names, but fill them in correctly)

With the Kendo UI Grid, how do you access the filtered and sorted data?

I have a Kendo grid that is sortable and filterable. When I export I want to export all the data that is currently viewable but not just the current page.
$("#grid").data("kendoGrid").dataSource -> seems to be the original list of items unsorted and unfiltered. In Chrome Developer tools, _data and _pristine seem to be the same.
There is also the dataSource.view but it is only the 10 items visible on the current page.
Is there a way to access the sorted list and/or filtered list?
update:
I have found this answer on the Kendo forums and will see if it helps.
http://www.kendoui.com/forums/framework/data-source/get-filtered-data-from-paged-grid.aspx
Here is how you access the filtered data:
var dataSource = $("#grid").data("kendoGrid").dataSource;
var filteredDataSource = new kendo.data.DataSource({
data: dataSource.data(),
filter: dataSource.filter()
});
filteredDataSource.read();
var data = filteredDataSource.view();
And then you can loop through the data:
for (var i = 0; i < data.length; i++) {
result += "<tr>";
result += "<td>";
result += data[i].SiteId;
result += "</td>";
result += "<td>";
result += data[i].SiteName;
result += "</td>";
result += "</tr>";
}
Most of the answers out there apply to the Kendo Grid when just looking at local data in memory. If you are using remote data (i.e. your grid is bound to an ODATA source for example) - you will need to iterate through all the pages to get the filtered data.
However, doing this was not as straight forward as I thought.
I came up with the following:
var filteredRows = [];
function getResults() {
var dataSource = $("#grid").data("kendoGrid").dataSource;
var filters = dataSource.filter();
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var data = query.filter(filters).data;
var totalRowCount = parseInt(dataSource.total().toString());
var totalPages = Math.ceil(totalRowCount / dataSource.pageSize());
PageTraverser(dataSource, 1, totalPages, filters, function () {
$('#pResults').text('Got ' + filteredRows.length + ' rows of filtered data.');
});
}
function PageTraverser(dataSource, targetPage, totalPages, filters, completionFunction) {
dataSource.query({
page: targetPage,
pageSize: 20,
filter: filters
}).then(function () {
var view = dataSource.view();
for (var viewItemId = 0; viewItemId < view.length; viewItemId++) {
var viewItem = view[viewItemId];
filteredRows.push(viewItem);
}
targetPage++;
if (targetPage <= totalPages) {
PageTraverser(dataSource, targetPage, totalPages, filters, completionFunction);
} else {
completionFunction();
}
});
}
Working example here: http://dojo.telerik.com/#JBoman32768/Ucudi
Here is how we are currently doing it, although there are multiple options:
var myData = new kendo.data.Query(dataSource.data()).filter(dataSource.filter()).data;
Your simply calling a new Query and applying the current filter that the grid has applied, which will return the exact same results as the grid.

Ext JS 4 - how to create multiple store instances and assign to views? (MVC)

How do you create unique instances of stores and assign them to views (I am ok with creating unique views and/or controllers if that's required)?
A simple use case - I want to open multiple grid's (of the same type) with a list of records from a store in each. Each grid would need to have it's own store instance, because it could have it's own list of records, it's own filtering, etc. etc.
I tried this, but it does not work, my grids do not draw:
var theView = Ext.create('App.view.encounter.List');
theView.title = 'WORC Encounters';
var theStore=Ext.create('App.store.Encounters');
theView.store=theStore;
tabhost.add({title:'WORC',items:theView});
var theView = Ext.create('App.view.encounter.List');
theView.title = 'NC Encounters';
var theStore2=Ext.create('App.store.Encounters');
theView.store=theStore2;
tabhost.add({title:'NC',items:theView});
You need to assign the store when the component is initializing (or before). In the initComponent.
Ext.define('classname', {
extend: 'Ext.grid.Panel',
//...
initComponent: function() {
var me = this;
var theStore = Ext.create('App.store.Encounters');
Ext.apply(me, {
store: theStore
});
me.callParent();
}
//...
});
You could also do it this way:
//Create the store
var theStore = Ext.create('App.store.Encounters');
//Create the view
var theView = Ext.create('App.view.encounter.List', {
store: theStore
});
Edit for you example specific:
var theStore = Ext.create('App.store.Encounters');
var theView = Ext.create('App.view.encounter.List', {
title: 'WORC Encounters',
store: theStore
});
tabhost.add({title:'WORC',items:theView});
var theStore2=Ext.create('App.store.Encounters');
var theView2 = Ext.create('App.view.encounter.List', {
title: 'NC Encounters',
store: theStore2
});
tabhost.add({title:'NC',items:theView2});

Resources