Adding a loading gif when submitting form? - javascript

While my code calculates, Id like the submit button to go from the "RUN" that it is now to the loading gif that I have. Now when I click the RUN button, I also need a certain script to run which calculates all sorts of data and returns it back to the page. I wrote a function that holds the other two function and calls them in sequence. I even added a 3rd function that would revert back the submit button but I can't seem to figure this out.
The website is www.fsaesim.com/simulation.html which would be much easier to see the code, however attached is the code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="framework.js"></script>
<script type="text/javascript">
function ShowCalculation() {
var results = Main($("#vehicleWeightTxt").val(), $("#tireChoiceSel").val(), $("#wheelBaseTxt").val(), $("#wheelRadiusTxt").val(), $("#trackWidthTxt").val(), $("#hcgTxt").val(), $("#weightDistributionTxt").val(), $("#shiftRpmTxt").val(), $("#ntTxt").val());
$('#outputTotalTime').empty();
$('#outputTotalPoints').empty();
$('#outputFuelUsed').empty();
$('#outputTimeOpenThrottle').empty();
$('#outputCorneringTimeTotal').empty();
$('#outputTotalStraightSectionTime').empty();
$('#outputTotalNumberOfShifts').empty();
$('#outputTractionLimitedDuration').empty();
$('#outputMeanLongAccel').empty();
$('#outputMeanHorsepower').empty();
$('#outputAccelerationTime').empty();
$('#outputMeanAccelerationLongAccel').empty();
$('#outputAccelerationTractionLimitedTime').empty();
$('#outputAccelerationTotalPoints').empty();
$('#outputAccelerationWideOpenThrottlePercentage').empty();
$('#outputAccelerationShifts').empty();
$('#outputAccelerationTrapSpeed').empty();
$('#outputTotalEnduranceTime').empty();
$('#outputTotalEndurancePoints').empty();
$('#outputTotalEnduranceFuelUsed').empty();
$('#outputTotalWOTPercentage').empty();
$('#outputTotalEnduranceShifts').empty();
$('#outputTotalEnduranceTractionLimitedTime').empty();
$('#outputTotalEnduranceAcceleration').empty();
$('#outputSkidpadTime').empty();
$('#outputSkidpadPoints').empty();
$('#outputSkidpadVelocity').empty();
$('#outputSkidpadAcceleration').empty();
$('#outputAutocrossTime').empty();
$('#outputAutocrossPoints').empty();
$('#outputAutocrossTotalShifts').empty();
$('#outputAutocrossTractionLimitedTime').empty();
$('#outputAutocrossVelocity').empty();
$('#outputAutocrossWOTPercentage').empty();
$('#outputAutocrossLongitudinalAcceleration').empty();
$('#outputMaxHorsepower').empty();
$("#outputTotalTime").append(results.output1);
$("#outputTotalPoints").append(results.output2);
$("#outputFuelUsed").append(results.output3);
$("#outputTimeOpenThrottle").append(results.output4);
$("#outputCorneringTimeTotal").append(results.output5);
$("#outputTotalStraightSectionTime").append(results.output6);
$("#outputTotalNumberOfShifts").append(results.output7);
$("#outputTractionLimitedDuration").append(results.output8);
$("#outputMeanLongAccel").append(results.output9);
$("#outputMeanHorsepower").append(results.output10);
$("#outputMaxHorsepower").append(results.output27);
$("#outputAccelerationTime").append(results.output11);
$("#outputMeanAccelerationLongAccel").append(results.output12);
$("#outputAccelerationTractionLimitedTime").append(results.output13);
$("#outputAccelerationTotalPoints").append(results.output14);
$("#outputAccelerationWideOpenThrottlePercentage").append(results.output15);
$("#outputAccelerationShifts").append(results.output16);
$("#outputAccelerationTrapSpeed").append(results.output17);
$("#outputTotalEnduranceTime").append(results.output1);
$("#outputTotalEndurancePoints").append(results.output2);
$("#outputTotalEnduranceFuelUsed").append(results.output3);
$("#outputTotalWOTPercentage").append(results.output4);
$("#outputTotalEnduranceShifts").append(results.output7);
$("#outputTotalEnduranceTractionLimitedTime").append(results.output8);
$("#outputTotalEnduranceAcceleration").append(results.output9);
$("#outputSkidpadTime").append(results.output18);
$("#outputSkidpadPoints").append(results.output19);
$("#outputSkidpadVelocity").append(results.output20);
$("#outputSkidpadAcceleration").append(results.output21);
$("#outputAutocrossTime").append(results.output22);
$("#outputAutocrossPoints").append(results.output23);
$("#outputAutocrossTotalShifts").append(results.output24);
$("#outputAutocrossTractionLimitedTime").append(results.output25);
$("#outputAutocrossVelocity").append(results.output26);
$("#outputAutocrossWOTPercentage").append(results.output4);
$("#outputAutocrossLongitudinalAcceleration").append(results.output9);
}
function mouseClick() {
document.getElementById("submitButton").src = "images/loading.gif";
}
function revertBack() {
document.getElementById("submitButton").src = "images/simulationSubmit.png";
}
function simulationEvents() {
mouseClick();
ShowCalculation();
revertBack();
}
</script>
<center><img src="images/simulationSubmit.png" alt="" id="submitButton" onmouseover="mouseOver()" onmouseout="mouseOut()" onclick="simulationEvents(); return false;" /></center>

