Callback function with onload in src/url - javascript

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.

Related

Even with the inline JavaScript function - Google ReCAPTCHA couldn't find user-provided function: function (response) -

I am using ReCAPTCHA version V2. On the callback function (i.e. data-callback), I am getting the following error message.
ReCAPTCHA couldn't find user-provided function: function (response)
Now, most of the posts/solutions I see on the web are related to a local callback function that doesn't get invoked when referred in data-callback attribute of the g-recaptcha div. However, in my case, even the inline function does not get invoked. Please have a look at the following image.
Screenshot-1:
In fact, when I am using JavaScript native function such as alert(), it is still not working.
Screenshot-2:
Here's the JS code I am using.
<script src='https://www.google.com/recaptcha/api.js'></script>
First try - callback function:
<div class="g-recaptcha" data-sitekey="Please add your site key if you want to test" data-callback="function (response) { alert('working: ', response);}"></div>
Second try - callback function:
<div class="g-recaptcha" data-sitekey="Please add your site key if you want to test" data-callback="Window.alert('hi');"></div>
I appreciate your help if you can help me understand why is the google API responding in a completely weird way.
Inline JavaScript function in Google ReCAPTCHA will never work.
If it could save somebody's time, I am posting his answer here.
All credit goes to #Christos Lytras. Many thanks to him for helping me understand the JS behind the Google ReCAPTCHA. What he said in the comment section about Recaptcha's JS tries to identify the function by its name in the global window object, is absolutely correct. Thus, my implementation was not working and will never work (at least in the V2 version).
In all my solutions when I was trying to implement an inline function, it was read as the window[function (){}]or window[Window.alert('hi');] which is incorrect JS syntax. Therefore, when I tried it the following way, it worked like charm.
Correct approach
<script>window.myCallBackFunction = function() { alert("HI"); }</script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="XXX" data-callback="myCallBackFunction" ></div>
Please note: Just for more clarity, I have also tried implementing the callback function initially before posting this question and it didn't work because of the order of the scripts. Thanks to this answer on another question that helped me immensely but after #Christos Lytras's explaination. In the beginning, I was implementing it in the following order.
Incorrect approach
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>window.myCallBackFunction = function() { alert("HI"); }</script>
<div class="g-recaptcha" data-sitekey="XXX" data-callback="myCallBackFunction" ></div>
I hope it could help somebody like me, in the future.

HTML onload not calling JavaScript function

