How to refresh table after everytime button click in ajax call - javascript

I want to show data in a table by clicking on a searching button. I am facing issue which is that if there is no data in between "Fromdate - Todate" , error is coming properly but now after this i enter correct fromdate and todate then nothing is displaying in table. I checked chrome console data is coming from backend but not displaying in table
$('#paymentdetails').click(function() {
var getData = basePath + 'Admin/GetPaymentsForDate/?FromDate=' + $(".datepickerInputFROM").val() + '&ToDate=' + $(".datepickerInputTO").val()
if (($(".datepickerInputFROM").val() == "") && ($(".datepickerInputTO").val() == "")) {
alertify.alert('Please select dates to proceed.')
return false;
//$('#financetbl').html('');
} else if (($(".datepickerInputFROM").val() == "") || ($(".datepickerInputTO").val() == "")) {
alertify.alert('Please select dates to proceed.')
return false;
//$('#financetbl').html('');
}
$.ajax({
url: getData,
async: true,
success: function(response) {
// alert(response[0]);
$('#financetbl').html('');
// if (response.resultCourse != '' && response[0]!= 'null') {
if (response.length > 0) {
var tr;
for (var i = 0; i < response.length; i++) {
tr = '<tr>'
tr += "<td>" + response[i].applicationNumber + "</td>";
tr += "<td>" + response[i].applicantName + "</td>"
tr += '</tr>'
$('#financetbl tbody').append(tr);
}
inittable();
console.log(response)
} else {
console.log(response)
alertify.alert("Error : No Payments Details Found");
//flush the table
$('#financetbl').html('No Payments Details Found');
}
}
});
});

I believe that when you execute:
$('#financetbl').html('');
Then tbody is gone you lose your selector for:
$('#financetbl tbody').append(tr);
I think the first line should be:
$('#financetbl tbody').empty();

change
$('#financetbl').html('No Payments Details Found');
to
$('#financetbl').html('<tr><td colspan="2">No Payments Details Found</td></tr>');

You have excess if statements and need to properly manage the table when results returned are empty. So let's put that in an empty table row.
No idea what inittable(); does so you may have to fix this to account for that.
$('#paymentdetails').on('click', function() {
if (($(".datepickerInputFROM").val() == "") || ($(".datepickerInputTO").val() == "")) {
alertify.alert('Please select dates to proceed.')
return false;
}
var getData = basePath + 'Admin/GetPaymentsForDate/?FromDate=' + $(".datepickerInputFROM").val() + '&ToDate=' + $(".datepickerInputTO").val();
$.ajax({
url: getData,
async: true,
success: function(response) {
$('#financetbl').find('tbody').html('');
if (response.length > 0) {
var tr;
for (var i = 0; i < response.length; i++) {
tr = '<tr>'
tr += "<td>" + response[i].applicationNumber + "</td>";
tr += "<td>" + response[i].applicantName + "</td>"
tr += '</tr>'
$('#financetbl tbody').append(tr);
}
inittable();
console.log(response);
} else {
console.log(response);
alertify.alert("Error : No Payments Details Found");
//flush the table
$('#financetbl').find('tbody').html('<tr><td>No Payments Details Found</td></tr>');
}
}
});
});

Try something like JSON.parse()
var json = '{"applicationName":"XYZ","applicationNumber":1}',
obj = JSON.parse(json);
alert(obj.applicationName);
or
var json = '{"applicationName":"XYZ","applicationNumber":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);

Related

ajax loading do not working with async:false

