Onclick event on button firing twice for one user only? - javascript

Apologies if the title seemed a bit vague, but I am at a complete loss as to why this may be happening now.
I have an online application that has been used for more than 2 years by a team of people, and we had a new starter about 6 months ago who when using the application, approx once a month, an event fires twice for this one user, and no other person.
It is a very basic onclick event the fires to controller, that updates a DB, I have tried to replicate the issue but am unable to on anyone else's machine.
<button class="btn btn-primary" type="button" onclick="advanceJob()">Advance Job</button>
function advanceJob() {
var details = {
Id: selectedJob,
MovedOnBy: '#ViewBag.DisplayName',
Frequency: $('#jobFrequency').val()
}
$.ajax({
type: 'POST',
url: '/Home/MoveJobOn',
cache: false,
data: details,
success: function (data) {
$('#jobModal').modal('hide');
alert(data);
},
error: function (x, y, z) {
alert(x.responseText + " " + y.responseText + " " + z.responseText);
}
}
});
I can only think it may be something specific to that persons machine, but have never encountered this before with any other of my applications.

Try to test this event using different browsers, if they all click twice, perhaps the issue is the Mouse is broken, try to replace the new Mouse.
Besides, you could also refer to the following code to disable the button after fist click the button.
<button class="btn btn-primary" type="button" onclick="advanceJob(this)">Advance Job</button>
<span id="output"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var count = 0;
function advanceJob(e) {
$(e).attr("disabled", true);
//after 3 seconds, enable the button.
setTimeout(function () {
$(e).removeAttr("disabled");
}, 3000);
count++;
$("#output").html(count.toString());
////other actions
//var details = {
// Id: selectedJob,
// MovedOnBy: '#ViewBag.DisplayName',
// Frequency: $('#jobFrequency').val()
//}
//$.ajax({
// type: 'POST',
// url: '/Home/MoveJobOn',
// cache: false,
// data: details,
// success: function (data) {
// $('#jobModal').modal('hide');
// alert(data);
// },
// error: function (x, y, z) {
// alert(x.responseText + " " + y.responseText + " " + z.responseText);
// }
//}
};
</script>
Also you could refer to this article to prevent multiple click the button.

Related

Ajax call in google spreadsheet (POST)

I have a button which calculates the time (in millisecond) between two button clicks
function stopButton() {
if (startTime) {
var endTime = Date.now();
var difference = endTime - startTime;
alert("Reaction time: " + difference + " ms");
startTime = null;
}
}
I want to store this value inside google sheet as soon as the click is triggered Here, i am using ajax
$(document).ready(function () {
$("#yes").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "https://script.google.com/macros/s/<somecode>/exec",
success: function (result) {
alert("ok");
},
error: function (result) {
alert("error");
},
});
});
});
<button id="yes" class="action-btn" name="yes">
<i class="fa fa-yes">Yes</i>
</button>
I want to store the value which calculates the time between two button click inside google spreadsheet. Is there any way to do that. I am very new to javascript. Any kind of help would be greatly appreciated.
Thank you

How to redraw jQuery DataTable after link is clicked without navigating from page?

I have a column in my jQuery datatable that renders a green checkmark link if data == true or a red X if data == false:
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '#Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '';
}
return '';
}
},
The problem is that when I click one of the links (either green checkmark or red X), it navigates to another page. I know that this is because I am using href and Url.Action.
When a user clicks one of the links, I want to call the /Payment/Set method to update the data (green checkmark to red X and vice versa) and then I want to redraw my datatable (i.e. dataTable.draw()) without navigating from the current page (i.e. Index view). /Payment/Set method updates the data without returning anything (i.e. void).
Update: I tried the following and it almost works, meaning that when I click one of the links, the data is updated and the datatable is refreshed, except it still tries to navigate to another page.
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '#Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '';
}
return '';
}
},
<script>
function onclickFunction() {
$.ajax({
type: "GET",
url: $(this).attr("href"),
success: function () {
paymentDataTable.ajax.reload();
}
});
}
</script>
If you use an anchor <a> it is obvious that the browser will navigate to another page. That's the actual purpose of the anchor tag.
You should use an AJAX function to call when your button is pressed and at the callback call the reload of the table.
This can be a way:
{
data: "HasPayment",
render: function (data, type, row) {
if (data) {
return '<button class="fas fa-solid fa-check" style="color: green" onclick="setPayment(row.Id, row.Year, row.Month, data)"></button>';
}
return '<button class="fas fa-solid fa-times" style="color: red" onclick="doSomethingElseMaybe()"></button>';
}
}
Then you should create two more functions, one with the AJAX call and one with the table reload to be called as callback.
function setPayment(id, month, year, data){
var url = `Payment/Set?applicationId=${id}&year=${year}&month=${month}&hasPayment=${data}`;
$.ajax({
type: "POST", //OR GET? it depends on your backend
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
reloadTable();
},
error: () => {
console.error("500 Internal Server Error.");}
});
}
Then in the reloadTable function just call the ajax.reload() method of the DataTable api.
for example
function reloadTable(){
datatable.ajax.reload();
}
Here is the documentation of DataTables reload method.
Here is the documentation of JQuery AJAX.
You may have to adapt the example code to your specific backend purpose.

Large amount of events loaded on the angularjs-bootstrap-calendar