I have looked at other questions similar to this, but I haven't found an answer.
My <body onload="doStuff()"> has stopped calling the doStuff() JavaScript function. I have tried replacing <body onload="doStuff()"> with <body onload="alert('Test');"> and that creates the alert successfully.
Then I tried putting that same alert just inside the doStuff() function (and reverting the onload to call doStuff()), but the alert did not appear.
Are there any reasons why this would happen? Also, it may be relevant to note that I am almost certain that I did not make any code changes in between this working and it not working (you may not believe that, but it's true); however, I did delete a sub-folder from the server that contained a Joomla installation.
Make sure that your script tag is correct.
<script src="myscript.js" /> will cause <body onload="...">...</body> to fail.
It should be:
<script src="myscript.js" type="text/javascript"></script>
Try to move away from inline calls and utilise jQuery as it was intended. Its really good working practice, (not to mention easier to debug) by keeping your style, and script logic separate.
for body on load, use this.
$(document).ready(function () {
doStuff();
});
or it can be shortened even further to
$(function () {
doStuff();
});
For whatever reason in firefox, my Scripts declared in the body of the page was preventing inline calls from firing. I moved my script tags to the header and then it worked.
The issue with the uncaught syntax error (see comments in original post) was that, when I was converting a PHP array into a JavaScript array, something was going wrong, i.e., a weird character was being appended. I solved this by replacing my DIY PHP-array-to-JS-array code with this code:
<?php
$js_array = json_encode($resultsArray);
echo "var jsResultsArray = ". $js_array . ";\n";
?>
This isn't really connected to the headline question of the post, but it was the root problem.

Adding a loading gif when submitting form?

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.

jQuery .load() does not load plug-ins [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a main page with 2 links that load external files via .load(). The first file has a simple JavaScript rollover, which works when the content is loaded. The second file has a jQuery plug-in that does not work when loaded via .load() - but works fine when the data file is viewed by itself.
Main file: http://gator1105.hostgator.com/~carc/test-load.html
Second data file that works by itself, but not from .load(): (same URL as above, but the file is test-load-two.html - StackOverflow will allow me to create only 1 hyperlink)
Rather than paste my source code here, you can just view it from the pages themselves.
How can I get the second file with the slideshow to work when loaded with .load()?
I acutally did something similar with a site I'm working on. What you'll want to do is make a callback function for each page for the $.load() call on the main page.
See the following code from the jquery.load() documenation:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
In your particular case, you'd want something like this on the main test-load.html page.
$(document).ready(
function(){
$('li').click(function(){
var showThisContent = this.id;
$('#content').load('test-load-'+showThisContent+'.html', function(){
if (showThisContent == "one"){
//Do logic for test-load-one.html
//Pre-load your images here.
//You may have to assign a class to your anchor tag
//and do something like:
$('a.assignedClass').mouseover(function(){});
$('a.assignedClass').mouseout(function(){});
} //end if
if (showThisContent =="two"){
//Do logic for test-load-two.html here
$('.slideshow').cycle({
fx: 'fade',
speed: 500,
timeout: 0,
next: '.nextSSimg',
prev: '.prevSSimg',
pager: '#SSnav',
cleartype: true,
cleartypeNoBg: true
}); //end .cycle()
} //end if
); //end .load(location, callback function())
}); //end $('li).click()
}); //end $(document).ready()
Now, obviously I didn't convert all your code, but what's happening here is that once document.ready is complete, the callback function will run, and since the elements like '.slideshow' are now loaded into the DOM, you're callback code will bind to them appropriately.
You could switch this code around in several ways to have the same result (i.e., wrap 2 $.load()s into conditions rather than doing the conditional logic in the .load callback, and/or put a callbackOne() and callbackTwo() function above document.ready and then call them appropriately) but that's your preference. You should be able to do what you want to using the callback function argument of the $.load().
Ignore this answer
Your second file does its initialization in a "document.ready" block. That's not going to be run when your content loads via AJAX. Try taking the code in the second page that's inside "document.ready" out of that, so that it's just a bare script block.
[edit] Oh I see - not only is the script inside a "document.ready" block (well, it's not anymore), but that second page is a complete HTML document. You can't really load a complete HTML document into the middle of another document; it doesn't make sense, and jQuery is only going to grab what's in the body. Thus, try moving your script tag into the body and see what happens. (You still don't want "document.ready", I don't think.)
[edit again] actually I take that back - I don't think jQuery strips anything out; I just bet the browser gets confused.
[edit yet again] ok, ok I see that you've changed it again - let me take a really close look.
OK here's a better answer: for reasons I don't understand, when you load a fragment (or a whole page; whatever) with jQuery using the special "selector" trick to pluck out just a portion of the document:
var showThisContent = this.id;
$('#content').load('test-load-' + showThisContent + '.html #content-area');
the jQuery library strips out the scripts completely from the content, and doesn't ever run them. Why? I don't know.
I know that you probably don't trust me anymore, but here's what I did with your source code: I took that second file (test-load-two) and stripped out the head and stuff; basically I made it a fragment containing only the "content-area". (I also got rid of the script tag that loads jquery, as you don't really need that since the outer page already has it.) Then I changed the main page (test-load) so that when it calls "load" it just passes in the URL without that '#content-area' selector. That works.
[edit] I just posted a question to the jQuery forum: http://forum.jquery.com/topic/the-load-function-and-script-blocks
Don't go for $.load. Try $.get instead, which might seem less comfortable, but it worked for me in a different case. Sample code as following.
$(li).click(function() {
// your code for finding the id
$.get('test-load-' + id + '.html', function(responseHtml){
$('div#content-area').empty().append($(responseHtml)); // remove all elements from #content-area
// $('...').html(responseHtml) will not work
});
});
I hope this solves your problem.

JQuery isn't recognising a #id selector, seems to be dependent on the URL

I'm writing a Ruby on Rails app. The following jQuery code is included in the head tag of the index.html.erb file, which is the template for all pages on the site.
<script>
$(document).ready(function() {
$("#select_mailshot").click(function () {
alert('mailshot');
document.location.href = "/products/1";
});
$("#select_blog").click(function () {
alert('blog');
document.location.href = "/messages";
});
$("#select_contact").click(function () {
alert('contact');
document.location.href = "/contacts/1";
});
});
</script>
(the alert steps are in there for debugging)
The following html code in index.html.erb
<ul>
<li id="select_mailshot">Mailshot</li>
<li id="select_blog">Blog</li>
<li id="select_contact">Contact us</li>
</ul>
The intention is that this effectively creates 3 buttons.
When clicking on any button from http://myurl.com/ it all works.
When clicking on any button from http://myurl.com/messages (get to this via the middle button) it all works
When starting from http://myurl.com/products/1 it all stops working (the alerts do not trigger). In fact when starting from http://myurl.com/anything/id it stops working.
I've been trying to solve this for hours now and the only difference between the working and non-working conditions is the url as far as I can see.
Can anyone shed any light as to what's going on here?
What does firebug tell you? Do you have javascript errors on the page? if so, what are they? Are you sure the jQuery library is included correctly in the deeper pages ( i.e. is it a relative path? )
Is this javascript inlined?
If not, then maybe the link is relative so when you try to load it from messages/40 you need ../script.js. Another solution is to use absolute URLs (http://myurl/script.js) or virtual (/script.js).
Thanks to cherouvim and digitaljoel.
This was due to javascript files being included relative to the current URL.
The following was included in the head tag
<script type="text/javascript" src="javascripts/jquery-1.3.2.js"></script>
I changed it to
<script type="text/javascript" src="/javascripts/jquery-1.3.2.js"></script>
(note the extra "/" in the src attribute) and everything works as expected.
I worked this out after checking the error logs on the server and in the browser.
Feeling a little dumb but a lesson well learned.
I was using FaceBox to create modal overlays and I couldn't figure out why I was having the same problem.
I turns out that the listener wasn't being attached to HTML elements until it was visible. (The items were available if I viewed source, but jQuery seemed not to attach a listener until it was visible.)
For anyone having the same problem, I'd suggest moving your click() code to a point where the HTML element you're attaching to is visible.
Also, I've found selecting by ID does give more problems than class. I have no idea why. (No, there were not duplicate IDs.)
Hope this helps someone with the same problem!

Categories