I'm trying to make loading appear before making a request using ajax and even then the screen is only locked.
JS:
function showEstoque(productId) {
if (url !== '' && url != '-1') {
if (active) {
hideEstoques(active);
}
var target = document.getElementById("productInfo" + productId);
target.innerHTML = generateRows(productId);
target.style.display = "block";
active = productId;
}
}
function hideEstoques(productId) {
document.getElementById("productInfo" + productId).style.display = "none";
active = null;
}
function generateRows(productId) {
var rows = '';
rows += generateRowsEstoque(productId);
rows += generateRowsReserva(productId);
return rows;
}
function generateRowsEstoque(productId) {
var textContent = searchE(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse[0].nothing : null;
if (!data)
return '<span>Nothing</span><table><tr><td>Nothing</td></tr></table>';
var rows = '<span>Nothing</span> <table><thead> <tr> <th>Nothing</th></tr> </thead> <tbody>';
for(var n=0; n < data.length; n++) {
rows += '<tr>' +
'<td>' + data[n].nothing + '</td>' +
'</tr>';
}
rows += '</tbody> </table>';
return rows;
}
function searchE(productId) {
var view_data = "[]";
jQuery.ajax({
url: url + "product/" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function generateRowsReserva(productId) {
var textContent = searchEReserva(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse : null;
if (!data)
return '<table class="info"><tr><td class="none">Nothing</td></tr></table>';
var foo = data.filter(function(p) { return p.idType === 'foo' });
var bar = data.filter(function(p) { return p.idType === 'bar' });
var fooQtd = foo.length ? foo[0].nothing : 0;
var barQtd = bar.length ? bar[0].nothing : 0;
var rows = '<br/><table class="info"><thead> <tr class="labels"> <th>Nothing</th> </tr> </thead> <tbody>';
rows += '<tr>' +
'<td>' + fooQtd + '</td>' +
'<td>' + barQtd + '</td>' +
'</tr>';
rows += '</tbody> </table>';
return rows;
}
function searchEReserva(productId) {
var view_data = "[]";
$j.ajax({
url: "url" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function startLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "";
}
}
function stopLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "none";
}
}
HTML:
<td
onclick="showEstoque(1);">
<div id="estoque_1" class="estoqueCor st-color_"/>">1</div>
<img id="imgEstoqueProduto"
style="vertical-align: middle; display: none;"
src="<c:url value="/images/ajaxLoader.gif"/>">
<div class="container-product-info">
<div onmouseout="hideEstoques(1);"
class="productInfo"
id="productInfo1"></div>
</div>
</td>
I tried to use the beforeSend, call before the ajax method starts, ajaxStart and even then it doesn't work and the screen just hangs. Could you help me please?
I called startLoading before everything and it still doesn't work
I removed async: false but, I need to wait for the data to be returned from the API

keep the memory of more than one index

I have more than three TextBoxes. I want to send this data as in the code. The "indeks " value is always the last click. How do I keep the index?
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
if (txtvalue != "") {
if (i)
field += " and ";
field = field + "[" + obje[indeks]+ "]" $(this ).val() + "'";
i++;
}
});
});
},
As I wasn't sure if I got your question right, I prefered to comment on your topic - but now it seems that my answer helped you, so I decided to post it as an actual answer:
1st step: declare an array outside your success handler
2nd step: push the index and the value for the element into this array
3rd step: loop through all entries of the array and build your 'select' statement
Here is your edited example:
https://jsfiddle.net/Lk2373h2/1/
var clickedIndexes = [];
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
$(this).attr('id', i);
var txtvalue=$(this).val();
if (i)
clickedIndexes.push({
index: indeks,
value: $(this ).val()
});
var selectString = "";
for (var u = 0; u < clickedIndexes.length; u++) {
selectString += "[" + obje[clickedIndexes[u].index].ALAN + "]" + "=" + "'" + clickedIndexes[u].value + "'";
}
field = selectString;
i++;
});
});
},

IE: jQuery.show() only shows element when using alert() before/after show

