Regarding Population of Grid data with Ajax Polling - javascript

I have a Map which contains the status information as a value for a object.The Ajax should poll the map and update the status on the grid.I am facing issue in updating the same.
The code snippet I am using is:
setInterval(
$.post("./listStatus.action", {
method: "getStatus",
}, function( data, success ) {
if ( success == "success" ) {
var rowsIds = statusGrid.getDataIDs();
console.log("Row Ids:"+rowsIds);
for(var i=0;i<data.statusList.length;i++){
var rowData=statusGrid.jqGrid('getRowData',data.statusList[i].rowID);
rowData["Status"] =data.statusList[i].Status;
statusGrid.jqGrid('setRowData', data.statusList[i].rowID, rowData);
}
}
}),5000);
On first call its able to show the data however in second call onwards it gives Uncaught SyntaxError: Unexpected identifier
Can anybody help me out how to implement the use case and how to resolve the issue as i am new to JS.
Thanks

I don't know if this answers your question exactly but, it might get you going. In my experience with jqGrid my automatic grid refreshes looked something like this.
If my HTML looked like this:
<div style="margin: 10px;">
<table id="custGrid"></table>
<div id="ptoolbar"></div>
<div id="pager" class="scroll" style="text-align: center;"></div>
</div>
The the javascript has this:
var grid = $("#custGrid");
jQuery("#custGrid").jqGrid({ ... });
when I refresh the data in the grid I would do something like this:
jQuery("#custGrid").jqGrid('setGridParam', { search: true, postData: { filters: postobj }, page: 1 });
jQuery("#custGrid").trigger("reloadGrid");
The trigger reload tells jqGrid to fetch new data based on the revised grid parameters.
Hope this helps.

setInterval takes a function as first parameter :
setInterval(function () {
$.post("./listStatus.action", {
method: "getStatus",
}, function (data, success) {
if (success == "success") {
var rowsIds = statusGrid.getDataIDs();
console.log("Row Ids:" + rowsIds);
for (var i = 0; i < data.statusList.length; i++) {
var rowData = statusGrid.jqGrid('getRowData', data.statusList[i].rowID);
rowData["Status"] = data.statusList[i].Status;
statusGrid.jqGrid('setRowData', data.statusList[i].rowID, rowData);
}
}
});
}, 5000);
I haven't checked the rest of your code.

Related

Data update without page reload jinja2

