Ajax call in google spreadsheet (POST) - javascript

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

Related

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.

Onclick event on button firing twice for one user only?

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.

my ajax post request is called twice

I have some javascript code in my wordpress site that post an ajax request to a php file and then the file generates a pdf with a quote.
It all works, but I don't understand why the second time I submit the request (to create the second quote, basically), the ajax request then is called twice?
the first time is correct, and it's called one time.
from the second time, it's always called twice.
here's the code:
$('#add-to-cart-quote-email-button').on('click', function() {
var statusIcon;
statusIcon = $('#quote-send-spinner');
$('.send-quote-from-cart-page-container').slideToggle();
statusIcon.removeClass('fa fa-check');
statusIcon.removeClass('fa fa-times');
$('#cart-quote-email-send-button').on('click', function(e) {
var data, email, name, quote_type, role;
e.preventDefault();
name = $('.send-quote-from-cart-page-container #name');
email = $('.send-quote-from-cart-page-container #email-address');
role = $('.send-quote-from-cart-page-container #user-role').val();
quote_type = $('.send-quote-from-cart-page-container #quote-type').val();
if (!name.val()) {
console.log("empty name");
name.addClass('invalid');
return;
} else {
if (name.hasClass('invalid')) {
name.removeClass('invalid');
}
}
if (!validateEmail(email.val())) {
console.log("invalid email");
email.addClass('invalid');
return;
} else {
if (email.hasClass('invalid')) {
email.removeClass('invalid');
}
}
console.log("sent! to email " + (email.val()) + " and name " + (name.val()));
data = {
name: name.val(),
email: email.val(),
role: role,
quote_type: quote_type
};
statusIcon.addClass('fa fa-spinner fa-spin fa-fw');
$.ajax({
type: 'post',
dataType: 'json',
url: '/wp-admin/admin-ajax.php',
data: 'cxecrt-success-get-link-url=&cxecrt-saved-cart-name=&cxecrt-landing-page=cart&action=save_cart_and_get_link_ajax',
success: function(response) {
data.cartURL = response.cart_url;
return $.ajax({
method: 'POST',
url: '/wp-content/themes/theme/generate_pdf_quotes/emailQuote.php',
data: data,
success: function() {
console.log("success!");
statusIcon.removeClass('fa fa-spinner fa-spin fa-fw');
statusIcon.addClass('fa fa-check');
return setTimeout(function() {
return $('.send-quote-from-cart-page-container').slideToggle();
}, 2000);
},
fail: function() {
console.log("fail");
statusIcon.removeClass('fa fa-spinner fa-spin fa-fw');
return statusIcon.addClass('fa fa-times');
}
});
}
});
});
});
return;
I need to call the second ajax on success of the first one, as they do two completely different things and the first one is required by the second one, that it's meant to be like that and it's not (i believe) the cause of this issue
I inspected the code but I couldn't see anything wrong in here.
Any thoughts?
thanks
You are defining an eventHandler within the first eventHandler.
On line 1:
$('#add-to-cart-quote-email-button').on('click', function() {
On line 7:
$('#cart-quote-email-send-button').on('click', function(e) {
That's why the second time it is clicked, it calls twice. I bet if you click it a third time it calls 3x ;-)

Using Jquery/SetTimeout to Update Div - Update Not Working

What I am Trying to Do:
I am trying to use settimeout to loop/run after a function is called to automatically update/refresh a div.
What Isn't Working:
To be clear settimeout is working, but the div is not automatically refreshing/updating when I enter new test data into the db. In other words, If I refresh the page, I see the new test data, but not if I let the update function run.
Code:
function update(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
console.log("Queried Database...");
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#login-box").hide();
//$("#trades").html(' ');
localStorage.setItem("wings_lastsignal", v.candel);
var lastsignal = localStorage.getItem("wings_lastsignal");
console.log(v.candel);
if(lastsignal == v.candel) {
console.log("No New Signals");
localStorage.getItem("wings_currentsignals");
if(v.signal == 'Buy') {
console.log("Current Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
} else {
console.log("Current Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
}
} else {
playChing();
console.log("New Signal");
if(v.signal == 'Buy') {
console.log("Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
} else {
console.log("Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
}
}
});
}
//alert(response);
//console.log(response);
}
}).then(function() { // on completion, restart
var a = localStorage.getItem("wingsaccnum");
//setTimeout(update, 10000);
setTimeout(function(){ update(a) }, 20000); // function refers to itself
console.log("Timeout");
});
}
This function is called when I a button is pressed, using this Jquery snippet:
$( "#rbuttonon" ).click(function() {
var acc = localStorage.getItem("wingsaccnum");
//refresh_box();
update(acc);
console.log('Interval set');
});
Other Notes:
To be clear, I don't mind if there is a way to always make sure this div is updated every xx amount of time, without the need to press any buttons. I believe the problem is in my code's logic, but I would greatly appreciate some assistance!

Repeat the function for every 1 min?

i am calling a function with parameters from onclick method what i want to do is i want this function to repeat every 1 min here is html code:
I am calling a function on everyclick with some parameter as id
The id fetches the the lat longs,and it is plotted in map ,i have done everything working except that i get the data keep recieving from the back end so what i want to do is , as i have clicked the href i want that particular id to be sent and keep recieve the data of that particular id only and when i click the second the first should be stopped and start the another .
<html>
</head>
<body>
</body>
</html>
javascript:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
Try this...
Use setInterval to call function every 1 minute and "trigger" function to click automatically when call function "test"
<html>
</head>
<body>
sdsd
sdsd
</body>
</html>
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
function test() {
$(".todo").trigger("click");
}
var refreshId = setInterval(test, 60000);
You can simply call a setInterval inside your todo function and it will fire with different calls, change your function like this:
function todo(id) {
setInterval(function() {
/*$.ajax({
type: "GET",
url: "example?value=" + id,
dataType: "text",
success: function(data) {
//parsing;
});*/
console.log(id);
}, 1000);
}
link1
link2
I used only 1000 milliseconds for test here, you only have to change it to 60000 to fit your needs, you can see the results in the console..
Note:
Keep in mind that for each click you will fire a new setInterval() so you have to disable click events after the first setInterval() to avoid this problem.
It is not clear as to what constraints you may require from your question and comments, but perhaps something like this?
Repeat will be stopped if there is an ajax error.
Clicking a button will cancel the current repeat and immediately start the new repeat (1-4). Requests in progress are not cancelled and there is no checking included to ignore processing them upon complete.
A stop button is included, this will stop the repeat but not the request in progress.
The requests are async and no effort has been made to make sure that they are processed in order of request.
This is a very basic example that starts you moving in the right direction.
var pre = document.getElementById('out'),
interval = 5,
running = false,
fetching = false,
timerId;
function stop() {
clearInterval(timerId);
running = false;
}
function todo(id) {
fetching = true;
$.ajax({
type: 'GET',
url: 'http://jsonplaceholder.typicode.com/albums?id=' + id,
dataType: 'jsonp',
error: function (qXHR, textStatus, errorThrown) {
pre.textContent += id + ': ' + textStatus + '\n';
stop();
},
success: function (data) {
pre.textContent += id + ': ' + data[0].title + '\n';
},
complete: function () {
fetching = false;
}
});
}
function start(id) {
if (running) {
stop();
}
running = true;
if (!fetching) {
todo(id);
}
timerId = setInterval(function () {
if (!fetching) {
todo(id);
}
}, interval * 1000);
}
document.body.addEventListener('click', function (evt) {
var target = evt.target;
if (target.classList.contains('album')) {
start(target.value);
}
}, false);
document.getElementById('stop').addEventListener('click', function () {
stop();
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="album" value="1">1</button>
<button class="album" value="2">2</button>
<button class="album" value="3">3</button>
<button class="album" value="4">4</button>
<button id="stop">stop</button>
<pre id="out"></pre>
You can use setTimeout of javascript.
It will repeat given function in specified time interval.
Javascript setTimeout function repeat
OR
setInterval( function(){ todo(id);}, 60000);
Make use of setTimeout to call the function again:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
setTimeout(function(){todo(id)}, 60000);
}
And if you also want to clear timeout on some condition:
var timer;
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
timer = setTimeout(function(){todo(id)}, 60000);
if(//Your condition){
window.clearTimeout(timer);
}
}

Categories

Resources