ajax execute script - javascript

Ok, I think i'm getting close but things still aren't working:
I've got the following function
function showRecaptcha()
{
alert("test2");
$.getScript("/plaoul/commentfiles/recaptchaJS.php", function(data, textStatus, jqxhr) {
console.log(data); //data returned
console.log(textStatus); //success
console.log(jqxhr.status); //200
console.log('Load was performed.');
});
}
The function is supposed to call the follow javascript: http://www.jeffreycwitt.com/plaoul/commentfiles/recaptchaJS.php (feel free to view this page - it works just fine here, but not when I call it through ajax)
This is a javascript that when executed displays the recapatcha form.
So far the console log returns the following:
<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6LfDj8gSAAAAAG53PTtr-1665awLtERThvylvnUY"></script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=6LfDj8gSAAAAAG53PTtr-1665awLtERThvylvnUY" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>
comment_navbar_jsfunctions.js:129success
comment_navbar_jsfunctions.js:130200
comment_navbar_jsfunctions.js:131Load was performed.
But I want the <script> to actually show up as the recpatcha image in a div on my page div#commentWindow. Once I have the script using getScript I can't figure out how to get the script to display in div#commentWindow. Can you help me?

Since you are grabbing this HTML via AJAX you don't have to worry about <noscript>. So you can do something like this:
//get plain-text from local PHP file
$.get('/plaoul/commentfiles/recaptchaJS.php', function (response) {
//get the source of the `<script>` element in the server response
var source = $(response).filter('script')[0].src,
script = document.createElement('script');
//set the type of our new `<script>` element and set it to `async = true`
script.type = 'text/javascript';
script.async = true;
//set the source of the new `<script>` element to the one in the server response
script.src = source;
//add the new `<script>` element to the DOM
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(script, s);
});
You may notice some of this code is from the Google Analytic Asynchronous tracking code (the part that creates a new <script> element).

So you simply want to fetch the output of that PHP file and render it out to the page?
Have you tried $('#commentWindow').load('/plaoul/commentfiles/recaptchaJS.php');
Edit -- sorry, that should have been .load. http://api.jquery.com/load/

Related

How do I trigger ad on button click? [duplicate]

I have 2 divs in my HTML.
<div id="div1"></div>
<div id="div2"></div>
On clicking the "div2" I want to load an external javascript file say for example "https://abcapis.com/sample.js".
I tried including the JS file on onclick event like below,
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://abcapis.com/sample.js";
document.getElementsByTagName("head")[0].appendChild(script);
This included the script tag in the head section but did not load since the script tag will be loaded on page load only (correct me here if I'm wrong).
Is there any other way that I could proceed?
Thanks in Advance.
Using jQuery's $.getScript() function should do the job for you.
Here is a slice of sample code:
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
If you are not using jQuery, you're going to have to learn how to use AJAX to dynamically load new script into your page.
Your code almost works. You need to use .setAttribute. Here is my working code. I used jQuery as my script:
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'jquery.min.js');
document.head.appendChild(script);
And that'll do it.
EDIT:
Some more info. When you do something like script.type = 'text/javascript' you are setting a property on the object but this is not necessarily the same thing as associating that property with an actual node attribute.
Are you using jQuery? If so, you can try $.getScript().
You might also want to check this answer. But basically, you can do something like this:
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
An info I missed was, that the path has to be absolute.
Copy and paste this function on your code.
<script type="text/javascript">
getScript=(url)=>{
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
if(document.body == null){
document.head.appendChild(script);
}else{
document.body.appendChild(script);
}
}
</script>
And now call this function with your .js file url.
Example:getScript('https://abcapis.com/sample.js');
Info:
File should not contain DOMContentLoaded or $(document).ready() function

click to load Google plus javascript to show comments

