how can i change div by click in javascript? - javascript

when i click one item in a.jsp, which is made by b.js calls c.js's function of getGrid() to show one more table.
it shows data of what i click in console well. but table grid-table-1 doesn't changed.
what i want is when i click another item, i want to call getGrid again to show data.
but in my code, only first click works
what is the problem? thanks!
itemClick: function(data){
getGrid(data.data.ITM_ID);
console.log(data.data.ITM_ID);
}
a.jsp
<nav>
<ul>
<li><a class="tri" href="javascript:void(0);" onclick="callMonth(50035);callSubtitle('살인'); this.onclick=null">살인</a></li>
<li><img src="css/f4f0edb08c97567ce6b0475a63bf7000.png" alt="Italian Trulli" width="40px" height="25px"></img></li>
<li>살인</li>
</ul>
</nav>
<div class="wrap">
<h3>등락율 순위</h3>
<table id="grid-table-1">
</table>
</div>
b.js
function callMonth(num) {
$.ajax({
url : 'http://www.crimestats.or.kr/openapi/Sttsapitbldata.do?KEY=373f2cc31cd449c992cc18004780f4e4&STATBL_ID=T184223019918177&DTACYCLE_CD=YY&WRTTIME_IDTFR_ID=2016&Type=json&CLS_ID='+num,
type : 'GET',
dataType: 'json',
success : function (resp) {
$(".chart01").html("");
console.log(resp);
var options = {
data : {
data: []
},
format: {
xAxis: function (_str) {
return _str.substr(0, 4);
},
yAxis: 'priceDataFormat'
},
func : {
tip: function (tipElement, data, rect) {
//console.log(data)
var date = data.xaxis.substr(0, 4);
var tip = '<div class="text">' + date + ' / ' + String(data.yaxis).format().trim() + '</div>';
tipElement.html(tip).show();
var arrow = '<div class="arrow" style="width: ' + tipElement.width() + 'px;"></div>';
tipElement.html(tipElement.html() + arrow).css({
left: rect.x - (tipElement.width() / 2), top: rect.y - 35
});
},
itemClick: function(data){
getGrid(data.data.ITM_ID);
console.log(data.data.ITM_ID);
}
},
use : {
animate : true,
aCrossLine: true
}
};
var rows = resp.Sttsapitbldata[1].row;
if (rows) {
var representativeRow;
for (i = 1; i < 13; i++) {
representativeRow = rows[i];
itemNm2 = representativeRow.ITM_NM;
dataV = representativeRow.DTA_VAL;
itm_id= representativeRow.ITM_ID;
/* console.log(itemNm2);
console.log(dataV);
console.log(itm_id);*/
options.data.data.push({DTA_VAL: dataV, ITM_NM: itemNm2, ITM_ID:itm_id});
}
var series = {
"main": {
"s1": {series: 'column', xaxis: 'ITM_NM', yaxis: 'DTA_VAL'}
}
};
event.stopPropagation();
var chart = webponent.chart.init($('.chart01'), options, styles, series);
}
}, /*error: function (xhr, status, error) {
alert("err")
}*/
});
}
c.js
function getGrid(itm_id_num) {
$(".grid-table-1").html("");
var table1 = $('#grid-table-1');
var template1 = $('#grid-template-1');
var grid1 = webponent.grid.init(table1, template1);
var body = [];
$.ajax({
dataType: 'json',
url : 'http://www.crimestats.or.kr/openapi/Sttsapitbldata.do?KEY=373f2cc31cd449c992cc18004780f4e4&STATBL_ID=T184223019918177&DTACYCLE_CD=YY&WRTTIME_IDTFR_ID=2016&Type=json&ITM_ID='+itm_id_num,
success : function (resp) {
var options = {
data: {
data: []
}
};
var rows = resp.Sttsapitbldata[1].row;
//console.log(rows);
if (rows) {
var representativeRow;
for (i = 11; i < 100; i++) {
representativeRow = rows[i];
itemNm2 = representativeRow.ITM_NM;
dataV = representativeRow.DTA_VAL;
stable_id = representativeRow.STATBL_ID;
cls_nm = representativeRow.CLS_NM;
cls_id = representativeRow.CLS_ID;
/* console.log(itemNm2);
console.log(dataV);*/
options.data.data.push({
ITM_NM : itemNm2,
STATBL_ID: stable_id,
CLS_NM : cls_nm,
CLS_ID : cls_id,
DTA_VAL : dataV
});
}
grid1.appendRow(options.data.data);
}
}
});
}

Related

Tree_view undefined after read kendo tree