The data has to be refreshed without page reload. Originally data is appeared on html with jinja2.
#app.route('/personal_account', methods=['POST'])
def welcome():
login = request.form['login']
data = get_default_user_data(login)
# ... processing
return render_sidebar_template("personal_account.html", data=data)
According to these data graph is building with chartist.js.
personal_account.html
<div id="data">
<ul id="consumed_values">
{% set count = 0 %}
{% for i in data.consumed_values %}
<li>{{ data.consumed_values[count] }}</li>
{% set count = count + 1 %}
{% endfor %}
</ul>
</div>
<canvas width="800" height="600" id="canvas"></canvas>
<button id="button">Update</button>
I need to update data. I am using ajax.
The function "request" make a post request to the server to the function get_selected_values in Python.
This function gives new data. But new data doesn't display in jinja2 on page. The data is still old.
personal_account.js
window.onload = draw();
function draw() {
var consumed_values = document.querySelectorAll('ul#consumed_values li');
var values = new Array();
for (var i = 0; i < consumed_values.length; i++) {
console.log(consumed_values[i].innerHTML);
values[i] = consumed_values[i].innerHTML;
}
var numbers = new Array();
for(var i=0; i<consumed_values.length; i++)
{
numbers[i]=i+1;
console.log(numbers[i]);
}
var ctx = document.getElementById('canvas').getContext('2d');
var grapf = {
labels : numbers,
datasets : [
{
strokeColor : "#6181B4",
data : values
}
]
}
new Chart(ctx).Line(grapf);
}
document.getElementById('button').onclick=function () {
request();
}
function reques() {
var first = selected[0];
var second = selected[1];
first.month = first.month+1;
second.month = second.month+1;
$.ajax({
type: 'POST',
url: '/get_selected_values',
success: function(response) {
alert('Ok');
draw();
},
error: function() {
alert('Error');
}
});
}
Function get_selected_values()
#app.route('/get_selected_values', methods=['POST'])
def get_selected_values():
# ...
data = fetch_selected_date(start_date=start_date, end_date=end_date, login=current_user.get_id())
if data:
# return jsonify({'result': True, 'data': data}) # does not work this way
# return jsonify({'result': False, 'data': []})
return render_sidebar_template("personal_account.html", data=data, result=1)
How to succeed in data's update and graph's rebuild?
EDIT 1
I am using the first version of get_selected_values function.
The request function look like this:
...
success: function(response) {
alert('Успешно получен ответ:!'+ response.data);
document.getElementById('consumed_values').innerHTML = response.data;
draw();
},
...
Data is updating successfully, but graph looks the same. How to fix?
OK here's my outlook on this. You're on the right track and there is a way to update the element without the need to re-draw the page in this instance. What's happening is that you are returning data from your get_selected_values() method but not doing anything with it once it's returned to your AJAX request.
So firstly, I'm going to draw your attention to your AJAX request:
$.ajax({
type: 'POST',
url: '/get_selected_values',
success: function(response) {
alert('Ok');
draw();
},
error: function() {
alert('Error');
}
});
When you're getting a successful response from this, you're seeing your "OK" alert in the UI, right? However nothing updates in the UI despite you calling on the draw() method?
You won't want to return a render_template from your Flask function in this case. You were already on the right track with returning JSON from your function:
if data:
# return jsonify({'result': True, 'data': data}) # does not work this way
When you return your JSON data, it will be stored in the response variable in your success function. If you're unsure of exactly what's going into that response variable then output its contents with something like alert(JSON.stringify(response)) in the success function of your AJAX request. From here you will see your data returned to your method.
Now you need to decide how you want to use that data to update your <div id="data"> element in your UI. You can do this just using JavaScript with a series of document.getElementById('element_id').innerHTML statements or such-like so that your element is populated with all of the updated data from your response.
This will auto-update the data you wish to have displayed without the need to refresh the page.
Now that you've done that, invoke your draw() function again and it should now use the updated data.
I hope this helps set you down the right path with this one!
AFTER EDIT 1
When you're originally populating <div id="data"> you are using a loop to populate a series of <li> tags in the element with your data.
When you are updating this element with your new data, you are just using .innerHTML to re-populate the parent <ul> element.
Your draw() method is looking to the data stored in the <li> elements.
Are you absolutely certain that, after you perform your update, your <div id="data"> element is in exactly the same (ie. expected) format to work with your draw() method? In that it's still in the structure:
<div id="data">
<ul id="consumed_values">
<li>Your updated data here...</li>
<li>More updated data...</li>
</ul>
</div>
This is the element structure that your draw() method is expecting to find. It's pulling its data in from each individual <li> element in the list. So these are the elements which need to store your updated values.

How to add content via ajax using the popover boostrap

I tried to view different sources and also looked into the forums posting similar question, but it didnt quite help me with the issue that im facing.
I have a text input filed to which I'm adding a popover to show similar a list of names in the database. The inout field checks for validation, to see if the name entered is unique, if not it displays similar names available in the database that could be re-used.
here is the popover snippet:
$("#account_name_create").popover({
title: 'Twitter Bootstrap Popover',
content: function (process) {
this.accountCollection = new ipiadmin.collections.AccountCollection();
var newName = $("#new-account-form #account_name_create").val();
var userFilter = "accountName~'" + newName + "'";
this.accountCollection.fetch({
data: { "f": userFilter,
"sortby": null,
"type":"ipi",
"pageno":0,
"pagesize":2,
"reversesort" : true
},
cache: false,
success: function(model, response, options) {
var states = [];
map = {};
$.each(model.aDataSet, function (i, state) {
map[state.accountName] = state;
states.push(state.accountName);
});
process(states); //gives an error saying 'undefined is not a function (says process is undefined)'
},
error: function(model, response, options) {
console.log('error');
}
});
},
});
here is the html:
<input type="text" id="account_name_create" name="account_name" class="" size="40" />
I'm not sure how why it says 'process' as undefined. Also not sure if this would be the correct way of displaying the data in the popover.
Any ideas??
Thanks!
process doesn't have scope in the success function, only in the content function. If you want to call the process function from within the success function, you could define it somewhere outside of the jQuery call.

Having issues tying together basic javascript chat page