I'm pulling in ALL my event data from my server and since I have a lot of events to pull, the angular-bootstrap-calendar takes a lot of time to load.
I was wondering if its possible to pull only a month's worth of data for the current view I'm in (month, week, day..I would hide the year view). As I change the view to the next month, I'd pull the data for that month only.
Right now, I pull ALL the data only once, when the calendar loads, but not sure how to pull the data when the view changes.
var urlapievents = $location.protocol() + "://" + $location.host() + "/api/events/" ;
$http.get(urlapievents).success(function(events) {
Good solution for me
Get year and month of view, send it to API, and only retrieve events for that year-month:
js
vm.viewChangeClicked = function() {
var viewDateYearMonth = moment(vm.viewDate).format('YYYY-MM');
var urlapieventsall = $location.protocol() + "://" + $location.host() + "/api/events/" + viewDateYearMonth ;
$http.get(urlapieventsall).success(function(events) {
vm.events = events.events;
});
};
html
<div class="col-md-6 text-center">
<div class="btn-group">
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'month'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Month</label>
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'week'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Week</label>
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'day'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Day</label>
</div>
</div>
I've also added logic to check if previous yyyy-mm is equal to current yyyy-mm to save some unnecessary calls to the API.
If you grab your events as a json feed, you can use additional options - startParam and endParam. They can be used like this:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
if (request) {
request.abort();
};
$.mobile.loading('show');
request = $.ajax({
type: "POST",
url: "../Services/Calendar/CalendarService.asmx/GetEvents",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ dtStart: " + JSON.stringify(start) + ", dtEnd: " + JSON.stringify(end) + "}",
success: function(data) {
var events1 = [];
$(data.d).each(function() {
events1.push({
title: this.Title,
start: this.Start,
end: this.End,
id: this.Id
});
});
callback(events1);
$.mobile.loading('hide');
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.statusText == 'abort') {
$.mobile.loading('hide');
return;
} else {
alert('There was an error');
$.mobile.loading('hide');
}
}
});
}
});
You can read more about those parameters here: https://fullcalendar.io/docs/event_data/events_json_feed/
The functionality you describe is a sort of date pagination, although this functionality isn't built in (shame, because it sounds really useful), you can implement your own with some small amount of work
First, the datepicker stores a JS Date object inside the ng-model, you can $watch it and get the current year/month/day out of it
$scope.modelDate = new Date()
...
$scope.$watch('modelDate', function(newDate, oldDate) {
newDate.getDay(); // 5
newDate.getMonth(); // 11
newDate.getYear(); // 116
})
Now you can query your database to get all the event for your selected month
Also, you can utilize the datepicker's mode (showing wether you are viewing the datepicker in the day/month/year mode, you set it up inside the options object).
datepickerMode C (Default: day) - Current mode of the datepicker (day|month|year). Can be used to initialize the datepicker in a specific mode.
Using this property you can query a month, year or years of events.

Unable to change href value with JQuery

I am aware that this question has been asked before and I had the solution working last week based on the responses in the answers provided, nothing has changed and all of a sudden the jquery has stopped working.
I am using an Ajax call (below) that returns me a string that I assign to a hidden link on a page to force the download of a file from my works LAN.
$(document).ready(function () {
$(".excelLoader").hide();
$('.extract')
.on('click',
function () {
var rh = Number($(this.id).selector);
console.log("clicked: " + rh);
var loader = "load_" + rh;
var excel = "excel_" + rh;
console.log(loader);
$("." + excel).hide();
$("." + loader).show();
var params = {
responseHeaderId: rh
}
$.ajax({
type: "POST",
url: "SubmissionTracker.aspx/ExportFile",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#hiddenLink").attr("href", data.d);
console.log($("#hiddenLink").val());
$("#hiddenLink").click();
$("." + excel).show();
$("." + loader).hide();
},
error: function (data) {
console.log("error :" + data);
console.log(data);
$("." + excel).show();
$("." + loader).hide();
}
});
});
})
the issue that I have now is that the href is not being set, so the click event fires but with nothing to fetch.
The line I believe to be the issue is $("#hiddenLink").attr("href", data.d);
the line it is trying work with in my ASP.Net Webforms page is <a id="hiddenLink" href=""></a>.
I have cleared my Cache, removed any temporary files that may have existed but still cannot reproduce the positive results I had last week.
Any and all help bery much appreciated.
-----------update----------------
issue appears to be on the click event of the link. JQuery that I am usering is version jquery-1.11.3.js which is referenced first, and the js file where this is referenced is in the middle of all the other referenced files.

jQuery object reference issue

function startCampaign(index, campaign_id) {
var btn = $('#toggleStateBtn' + index);
btn.html('<i class="icofont-pause"></i>');
btn.removeClass('btn-success');
btn.addClass('btn-warning');
btn.attr('title', 'Pause this campaign');
btn.width('9px');
// Start campaign
$.ajax({
url: '/campaign/startCampaign/' + campaign_id,
type: 'POST',
success: function(data){
// Reflect the new state in status column
btn.html(data);
}
});
}
function pauseCampaign(index, campaign_id) {
var btn = $('#toggleStateBtn' + index);
btn.html('<i class="icofont-play"></i>');
btn.removeClass('btn-warning');
btn.addClass('btn-success');
btn.attr('title', 'Run this campaign');
btn.width('9px');
// Pause campaign
$.ajax({
url: '/campaign/pauseCampaign/' + campaign_id,
type: 'POST',
success: function(data){
// Reflect the new state in status column
btn.html(data);
}
});
}
For some reason this is causing strange behaviour. If you replace btn with $('#toggleStateBtn' + index) in all places then everything works fine.
My guess is, if for instance you first call startCampaign() and then called pauseCampaign() the old btn reference gets changed to the new one. But I'm not sure.
Ideas?
Nevermind I am an idiot, the btn in btn.html(data) is actually a different control. I was mindlessly substituting. Looks like I need an extra dose of caffeine this morning.

Categories

Resources