Since all your processing is being done in javascript, that will tie up your script until it finishes.
Javascript isn't multithreaded, it does one task at a time until that task is done.
Generally, when you see that animated gif while a form is being processed the page is using AJAX or something similar. The number crunching is happening server-side using PHP or Python or something like that.
The animation just runs while the javascript waits to hear back from the server-side script.
You might be able to work around it somewhat with this tutorial but that seems like overkill for this situation. The easiest thing would probably be to send the form data to a server-side script or just deal with not having an animation during processing.
Edit: If you're wanting to learn how to do AJAX, here's a tutorial that uses jQuery, which your site is already loading.

Related

Callback function with onload in src/url

This may be a really simple question but despite all my fiddling I can't get it to work and I think others might find it helpful in the future.
I'm using the embed payment button here: https://commerce.coinbase.com/docs/#payment-buttons
I have my script:
<div>
<a class="buy-with-crypto" data-custom="MY_CUSTOM_DATA"
href="https://commerce.coinbase.com/checkout/e690ad8a-8bed-4d6e-a8a7-
b47c2efc456f">
Register
</a>
<script src="https://commerce.coinbase.com/v1/checkout.js?version=201807">
BuyWithCrypto.registerCallback("onPaymentDetected", function(e){
alert("payment detected");
});
</script>
</div>
I've tried putting the function above in separate script tags, tried amending the url with .js?onload=[untold number variables/callbacks] as it details in the docs for initialization but it's still not working.
What I want (and what I believe this is meant to do), is once a payment is detected by the script it activates the function and sends an alert (alert to eventually be replaced by what I actually want but you get the idea).
Got it to work. I have the function in separate script tags above and below (just covering all options). I then amended the src/url with js?onload=BuyWithCrypto(onPaymentDetected) and the alert came through.

Attach javascript event to content loaded with AJAX