I'm trying to add a simple 'wait box' on a javascript function, like this:
function caricaElenco(indice) {
(...)
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
(...)
$("[id*=Wait1_WaitBox]").hide();
}
And it's working good on Firefox, but not on Internet Explorer 11, that's not showing it. The HTML is:
<div id="ctl00_Wait1_WaitBox" class="updateProgress">
Attendere...<br />
<img src="../Images/wait.gif" align="middle" />
</div>
The weirdest thing is that I try this, for a simple check:
function caricaElenco(indice) {
(...)
alert($("[id*=Wait1_WaitBox]").css('display'))
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
alert($("[id*=Wait1_WaitBox]").css('display'))
(...)
$("[id*=Wait1_WaitBox]").hide();
}
And it's working, I mean that it's showing the alert with 'none' and after 'block'... And it's showing the box too! But not without the alert... Why?
UPDATE:
Tried with [id*="Wait1_WaitBox"], but it's the same. jQuery version is 1.8.2.
With
it's working only with the alert
I mean that if I do:
function caricaElenco(indice) {
(...)
alert('whatever');
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
alert('whatever');
(...)
$("[id*=Wait1_WaitBox]").hide();
}
It's showing the box, but if I do:
function caricaElenco(indice) {
(...)
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
(...)
$("[id*=Wait1_WaitBox]").hide();
}
It's not working (I mean not showing the 'wait box', but doing all the other stuff the function has to do in (...) correctly—load a gridview with an AJAX call) on Internet Explorer 11, in Firefox are both working. No JavaScript error.
UPDATE 2:
Almost entire javascript function:
// Fill part of gridView
function loadList(index) {
index = parseInt(index);
buffer = 100; // Number of rows to load
$("[id*=divGrid]").unbind('scroll');
$('[id*="Wait1_WaitBox"]').show(); // Show loading 'wheel'
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PageName.aspx/webMethodName",
data: '{id:' + $("[id*=hdnID]").val() + ', index:' + index + '}',
dataType: "json",
async: false,
success: function (response) {
if (index == 0) {
(...)
$("[id*=grid] tr:last-child").remove();
var row = "<tr class='" + response.d[index].State + "'>";
row += "<td class="Column1"></td>";
(...)
row += "<td class="DateColumn"></td>";
(...)
row += "<td class='columnN'></td></tr>";
$("[id*=grid]").append(row);
}
row = $("[id*=grid] tr:last-child").clone(true);
$("[id*=grid] tr:last-child").remove();
if (index <= response.d.length) {
if (index + buffer > response.d.length)
var stop = response.d.length;
else
var stop = index + buffer;
(...)
for (var i = index; i < stop; i++) {
var j = 0;
(...)
$("td", row).eq(j).html("<span id='lblCodeNumber" + i + "' >" + response.d[i].CodeNumber + "</span>"); j++;
(...)
var effectDate = new Date(parseInt(response.d[i].effectDate.substr(6)));
$("td", row).eq(j).html(effectDate.getDate() + '/' + (effectDate.getMonth() + 1) + '/' + effectDate.getFullYear()); j++;
}
(...)
var toBeCounted = "";
var checked = "";
if (response.d[i].ToBeCounted != null)
toBeCounted = response.d[i].ToBeCounted .toString();
else
toBeCounted = "true";
if (toBeCounted == "true")
checked = "checked = 'checked'";
else
checked = "";
var rdToBeCounted = "<span><input type='radio' class='radio' " + checked + " name='ToBeCounted" + i + "' value='s' id='sToBeCounted" + i + "' />";
rdToBeCounted += "<label for='s" + i + "'>YES</label>";
if (toBeCounted == "false")
checked = "checked = 'checked'";
else
checked = "";
toBeCounted += "<input type='radio' class='radio' " + checked + " name='ToBeCounted" + i + "' value='n' id='nToBeCounted" + i + "' />";
rdToBeCounted += "<label for='n" + i + "'>NO</label></span>";
$("td", row).eq(j).html(rdToBeCounted);
$("[id*=grid]").append(riga);
(...)
riga = $("[id*=grid] tr:last-child").clone(true);
}
if (stop < response.d.length) {
$("[id*=divGrid]").scroll(function (e) {
if (element_in_scroll(".congruenti tbody tr:last")) {
loadList($(".congruenti tbody tr:last td:last").html());
};
});
}
$('[id*="Wait1_WaitBox"]').hide();
}
},
error: function (result) {
alert("Error! " + result.status + " - " + result.statusText);
}
});
}
At the end you seem to be hiding it again $("[id*=Wait1_WaitBox]").hide();.
You need to show what goes in between these two lines.
It works with alert because the execution of the script is frozen until you close the alert (and that final line is not executed yet).

Call saveCell on jqGrid blur

