I ended up using the following script in order to auto-submit forms to my server after 60 seconds. However, for some reason the forms are reporting an error.
</style>
<script>
var counter{{num}} = {{seconds}};
var interval = setInterval(function() {
counter{{num}}--;
// Display 'counter' wherever you want to display it.
document.getElementById("counter{{num}}").innerHTML = "Timer:"+counter{{num}}
if (counter{{num}} == 0) {
// Submit form
test.submit('timeout');
}
}, 1000);
</script>
<p id="counter{{num}}" style="text-align: right;">COUNTER</p>
The script looks a little funny because there is this `{{num}}' value. This is basically replaced by a different number using server side scripting each time the form is called so that multiple functions are not generated simultaneously which force the timer to zero twice or three times faster than before.
Sorry if this is unclear. I tried every solution to auto-submit this form but I think there were server side conflicts with my javascript. This is all pretty new to me.
Thanks for any help you can provide!
Related
I am quite the beginner in programming with web applications. My goal is to receive data from realtime firebase database.
So I have this code to read from realtime firebase application. When I do this I can actually see the output. My problem is that if I change a value in the input-box and submit again without reloading page, the javascript will not run the new input value.
For the console output in internet:
The problem is here, if I change value to "1" in input box without refreshing page, my program won't take that input and do stuff with it. Check below:
It's suppose to return a value of 0 and where i marked with circle it should say "1". If i refresh page and then put in 1 into input box, it works fine. But if I change back to 2 without refreshing. same problem.
I just want to do the same without user having to refresh page eveyrtime they type in new data.
Hope someone out there can help :) I watched so many tutorials for reading from database and I can't figure out what to do here.
You can use oninput JS event to capture a value when it is changed
var standNr = document.getElementById("standNr");
standNr.oninput = function() {
console.log(standNr.value);
}
<input type="text" id="standNr"/>
defineStand.addEventListener('submit', (e) => {
var stand_number = document.getElementById("standnr").value
var dbRef = database.ref('stand/' + stand_number + '/status')
e.preventDefault()
dbRef.on('value', function(snapshot) {
console.log(snapshot.val())
})
console.log(stand_number)
console.log(dbRef)
})
I solved it now. Works perfectly :D
My issue was that e.preventDefault wasn't placed after definings the variables :)
I’m making a html & Javascript game and I’m currently trying to write some code that will show the player’s gold balance on the screen and make it decrement by 1 every time the player clicks on a Javascript object (this object is placed in a div on the html page).
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a <div> but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
I don’t want the figure to decrement below 0. Instead, whenever it reaches 0 I want to initiate a Javascript modal to inform the player that they’ve run out of coins.
~~
Originally I was trying to use websockets to display the player’s balance on screen, but I found it very confusing (I’m a beginner at programming in general), so I’m now trying to load the balance on page load, then post the updated balance amount back to my database using AJAX every 60 seconds, or whenever the user closes the browser window, refreshes the page or navigates away from the page. I don’t know if it’s possible to do all these things, or where to start, maybe this is a really bad way to go about this and maybe it's not scalable (maybe the database wouldn't support constant updates from 1000s of players by using this method)?
I would really appreciate any advice or help anyone could give me on any of this.
Thanks in advance!
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
Here are two divs: you store the total number of coins in one and you click the second one to lose coins
<div id="coins">10</div>
<div onCLick="javascript:loseCoin()">If you click here it will cost you 1 coin</div>
Using a function to decrement the cost.
function loseCoin(){
var coins = getElementByid("coins");
var coins_nr = parseInt(coins.innerHTML,10);
if( coins_nr> 0 ){
coins.innerHTML = coins_nr - 1;
} else {
showModal();
}
}
Where showModal() will be your modal (ask if you don't know how to make it)
As for updating the database every 60 sec, you would need a timer loop such as:
setInterval(function () {
// get number of coins from your div's innerHTML
// then call your ajax controller to update DB
}, 60000);
An example of ajax using javascript:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE ) {
if(xhr.status == 200){
console.log(xhr.responseText);
} else {
console.log('something else other than 200 was returned');
}
}
}
xhr.open("POST", "url_of_your_controller_here", true);
xhr.send("coins="+ coins_nr);
(maybe the database wouldn't support constant updates from 1000s of
players by using this method)?
Any decent server should have no problem handling 1000 requests every 60 sec, but it may depend on how many other requests it has and the complexity of your requests.
If you are just trying to decrement a visible counter in the window on each click, you can do something like this:
HTML:
<div id="coinsRemaining">20</div>
code:
// use whatever click handler is appropriate to your app
document.addEventListener("click", function(e) {
var elem = document.getElementById("coinsRemaining");
// get current display text and convert to number
var cnt = +elem.textContent;
--cnt;
if (cnt >= 0) {
elem.textContent = cnt;
}
if (cnt <= 0) {
alert("There are no more coins");
}
});
Working demo: http://jsfiddle.net/jfriend00/s9jb6uhf/
It seems like you don't need to update the database on every click unless there's some realtime aspect of your coin balance that affects other users. If you're just keeping track of your coin balance for future web page visits, then you could update the database much less often than every click.
I will put this post into paragraphs to make it easier reffering to specific content.
I have made a simple button in html that plusses a number with 1 everytime the button is pressed. This function is made in Javascript. This number has to be put into the database every 20 seconds.
Since Javascript is running on the client side, every visiter will be able to change the current number of times the button is pressed, and that "fake" number will then be sent to the database after 20 seconds.
The user should not be able to change this number, because it's considered cheating.
I could use other languages to complete this like java, flash etc. but I need to make it working with Javascript/Jquery that runs on the client side. The reason for this is that it will take too hard on the server if there is sent a request to the server everytime to button is pressed.
I hope you understand all 4 steps, if not please let me know which step I shall deepen.
Question: How can I make a secure way of processing a number from the client-side to the database without the user being able to change that number on their computer? If I can't, any other suggestions?
Thanks in advance.
First of all, your counter should be on your server. Don't let the client side tell you how many times the button has been pressed - store this yourself on the server (where no one can reach).
This will mean that you'll have to notify the server every time the user clicks the button. Furthermore, you'll need to make sure that each "click" is valid. You could do this by attaching a unique key to each of the buttons clicks. As soon as the user clicks the button, this key will be sent to the sever and validated. If it is valid, the server will return a new key to be sent when the button is next clicked.
You should be aware that it is very VERY easy to write a short jQuery script to manipulate clicks on DOM elements though. A command as simple as
setInterval(function(){
$('button').trigger('click');
},500);
Would trigger a click event on the button every 500 milliseconds (0.5 seconds).
Code that runs in JavaScript can't practically be protected against "cheating". Your best bet might be data hiding:
var myobj = (function() {
var i = 0;
return {
function setI(newvalue) {
// do checks here
if (true) {
i = newvalue;
}
},
function sendI() {
// send value of i
}
}
}());
myobj.setI(123);
myobj.sendI();
myobj.i // undefined
Moving the logic that prevents data tampering to the server is better though.
Hope you can assist.
I am currently trying to conduct one of the most simplest tasks via a user event script - that is to set a new value in the 'discount rate' field on the sales order. My script works fine when testing it on the client, but when the scheduled script is triggered, the field fails to set/update.
The following code is within a 'beforesubmit' operation. Can you spot what I have done wrong?
function beforeSubmit_discountVAT(type){
if(nlapiGetContext().getExecutionContext() !='scheduled')
return;
var getDiscountVal = nlapiGetFieldValue('discountrate');
var correctDiscount = getDiscountVal / 1.2;
nlapiSetFieldValue('discountrate', correctDiscount);
}
In short - All i want to do is deduct the discount value by 20%. Can you use 'nlapiSetFieldValue' when a user event script is triggered from a scheduled script?
Thanks in advance.
AWB
When editing an existing record, nlapiSetFieldValue cannot be used in a Before Load event on fields that are stored with the record. From the function's JSDocs:
Sets the value of a given body field. This API can be used in user event beforeLoad scripts to initialize field on new records or non-stored fields.
nlapiSetFieldValue can thus only be used reliably in Before Load on new records or non-stored fields.
Realizing this is a month old so you've probably found a solution, I would move your code to the Before Submit event. I tested this using a Scheduled Script:
var customer = nlapiLoadRecord('customer', '31294');
nlapiSubmitRecord(customer);
and User Event on the Customer record, Before Submit event:
if (nlapiGetContext().getExecutionContext() === 'scheduled') {
nlapiSetFieldValue('url', 'http://www.google.com/', false);
}
This works as expected for me in a 2013.1 Sandbox environment.
Using nlapiSubmitField in After Submit as mentioned in the other answer is an unnecessarily long operation that will use extra governance units. Not a huge deal if that's the only thing your script is doing, but if you ever expand the script or add looping, it can add up quickly in terms of performance and governance usage.
Also, it may not be necessary, but you should ensure that getDiscountVal is a Number by doing:
var getDiscountVal = parseInt(nlapiGetFieldValue('discountrate'), 10);
If it comes back as a String then your division operation may give a strange result which may also cause nlapiSetFieldValue to fail or set the field to an odd value.
two suggestions
Make sure that your script is being executed by adding a few nlapiLogExecution statements
Instead of doing it in beforesubmit, change this field in aftersubmit function using nlapiSubmitField
"Can you use 'nlapiSetFieldValue' when a user event script is triggered from a scheduled script?"
Yeah Absolutely yes.Context is also correct its scheduled.
Please make sure that you are submitting the record nlapiSubmitRecord(recordObj) at the end.
If you are not comfortable with nlapiSubmitRecord() you can obviously use nlapiSubmitField()
If still you get stuck up then please paste the complete code so that we could assist you.
Cheers!!!
I have a html page with 2 buttons on it and a big javascript function that is executed every 10 ms. Each click on each button executes a javascript function that changes some variables used by the big javascript function and change its behaviour. In time the code got very complex and time consuming and I would like to move the entire calculation of variables over to the server side. Or, better yet I would like to generate the entire function on the server.
How can I dynamically change the big javascript function when any of the 2 buttons is being pressed?
What you could do is once the button is pressed you make an Ajax request to the server side. There you generate the javascript code based on the button pressed and send it back. You can then eval the response and execute the appropriate function.
Grabbing a large script and executing it every 10 ms is bound to be slow.
Modifying a large script isn't that bad and then you only care about the execution plan of the script. (It doesn't matter how fast the server can generate the script the client will execute if you're sending it every 10 ms and it's super complicated. Client execution is going to cause the client to creep if not properly made.)
However have you considered just "fixing" your script so that it's a bit more compartmentalized. Surely the entirety of the function does not change every 10 ms? (On your site does it change from being a game of Pong to a looping weather radar graphic every 10 ms?)
compartimentalized javascript example (using jquery): Assumes you have two tags one with the class buttonA and one with the class buttonB. Clicking buttonA or buttonB changes internal values and then the script is executed.
var complicatedFunction = function(){
//private variables and methods
var a = 2, b = 3;
//public variables and methods
return {
exec: function(el){
//which button was pushed?
if($(el).is('.buttonA')){
a = 4;
b = 8;
} else {
a = 10;
b = 2;
}
alert('The result of a*b is ' +(a*b));
}
}
}();
$('.buttonA, .buttonB').click(function(){complicatedFunction.exec(this)});
Wish I could help more, if you post a code example maybe we can!