I have the skeleton of a chat page but am having issues tying it all together. What I'm trying to do is have messages sent to the server whenever the user clicks send, and also, for the messages shown to update every 3 seconds. Any insights, tips, or general comments would be much appreciated.
Issues right now:
When I fetch, I append the <ul class="messages"></ul> but don't want to reappend messages I've already fetched.
Make sure my chatSend is working correctly but if I run chatSend, then chatFetch, I don't retrieve the message I sent.
var input1 = document.getElementById('input1'), sendbutton = document.getElementById('sendbutton');
function IsEmpty(){
if (input1.value){
sendbutton.removeAttribute('disabled');
} else {
sendbutton.setAttribute('disabled', '');
}
}
input1.onkeyup = IsEmpty;
function chatFetch(){
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
method: "GET",
success: function(data){
$(".messages").clear();
for(var key in data) {
for(var i in data[key]){
console.log(data[key][i])
$(".messages").append("<li>"+data[key][i].text+"</li>");
}
}
}
})
}
function chatSend(){
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input1.draft').val()}),
success:function(message){
}
})
}
chatFetch();
$("#sendbutton").on('click',chatSend());
This seems like a pretty good project for Knockout.js, especially if you want to make sure you're not re-appending messages you've already sent. Since the library was meant in no small part for that sort of thing, I think it would make sense to leverage it to its full potential. So let's say that your API already takes care of limiting how many messages have come back, searching for the right messages, etc., and focus strictly on the UI. We can start with our Javascript view model of a chat message...
function IM(msg) {
var self = this;
self.username = ko.observable();
self.message = ko.observable();
self.timestamp = ko.observable();
}
This is taking a few liberties and assuming that you get back an IM object which has the name of the user sending the message, and the content, as well as a timestamp for the message. Probably not too far fetched to hope you have access to these data elements, right? Moving on to the large view model encapsulating your IMs...
function vm() {
var self = this;
self.messages = ko.observableArray([]);
self.message = ko.observable(new IM());
self.setup = function () {
self.chatFetch();
self.message().username([user current username] || '');
};
self.chatFetch = function () {
$.getJSON("https://api.parse.com/1/classes/chats", function(results){
for(var key in data) {
// parse your incoming data to get whatever elements you
// can matching the IM view model here then assign it as
// per these examples as closely as possible
var im = new IM();
im.username(data[key][i].username || '');
im.message(data[key][i].message || '');
im.timestamp(data[key][i].message || '');
// the ([JSON data] || '') defaults the property to an
// empty strings so it fails gracefully when no data is
// available to assign to it
self.messages.push(im);
}
});
};
}
All right, so we have out Javascript models which will update the screen via bindings (more on that in a bit) and we're getting and populating data. But how do we update and send IMs? Well, remember that self.message object? We get to use it now.
function vm() {
// ... our setup and initial get code
self.chatSend = function () {
var data = {
'user': self.message().username(),
'text': self.message().message(),
'time': new Date()
};
$.post("https://api.parse.com/1/classes/chats", data, function(result) {
// do whatever you want with the results, if anything
});
// now we update our current messages and load new ones
self.chatFetch();
};
}
All right, so how do we keep track of all of this? Through the magic of bindings. Well, it's not magic, it's pretty intense Javascript inside Knockout.js that listens for changes and the updates the elements accordingly, but you don't have to worry about that. You can just worry about your HTML which should look like this...
<div id="chat">
<ul data-bind="foreach: messages">
<li>
<span data-bind="text: username"></span> :
<span data-bind="text: message"></span> [
<span data-bind="text: timestamp"></span> ]
</li>
</ul>
</div>
<div id="chatInput">
<input data-bind="value: message" type="text" placeholder="message..." />
<button data-bind="click: $root.chatSend()">Send</button>
<div>
Now for the final step to populate your bindings and keep them updated, is to call your view model and its methods...
$(document).ready(function () {
var imVM = new vm();
// perform your initial search and setup
imVM.setup();
// apply the bindings and hook it all together
ko.applyBindings(imVM.messages, $('#chat')[0]);
ko.applyBindings(imVM.message, $('#chatInput')[0]);
// and now update the form every three seconds
setInterval(function() { imVM.chatFetch(); }, 3000);
});
So this should give you a pretty decent start on a chat system in an HTML page. I'll leave the validation, styling, and prettifying as an exercise to the programmer...

How do I create a web link inside a javascript function and pass cell value as a parameter to servlet?