previously I had page that was loaded in the usual way with a list of addresses taken from the database and displayed on the page with a php script. I had on the page a JavaScript code that obfuscated the telephone numbers with the following code.
<div class="telephoneNumber" data-last="'.$data_last.'" data-first="'.$first_numbers.'">
<span style="cursor:pointer;">'.$data_last.'</span>
</div>
$(document).ready(function(){
$('.telephoneNumber').toggle(function() {
$(this).find('span').text(Joomla.JText._('ADVKONTENT_SHOW_TELEPHONE_NUMBER'));
},function() {
$(this).find('span').text( $(this).data('first') + $(this).data('last') );
}).click();
}
I have change the architecture of the page and we now load the list of addresses using a ajax call and the results injected into the page. The numbers are now not obfuscated.
I have searched for possible solutions but they all seem to involve some user action such as click. Is it possible to rewrite the JavaScript, it does have to be in jquery, so that as the result are loaded into the page we can apply the obfuscate script?
The solution turned out to be remarkably simple. Putting the the code:
$('.telephoneNumber').toggle(function() {
$(this).find('span').text(Joomla.JText._('ADVKONTENT_SHOW_TELEPHONE_NUMBER'));
},function() {
$(this).find('span').text( $(this).data('first') + $(this).data('last') );
}).click();
at the end of the HTML that is returned in the AJAX call means the toggle function is add at the right points and the phone numbers are hidden.

Design pattern for loading view in front-end JavaScript

I am relatively new to web-programming and am looking for a simple pattern to show a "loading"/waiting view for the web. Before I say anything else, I am sending only the minimum amount of data from the server, and start sending the JS/HTML resources to client while the client is using AJAX to request more data from the server (this might be suboptimal but bear with me). So basically, in theory this should mean the web view pops up earlier initially, but spends more time loading some of the data and corresponding subviews. Thus the need for a loading view.
So we have the standard jQuery function .ready()
fetchSomeDataAsynchronously(); //self-explanatory
$(document).ready(function () {
//should I load waiting view here or can I initialize it earlier??
window.mainUserHomeView = new MainUserHomeView({el: $("#user-home-main-div")});
window.mainUserHomeView.render();
window.userHomeMainTableView = new UserHomeMainTableView({el: $("#user-home-main-table-div")});
window.userHomeMainTableView.render();
fetchTeamSnapTeams(); //fetch more data asynchronously
});
Maybe my question is simply - can I show a loading screen before .ready() fires and what does that look like?
Yes you can. Just include the script to show the view in your HTML's head or at the beginning of the body. Make sure that you put it after you've loaded your required resources (e.g. jQuery) though.
Simplified example:
<html>
<head>
<script type="text/javascript">
function showLoadingView() {
// ...
}
showLoadingView();
</script>
</head>
<body>
<!-- ... -->
</body>
</html>

How to load an external JS library that has code between <script> tags using jQuery

The original code I have is
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: qwerty
</script>
I want to make this code happen using jQuery after something has been triggered. Something like this
jQuery.getScript('http://platform.linkedin.com/in.js');
The problem is that I am not sure what the api_key part does, I've never seen the combination of a request to external lib and code between script tags. Is there a way to imitate that with jQuery? And also - what does that line do? :)
Thanks!
It's not exactly the answer to the question I originally posted, which is more abstract. But in case someone stumbles on this question in connection to linkedin, here's the way to load their framework asynchronously.
jQuery.getScript("http://platform.linkedin.com/in.js?async=true", function success() {
IN.init({
api_key: "qwerty"
});
});
I did some digging through what happens when you load the script, and found that in.js parses the contents of the tag whose src is itself and uses them to build a new script tag to append to the head.
Based on your post, it appended
<script src="https://www.linkedin.com/uas/js/userspace?v=0.0.2000-RC1.20888-1402&apiKey=qwerty&"></script>
to the head. userspace.js obviously rejected the api key, but because this is a proprietary method of loading data, I can't predict how it'll work if and when you try to turn that into an ajax call.
Update:
According to the script tag standard, "If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI." This allows LinkedIn to get away with putting invalid Javascript inside the script tag, knowing it'll never get evaluated by the browser.
This should work correctly on jQuery mobile site.
<script type="IN/Apply" data-companyname="XXX" data-jobtitle="XXX" data-joblocation="XXX" data-email="XXX#XXX.XXX">
</script>
<script type="text/javascript">
$(function() {
if(typeof(IN)=="undefined"){
$.getScript("//platform.linkedin.com/in.js?async=true", function success() {
IN.init({api_key: "XXX"});
});
}
else{
IN.parse();
}
});
</script>

Tracking outgoing links with Javascript and PHP

I have tried it using jQuery but it is not working.
<script>
$("a").click(function () {
$.post("http://www.example.com/trackol.php", {result: "click"
}, "html");
});
</script>
out
To get the best results you should change two things in your approach
Use onmousedown instead of click - this way you get a few extra milliseconds to complete the tracking request, otherwise the browser might not start the connection to your tracker at all as it is already navigating away from the original page. The downside is that you might get some false-positive counts, since the clicking user might not finish the click (eg. keeps the mousebutton down and moves the cursor away from the link) but overall it's a sacrifice you should be willing to make - considering the better quality of tracking.
Instead of an Ajax call ($.post('...')) use an image pre-fetcher (new Image().src='...'). The fact that the tracker is not an image is not relevant in this case because you don't want to use the resulting "image" anyway, you just want to make a request to the server. Ajax call is a two way connection so it takes a bit more time and might fail if the browser is already navigating away but the image pre-fetcher just sends the request to the server and it doesn't really matter if you get something back or not.
So the solution would be something like this:
<script>
$(document).ready(function() {
$("a").mousedown(function (){
new Image().src= "http://www.example.com/trackol.php?result=click";
});
});
</script>
out
Instead of using JavaScript to call a php tracking script, you could just link to your tracking script directly and have it in turn redirect the response to the ultimate destination, something like this:
out
and in the PHP script, after you do your tracking stuff:
...
header("Location: $dest");
As mentioned, the problem is you’re not running the script after the DOM has loaded. You can fix this by wrapping your jQuery script inside $(function() { }, like so:
This works:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tracking outgoing links with JavaScript and PHP</title>
</head>
<body>
<p>Test link to Google</p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
$('a').click(function() {
$.post('http://www.example.com/trackol.php', { result: 'click' }, 'html');
});
});
</script>
</body>
</html>
See it in action here: http://jsbin.com/imomo3

Categories