Hi i want to load comments from google plus. what people are posted on google plus from my website.
i actually just installed this code in WordPress blog post. if a user wants to reply to post by clicking on Google+ button to load code from Google plus and load comments.
<button onClick="showGoogle();">Google+</button>
<div style="max-width:100%" id="loading">
<div id="gpcomments" style="max-width:100%"></div>
</div>
<script>
gapi.comments.render('gpcomments', {
href:'http://findsgood.com/?p=43224',
width: '682',
first_party_property:'BLOGGER',
view_type: 'FILTERED_POSTMOD','callback' : function showGoogle() {src='https://apis.google.com/js/plusone.js';}});
</script>
plusone.js is being loaded asynchronously but gapi is being called synchronously. gapi isn't available until plusone.js is finished loading. You can use an onload event to wait until gapi is ready for use.
<button onClick="showGoogle();">Google+</button>
<div style="max-width:100%" id="loading"><div id="gpcomments" style="max-width:100%"></div></div>
<script>
function showGoogle() {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://apis.google.com/js/plusone.js';
script.onload = function() {
gapi.comments.render('gpcomments', {
href:'http://findsgood.com/?p=43224',
width: '682',
first_party_property:'BLOGGER',
view_type: 'FILTERED_POSTMOD'
});
}
head.appendChild(script);
}
</script>
finally found code working but i have to click button twice. i don't know why i need to click two times?. please someone help?
<button onClick="showGoogle();">Google+</button>
<div style="max-width:100%" id="loading"><div id="gpcomments" style="max-width:100%"></div></div>
<script>function showGoogle() {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'https://apis.google.com/js/plusone.js';
head.appendChild(script);
gapi.comments.render('gpcomments', {
href:'http://findsgood.com/?p=43224',
width: '682',
first_party_property:'BLOGGER',
view_type: 'FILTERED_POSTMOD'
});}
</script>
you can run test here a on blog post http://findsgood.com/?p=43224
First click generates an error in the console, for the sake of testing try to include plusone.js in theme header manually. (this feels more like a comment, just can't add them yet).

Incomplete HTML after Executing `document.write()`

After executing document.write(), Google Chrome shows me that the HTML codes is changed from Code A to Code B. It seems that document.write() overwrite the entire page. If yes, how to append the script tag inside head tag?
Code A : Before Executing document.write()
<!--DOCTYE html-->
<html>
<head>
<script src=".\js\main_CasCode.js"></script>
</head>
<body onload="main()">
<p>hi</p>
</body>
</html>
Code B : After Executing document.write()
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
</html>
JavaScript in File .\js\main_CasCode.js
function main() {
//console.log = function() {};
loadjQuery();
//waitjQueryLoaded_and_start();
}
function loadjQuery() {
console.log("Loading jQuery...");
var s = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>';
document.write(s); //<----Problem Here
}
That's because document.write erases and rewrites the document when the document has already finished rendering (like after onload). It only appears to append when called during the rendering of the page.
A better way to do this is to dynamically create a script element, add it to the page, and add an src which triggers the loading mechanism.
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
In other news, why are you loading jQuery dynamically when you have control of the page? Why not add it directly as a <script> on the HTML?
I don't think you want to be using document.write at all. You can use the following. Make a script element, and append it to the head element
var head = document.getElementsByTagName('head')[0]
var s = document.createElement('script')
s.src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"
head.appendChild(s)
document.write overwrites the whole DOM
You can create a function
function loadjQuery() {
console.log("Loading jQuery...");
var scrpt = document.createElement('script');
scrpt.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
document.head.appendChild(scrpt);
}

how to add this html code into the append code

So I have the following html code:
<div>
<script type="text/javascript" src="https://app.ecwid.com/script.js?4549118"></script>
<script type="text/javascript"> xMinicart("style=","layout=Mini"); </script>
</div>
Please take a look at the actual code run in the browser. It shows a link.
I want to add the link to an navigation bar with the following code:
<script>
window.onload=function(){
$('nav ul').append('<li><a onClick="test()" href="javascript:void(0);">Link 3</a></li>');
}
</script>
But I'm not managing to add the code within the append correctly. How do I reference the js source and call the xMinicart function within the append code?
Thanks a lot!
super important update!
It's almost there! the following javascript code does work in jsfiddle but it doesn't work in squarespace. I'm not sure why.
$('nav ul').append('<li id="hello">test</li>');
$.getScript("https://app.ecwid.com/script.js?4549118", function(){
xMinicart("style=","layout=Mini","id=hello");
});
You can see it working here: http://jsfiddle.net/u3NKD/8/
I think you want to use jQuery's getScript function
https://api.jquery.com/jQuery.getScript/
So you would load the URL and then use the callback to execute the code
<script>
var url = "https://app.ecwid.com/script.js?4549118";
$.getScript( url, function() {
var s = document.createElement('script');
s.innerText = 'xMinicart("style=","layout=Mini");'
$('nav ul').append(s);
});
</script>
Try this instead of my other answer, here's a JSFiddle I tried
http://jsfiddle.net/W2pQA/1
<script>
$(function(){
$('ul').append('<li><a onClick="test()" href="javascript:void(0);">Link 3</a></li>');
var url = "https://app.ecwid.com/script.js?4549118";
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
var s = document.createElement('script');
s.innerText = 'xMinicart("style=","layout=Mini");'
$('ul').append(script).append(s);
});
</script>
It may be that the JS you're trying to execute is trying to run before the external JS file has completed loading.
I modified your latest JSFiddle to wait for the external file to load, then when finished, execute the xMiniCart code:
http://jsfiddle.net/u3NKD/9/
$('nav ul').append('<li id="hello">test</li>');
var script = $.getScript("https://app.ecwid.com/script.js?4549118");
$.when(script).then(function(){
xMinicart("style=","layout=Mini","id=hello");
});
Here's some documentation on the $.when code above:
https://api.jquery.com/jQuery.when/

How to load an external Javascript file during an "onclick" event?

I have 2 divs in my HTML.
<div id="div1"></div>
<div id="div2"></div>
On clicking the "div2" I want to load an external javascript file say for example "https://abcapis.com/sample.js".
I tried including the JS file on onclick event like below,
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://abcapis.com/sample.js";
document.getElementsByTagName("head")[0].appendChild(script);
This included the script tag in the head section but did not load since the script tag will be loaded on page load only (correct me here if I'm wrong).
Is there any other way that I could proceed?
Thanks in Advance.
Using jQuery's $.getScript() function should do the job for you.
Here is a slice of sample code:
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
If you are not using jQuery, you're going to have to learn how to use AJAX to dynamically load new script into your page.
Your code almost works. You need to use .setAttribute. Here is my working code. I used jQuery as my script:
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'jquery.min.js');
document.head.appendChild(script);
And that'll do it.
EDIT:
Some more info. When you do something like script.type = 'text/javascript' you are setting a property on the object but this is not necessarily the same thing as associating that property with an actual node attribute.
Are you using jQuery? If so, you can try $.getScript().
You might also want to check this answer. But basically, you can do something like this:
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
An info I missed was, that the path has to be absolute.
Copy and paste this function on your code.
<script type="text/javascript">
getScript=(url)=>{
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
if(document.body == null){
document.head.appendChild(script);
}else{
document.body.appendChild(script);
}
}
</script>
And now call this function with your .js file url.
Example:getScript('https://abcapis.com/sample.js');
Info:
File should not contain DOMContentLoaded or $(document).ready() function

Categories