Here's my problem:
I load a first time my tree to display him.
I can change the value of the Session's files name "state" to enable or disable a node in my tree.
But after I change ne value in my database and return the JSON, I read again the tree to refresh my tree with the changes but it's failed and write in console :
" TypeError: Tree_view.getElementsByClassName(...)[0].children[(item.id_perso - 1)].children[1] is undefined".
That I don't understand is I pass my first time by these functions and it work well, but when I reload it failed apparently because the it undefined.
Thank's for any help.
$(document).ready(function() {
$('#Tree_view').kendoTreeView({
template: "#= item.name #",
dataSource: Parcours,
dataTextField: 'name',
loadOnDemand: true,
expand: onExpandedItem
});
});
function onExpandedItem(e) {
var id_user = #Model.id;
var item = $('#Tree_view').data('kendoTreeView').dataItem(e.node);
var treeview = $('#Tree_view').data('kendoTreeView');
var type = item.fields.type;
if (item.level() > 0) {
item.id_parcours = item.parentNode().id_parcours;
if (item.level() == 2) {
item.id_promo = item.parentNode().id;
}
}
else item.id_parcours = item.Id;
switch (type) {
case 'parcours':
item.children.transport.options.read = {
url: '#Url.Action("Get_Session", "Users")' + '?user_id=' + id_user,
dataType: "json",
};
break;
case 'session':
item.children.transport.options.read = {
url: '#Url.Action("Get_Matiere")' + '?user_id=' + id_user,
dataType: "json"
};
break;
default:
break;
}
if (item.level() == 0) {
setTimeout(function() { waitDisable(item, treeview); }, 1000);
}
}
function waitDisable(item, treeview) {
if (item.fields.type == "parcours")
{
var node = Tree_view.getElementsByClassName('k-group')[0].children[item.id_perso - 1].children[1].children;
for (i = 0; i < item.children._data.length; i ++)
{
if (item.children._data[i].state != null) {
node[i].children[0].children[1].className = "k-in k-state-disabled";
node[i].children[0].children[0].className = ".k-icon-remove";
}
else node[i].children[0].children[0].className = "k-icon k-plus";
addRow(node, item, i, treeview);
}
}
}
var cmp = 0;
var One_Time = false;
function addRow(node_Here, item, i, treeview) {
var actual_row = node_Here[i].children[0];
if (actual_row.childNodes.length < 3) {
var newSpan = document.createElement('button');
if (item.children._data[i]._childrenOptions.data.state != null) {
newSpan.appendChild(document.createTextNode("Re-Up"));
newSpan.className = "change_state btn btn-success btn-xs";
}
else {
newSpan.appendChild(document.createTextNode("Down"));
newSpan.className = "change_state btn btn-danger btn-xs";
}
actual_row.appendChild(newSpan);
}
cmp += 1;
if (cmp == item.children._data.length)
One_Time = true;
if (One_Time) {
addClickListner(item, i, treeview);
One_Time = false;
cmp = 0;
}
}
function addClickListner(item, i, treeview) {
$(".change_state").click(function (event) {
var name_Promo_Rm = event.target.parentNode.children[1].textContent;
var User_Select = event.view.Parcours.transport.read.data.user_id;
$.ajax({
url: '#Url.Action("ChangeStatutBase", "Users")',
type: 'GET',
dataType: 'json',
data: { Name_Promo: name_Promo_Rm, User_id: User_Select },
});
refreshTree(treeview);
})
}
// Refresh tree
function refreshTree(treeview) {
// Save open items
saveExpandedItems(treeview);
// Reload data source
treeview.dataSource.read();
// Load open items
console.log("OKKKKKKK");
setTimeout(loadExpandedItems(), 600);
}
I've resolved my problem, in the "setTimeout" in the bottom I've placed "()" in the first parameter and it doesn't put the pause and data don't have the time to be loaded.

Update textarea after get response from servlet in javascript