I've made a custom radio button element for jqGrid, and it works fine, but I'm not able to call saveCell method when I click outside the grid.
HTML Code:
{ name : 'radioelement',
index : '1',
editable : true,
edittype: "custom",
editoptions : {custom_element: yesNoRadioElem, custom_value: yesNoRadioValue}
},
Javascript Code:
function yesNoRadioElem(value, options){
var result = "";
var radioName = "radio_"+options.name;
if(value == null){
value = false;
}
result += "<div><label>" + $.pf.locale.yesNoRadioTrue + "</label><input type='radio' name='" + radioName + "' value='True' ";
if (value==="True"){
result += " checked ";
}
result += "/></div>";
result += "<div><label>" + $.pf.locale.yesNoRadioFalse + "</label><input type='radio' name='" + radioName + "' value='False' ";
if (value==="False"){
result += " checked ";
}
result += "/></div>";
return result;
}
function yesNoRadioValue(elem, operation, value){
if (operation === 'get') {
var result = $(elem).find("input:checked");
if (result.length > 0){
return result.val();
}
else{
return "";
}
} else if (operation === 'set') {
if ($(elem).is(':checked') === false) {
$(elem).filter('[value=' + value + ']').attr('checked', true);
}
}
}
Is there any way to set up this new element to call saveCell() when I click outside the grid? It's only called when I click on another row.

Why can't I replace the URL of these incoming JSON'd images?

So I've got this JS code that pulls JSON from a php file. That works. What I'm trying to do is change JSON values before they're put into the DOM to replace image URLs with lower-res images. You'll see the beginning of this in the IF statement calling the mobile() function
Here we go:
$.post(url, project, function(data, textStatus) {
$(data.tags).each(function(i, item){
projectTags += "<span class='project-tag'>"+item+"</span>";
});
$(data.slides).each(function(i, item){
if ((mobile() == true && $(window).width() <= 680)){
if (i != 0){
console.log('Before' +item);
var newItem = JSON.stringify(item);
$(newItem).replace('.png','-lofi.png');
console.log(newItem);
console.log('After' + item);
}
}
projectImages += "<div class=\"slide-container\">" + item + "</div>";
console.log(projectImages);
});
setTimeout(function(){
btnAbout.removeClass('active');
sectionDetail
.attr('data-id', data.id)
.find('.project-name').html(data.name).end()
.find('.project-year').html(data.year).end()
.find('.project-agency').html(data.agency).end()
.find('.project-details').html(data.details).end()
.find('.project-tags').html(projectTags).end()
.find('#slideshow').html(projectImages);
}, "json");
What gives? ALL I want to do is replace the URL of JSON value if it's a mobile device smaller than an iPad.
EDIT: Fixed by James! Thanks buddy! FINAL CODE BELOW.
$.post(url, project, function(data, textStatus) {
$(data.tags).each(function(i, item){
projectTags += "<span class='project-tag'>"+item+"</span>";
});
$(data.slides).each(function(i, item){
var loFi = JSON.stringify(item);
if ((mobile() == true && $(window).width() <= 680)){
if (i != 0){
loFi = loFi.replace(/(.png)/g,'-lofi.png')
loFi = $.parseJSON(loFi);
item = loFi;
}
}
projectImages += "<div class=\"slide-container\">" + item + "</div>";
});
setTimeout(function(){
btnAbout.removeClass('active');
sectionDetail
.attr('data-id', data.id)
.find('.project-name').html(data.name).end()
.find('.project-year').html(data.year).end()
.find('.project-agency').html(data.agency).end()
.find('.project-details').html(data.details).end()
.find('.project-tags').html(projectTags).end()
.find('#slideshow').html(projectImages);
}, "json");
Should be:
var newItem = JSON.stringify(item);
newItem = newItem.replace('.png','-lofi.png');
You're forgetting to assign the result of 'replace' to your variable and you don't need to wrap newItem in $(..), replace is a String object function.
PS. You probably don't need to stringify either. Isn't your item already a String?
$(data.slides).each(function(i, item){
var newItem = JSON.stringify(item); <-- Add this early
if ((mobile() == true && $(window).width() <= 680)){
if (i != 0){
console.log('Before' +item);
newItem = newItem.replace(/(.png)/g,'-lofi.png');
console.log(newItem);
console.log('After' + item);
}
}
You are still adding the regular item here? any changes you made to item are not reflected.
projectImages += "<div class=\"slide-container\">" + item + "</div>";
change to
projectImages += "<div class=\"slide-container\">" + newItem + "</div>";

Categories