I am creating a table dynamically with JavaScript as you can see below. I want users to be able to click on the first column value and pass the value of the cell as a parameter to a J#EE servlet. Can you help me? Basically the first column should be links to a new page with a country details. How can I do that? Thank you.
Where do I put the link code?
function oneSecondFunction() {
$.get('DisplayCountries', function(responseJson) {
if (responseJson != null) {
$("#countrytable").find("tr:gt(0)").remove();
var table1 = $("#countrytable");
$.each(responseJson, function(key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td>" +
"<td></td><td></td></tr>");
rowNew.children().eq(0).text(value['id']);
rowNew.children().eq(1).text(value['country1']);
rowNew.children().eq(2).text(value['country2']);
rowNew.children().eq(3).text(value['country3']);
rowNew.children().eq(4).text(value['country4']);
rowNew.children().eq(5).text(value['country5']);
rowNew.children().eq(6).text(value['country6']);
rowNew.children().eq(7).text(value['country7']);
rowNew.children().eq(8).text(value['country8']);
rowNew.appendTo(table1);
});
}
});
and here is the link code. I have tried several options and it doesn't work.
id
First, assign a class to the first <td> something like <td class="linkHolder">.
Then, write a click handler to send ajax request to servlet:
$('#countrytable').on('click', '.linkHolder', function() {
var link = $(this).html();
$.post('/myservlet', {url: link}, function(response) {
//handle response here
});
return false;
});
You can access the link on the servlet side with the request parameter url

Ajax POSTS not updating screen content

So I have a "scenario", made up of lots of "forms" which contain lots of "events" and "data" etc. To populate all this information I have this in the page to run once the page is finished
$(document).ready(function() {
var scenarioID = ${testScenarioInstance.id}
var myData = ${results as JSON}
populateFormData(myData, scenarioID);
});
This then calls the functions below (the first calls the second, done like this as I had an issue where as it was ajax the variables in the loop were updating before things were being appended and so everything ended up in the last sub table): -
function populateFormData(results, scenarioID) {
$table = $('#formList')
for ( var i in results) {
var formIDX = (results[i]["forms_idx"])
var formID = (results[i]["form_id"])
appendSubTable(formIDX, scenarioID, $table, formID);
}
}
function appendSubTable(formIDX, scenarioID, $table, formID) {
var url = "http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
$subTable.append(data)
}).fail(function() {
alert("it failed!")
});
}
This then goes off grabs the data from the controller like so..
def ajaxPopulateSubTables(int formIDX, int scenarioID, int formID) {
def db = new Sql(dataSource)
String mySQL = "Loads of SQL STUFF"
def subTableResults = db.rows(mySQL)
render(template: "subTableEntry", model: [subTableResults:subTableResults, formID:formID, formIDX:formIDX])
}
and fires it at the gsp:
<colgroup>
<col width="150"/>
<col width="350"/>
<col width="350"/>
<col width="350"/>
</colgroup>
<g:if test="${subTableResults != null && !subTableResults.isEmpty()}">
<tr>
<th>eventIDX</th>
<th>eventID </th>
<th>objID</th>
<th>testVal</th>
</tr>
</g:if>
<g:each in="${subTableResults}" status = "i" var="item">
<tr id = ${i} class="${((i) % 2) == 0 ? 'even' : 'odd'}" name="main">
<td>${item.events_idx}</td>
<td>${item.type}</td>
<td>${item.object_description}</td>
<td><g:textField id = "testData[${formIDX}:${formID}:${i}]" name="testData[${formIDX}:${formID}:${i}]" value="${item.value}" optionKey="id" /></td>
</tr>
</g:each>
Before then jamming it into the relevant sub table.
The problem is, sometime when I load up a page not all the sub tables are filled out, but if I hit F5 to refresh the page this then seems to fix the issue... Although not always, sometimes I then get a different section not refreshing :(
I put a println into the controller to see if all the SQLs were being fired off but it always returns all the individual form SQL strings fine...
Looking in firebug all the POSTs are coming back fine but the page just isn't updating...
Any suggestions or ideas as to what might be causing this would be appreciated, I'm at a loss..
I also tried updating my appendSubTable function where the post is to include a fail in case something was failing, but this isn't hit either, have updated code above to show this
Oddly I altered the post function slightly to the below, moving the finding of the table to the beginning of the function rather than within the post itself and that seems to have done the trick, although why I'm not sure... Whether someone can explain why this is or not I'd be interested to know why!
function appendSubTable(formIDX, scenarioID, $table, formID) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url = "http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
$subTable.append(data)
}).fail(function() {
alert("fail")
});
}

Categories