I have a program which calls a function in javascript with 1 o more requests to 1 servlet, I want to execute request after request and get the response after each exucution, to make this I have 1 function, but it only shows the result after all requests have been executed.
function cmd(args) {
width = 0;
var res = args.split('\n');
var largo = res.length;
var progressLength = 100 / largo;
for (var i = 0; i < largo; i++)
{
if (res[i] == 'desconectar')
{
desconectar();
break;
}
else
{
executeCMD(res[i]);
}
}
}
function executeCMD(args)
{
$.ajax({
type: "POST",
url: 'Controlador',
data: {cmd: args, operacion: 1},
success: function (response) {
document.getElementById('respuesta').value = document.getElementById('respuesta').value + response;
},
dataType: 'text',
async: false
});
}
If I add window.alert(response); inside success field it shows the progress step by step and works fine, but it show alerts which I don't want.
This is I want http://imgur.com/a/9nclR but I'm getting only last picture.
The solution if anyone is intersting was using a recursive function as next:
function cmd(args) {
width = 0;
move(0);
var res = args.split('\n');
var largo = res.length;
var valInit = 0;
if (largo > valInit)
{
executeCMD(res, valInit);
}
}
function executeCMD(args, i)
{
$(document).ready(function () {
$.ajax({
type: "POST",
url: 'ControladorServlet',
data: {cmd: args[i], operacion: 1, ticket: ticket, iddispositivo: sesion},
success: function (response) {
var textarea = document.getElementById('respuesta');
var res = response.trim().split('\n');
if(error){//dc}
else
{
document.getElementById('respuesta').value = document.getElementById('respuesta').value + response.trim() + "\n\n";
var valor = (100) * (i + 1) / args.length;
move(valor);
if (i + 1 < args.length)
{
executeCMD(args, i + 1);
}
}
},
dataType: 'text'
});
});
}

Can ghost.py scrape a web page with javascript setInterval update repeatedly?

I plan to use Ghost.py to scrape a web page which is updated every 5 seconds by setInterval.
How can I scrape the updated data by Ghost.py repeatedly, once there is a new update by this script?
The setInterval code below:
(function () {
var template;
(function () {
template = $("#template1 tbody").html();
GetData();
})();
function GetData() {
var max = 100,
sn = $.data(document, "sn");
if (sn === undefined) {
sn = 0;
} else {
sn = parseInt(sn, 10);
}
$.ajax({
url: path + "ashx/notice.ashx",
async: true,
cache: false,
data: {
act: "GetBotSignal",
sn: sn,
max: max
},
type: "get",
dataType: "json",
success: function (data) {
if (data !== null && data.length !== 0) {
var html = "";
var expselbox = $(".exp-sel-box");
for (var i = 0, j = data.length; i < j; i++) {
var item = template;
item = item.replace(/\{0}/g, data[i].SignalOccurTime);
(parseFloat(data[i].Ratio) >= 2 && parseFloat(data[i].Probability) >= 50) ? " sp" : "");
html += item;
}
expselbox.prepend("<tr ef=\"1\" style=\"height:0px;\"></tr>");
expselbox.find("tr[ef=1]").animate({ "height": (34 * data.length) + "px" }, "fast", function () {
expselbox.find("tr[ef='1']").remove();
expselbox.prepend(html);
expselbox.find("tr:hidden").fadeIn("fast");
expselbox.find("tr:gt(" + max + ")").remove();
$.data(document, "sn", data[0].SN);
ScrollBar($(".expscall-out"), 642, 342, true);
});
}
}
});
}
if (srvTime.getHours() > 7 && srvTime.getHours() < 14) {
setInterval(function () {
GetData();
}, 5000);
}
})();

Ad Block Plus Blocking jQuery Script?

I have a script that pulls data from my CMS and then allows a person to vote on a poll. The script works fine. However, I have Ad Block Plus Plugin installed in Firefox. When that is enabled to blocks the script from submitting the form correctly. It appears to submit correctly in the front end but is never registered in the back end.
Why does Ad Block Plus block my script that has nothing to do with ads?
The script is below:
$(document).ready(function () {
var Engine = {
ui: {
buildChart: function() {
if ($("#pieChart").size() === 0) {
return;
}
var pieChartData = [],
totalVotes = 0,
$dataItems = $("ul.key li");
// grab total votes
$dataItems.each(function (index, item) {
totalVotes += parseInt($(item).data('votes'));
});
// iterate through items to draw pie chart
// and populate % in dom
$dataItems.each(function (index, item) {
var votes = parseInt($(item).data('votes')),
votePercentage = votes / totalVotes * 100,
roundedPrecentage = Math.round(votePercentage * 10) / 10;
$(this).find(".vote-percentage").text(roundedPrecentage);
pieChartData.push({
value: roundedPrecentage,
color: $(item).data('color')
});
});
var ctx = $("#pieChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx).Pie(pieChartData, {});
}, // buildChart
pollSubmit: function() {
if ($("#pollAnswers").size() === 0) {
return;
}
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button"),
bcField_1 = "CAT_Custom_1",
bcField_2 = "CAT_Custom_2",
bcField_3 = "CAT_Custom_3",
$formSubmitData = "";
$radioOptions.on("change", function() {
$formButton.removeAttr("disabled"); // enable button
var chosenField = $(this).data("field"), // gather value
answer_1 = parseInt($existingDataWrapper.data("answer-1")),
answer_2 = parseInt($existingDataWrapper.data("answer-2")),
answer_3 = parseInt($existingDataWrapper.data("answer-3"));
if (chosenField == bcField_1) {
answer_1 = answer_1 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_2) {
answer_2 = answer_2 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_3) {
answer_3 = answer_3 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
prepForm($formSubmitData);
});
function prepForm(formSubmitData) {
$formButton.click(function(e) {
e.preventDefault();
logAnonUserIn("anon", "anon", formSubmitData); // log user in
}); // submit
} // prepForm
function logAnonUserIn(username, password, formSubmitData) {
$.ajax({
type: 'POST',
url: '/ZoneProcess.aspx?ZoneID=-1&Username=' + username + '&Password=' + password,
async: true,
beforeSend: function () {},
success: function () {},
complete: function () {
fireForm(formSubmitData);
}
});
} // logAnonUserIn
function fireForm(formSubmitData) {
// submit the form
var url = "/CustomContentProcess.aspx?A=EditSave&CCID=13998&OID=3931634&OTYPE=35";
$.ajax({
type: 'POST',
url: url,
data: formSubmitData,
async: true,
success: function () {},
error: function () {},
complete: function () {
window.location = "/";
}
});
}
} // pollSubmit
} // end ui
};
Engine.ui.buildChart();
Engine.ui.pollSubmit();
});
As it turns out easylist contains this filter:
.aspx?zoneid=
This is why my script is being blocked.
I was told I can try this exception filter:
##||example.com/ZoneProcess.aspx?*$xmlhttprequest
I could also ask easylist to add an exception.
Answer comes from Ad Block Plus Forums.

jquery ajax not populating the drop down on first call

I have an input text box which fires each time when the user enters data and fills the input text.I'm using bootstrap typehead. Problem is when i enter a letter a it does fire ajax jquery call and fetch the data but the input text box is not populated.Now when another letter aw is entered the data fetched against letter a is filled in the text area.
I have hosted the code here http://hakunalabs.appspot.com/chartPage
Ok so here is part of my html code
<script type="text/javascript">
$(document).ready(function () {
$('#txt').keyup(function () {
delay(function () {
CallData();
}, 1000);
});
});
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
</script>
<input type="text" id="txt" runat="server" class="span4 typeahead local remote" placeholder="Search..." />
And here is my javascript code
var DataProvider;
function CallData() {
DataProvider = [];
var vdata = $('#txt').val();
if (vdata != "") {
var urlt = "http://examples/search?keyword=" + vdata + "&callback=my_callback";
$.ajax({
type: "GET",
url: urlt,
jsonpCallback: "my_callback",
dataType: "jsonp",
async: false,
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
}
function my_callback(data) {
var NameArray = new Array();
var descArray = new Array();
for (var i = 0; i < data.count; i++) {
NameArray.push(data.response[i].days_till_close + " Days Left | " + data.response[i].name + " | " + data.response[i].description);
}
for (var i = 0; i < data.count; i++) {
descArray.push(data.response[i].description);
}
DataProvider = [];
for (var i = 0; i < data.count; i++) {
var dataObject = { id: i + 1, name: NameArray[i], description: descArray[i] };
DataProvider.push(dataObject);
}
var vdata = $('#txt').val();
var urlp = "http://example.com/v1/members/search?keyword=" + vdata + "&my_callbackMember";
$.ajax({
type: "GET",
url: urlp,
jsonpCallback: "my_callbackMember",
dataType: "jsonp",
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
function my_callbackMember(data) {
var memberArray = new Array();
for (var i = 0; i < data.count; i++) {
memberArray.push(data.response[i].name);
}
for (var i = 0; i < data.count; i++) {
var dataObject = { id: i + 1, name: memberArray[i] };
DataProvider.push(dataObject);
}
localStorage.setItem("name", JSON.stringify(DataProvider));
var sources = [
{ name: "local", type: "localStorage", key: "name", display: "country" }
];
$('input.typeahead.local.remote').typeahead({
sources: [{ name: "", type: "localStorage", key: "name", display: "name"}],
itemSelected: function (obj) { alert(obj); }
});
}
Your issue is that typeahead can only present to you the results that are already in localstorage at the moment when you do a key press. Because your results are fetched via AJAX, they only show up in localstorage a second or so AFTER you've pressed the key. Therefore, you will always see the results of the last successful ajax requests in your typeahead results.
Read the bootstrap documentation for type aheads http://twitter.github.com/bootstrap/javascript.html#typeahead and read the section about "source". You can define a "process" callback via the arguments passed to your source function for asynchronous data sources.

Categories