Inserting script from jQuery / Javascript - javascript

I'm trying to insert reCaptcha code into my page from jQuery, but it doesn't work.
Here is my code:
$("#button").click(function() {
$("#loginBox").html($.getRecaptcha());
})
When I try the following, my code doesn't even run. I think it's trying to execute instead of rendering it.
$.getRecaptcha = function(){
return '<script type="text/javascript"' +
'src="http://api.recaptcha.net/challenge?' +
'k=6Ld3iAsAAAAAAGyX8QT244GagPEpCDSD-96o4gEi"></script>';
}
With the following, the code runs, but when I click to #button I get an empty, full white
browser window.
$.getRecaptcha = function(){
var captcha = $("<script>")
.attr("type", "text/javascript")
.attr("src", "http://api.recaptcha.net/challenge?k=6Ld3iAsAAAAAAGyX8QT244GagPEpCDSD-96o4gEi");
return captcha;
}
I don't want to insert reCaptcha code into my html from the beginning, because it downloads the reCaptcha content from the reCaptcha server even if my users don't want to use it. I could set the visibility of the container that holds the reCaptcha to invisible (display: none;), but it will dowload the content irrespectively of it.
I can insert the "noScript" code that reCaptcha gives us, but it doesn't work either, because it can spot that the browser allow javascript but I use noScript.
Any suggestions?
(I know I put my public reCaptcha key into the code, but it is just for testing purposes, and you could get it from my html or javascript code anyway)
UPDATE:
Krunal Mevada answered my question. But it doesn't work with reCaptcha. reCaptcha offers a reCaptcha AJAX API which is the answer to my specific question. However, with getScript() I can dinamically download the reCaptcha AJAX API javascipt file.

Use getScript method of jQuery.
May be this answer can be useful:
Stack Answer

First code part: insert a space at the end of the first line:
return '<script type="text/javascript" ' +

Related

Changing all post images URL to a new URL from the post excerpt field

It's my first time posting here.
I have a fairly simple script that I'm trying to get working on my word press website. I'm essentially trying to make a loop that goes through all the posts on a page and changes that URL to another URL
I am going to be pasting the new URL in the post excerpt field. What I want to happen is that once a user clicks on the image of a post on the homepage, they are taken to the URL that I specified on the post excerpt field of that respective post.
here is the code I came up with.
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
$('ul.g1-collection-items li.g1-collection-item').each(function(){
var that = $(this);
var excerpt_link = $(<?php echo get_the_excerpt ?>);
that.find('.entry-featured-media a').attr('href', excerpt_link);
});
});
</script>
But as expected, this doesn't work. Also, using this code seems to only work on the URL slug, not the entire URL
Any thoughts? Thank you so much for all your help!
The code dosen't work because you're mixing jQuery foreach loop without a Wordpress foreach loop. I get what you're trying to do, but you're doing it wrong.
In the part where you have the loop for posts just add the
<?php echo get_the_excerpt();?>
And put it on the anchor tag of the image, and you're done, no need for jQuery.
P.S. you also wrote the get_the_excerpt wrong, it wouldn't work. It's a function so it needs a ()

Detect if tag is in URL and then remove hidden class

I have a form on my contract form, which submits to a third party site and then I can define a URL to return the user to. I currently return the user to the same /contact page but I wanted to give them a message that it had submitted (since ajax forms don't work with the third party) and I don't want to have a whole page for it.
Therefore I had the idea to return the user to /contact#thanks
I have some code on my site which goes like this:
<div id="alert" class="hidden">Form Submitted. We will reply soon.</div>
Now I want a small bit of javascript on my page which detects if the URL has the #thanks tag on it, as above, and then removes the hidden class from my alert div. Is javascript able to detect this and if so, how do I go about it?
Include jquery and script. I test and work
$(document).ready(function(){
if(window.location.hash) {
$("#alert").show()
}
});
Siii = Yes use hash
I'm not totally sure that I've understood what are you trying to achieve, but this might help you:
if (window.location.hash === '#thanks') {
document.getElementById('alert').classList.remove('hidden');
}

How do I change URL without reloading page? - WITH A TWIST

I am looking to remove a certain amount of a page URL without reloading.
I have looked on StackOverflow for the answer and there are a few close answers but not what I'm looking for really.
I do not want to use the hash function and if possible, avoid using the HTML5 version because HTML5 isn't the ratified standard yet and for the website this will be used on, I wouldn't be at all surprised is some of the clients used IE6.
I would prefer if it wasn't an extremely complicated solution with 400 lines of code (at that cost I'd rather just reload the page to be honest).
I forgot to mention this, critical, part of the question
The user is directed from a different page with this string via PHP. So for example:
user submits a form with errors. Let's say the form is on /myform.php
The user gets headed to /index.php?string
carry on as normal
What I have:
This is an example URL that I wish to edit without reloading:
http://www.mywebsite.com/index.php?string
Wait! ?string has a use on /index.php
index.php will use $_GET['string']; and display a message to the user
I have used JQuery to remove the message after 4 seconds like this:
<div id="pagemsg"><?php echo $string; ?></div>
<script language="javascript">
setTimeout( "$('#pagemsg').fadeOut();", 4000);
</script>
This works all well and the message disappears after 4 seconds. However I'm left with this URL:
http://www.mywebsite.com/index.php?string
I don't want this string anymore because ?string has done its job!
I would like to remove the ?string without reloading the while page.
Is there any solution that can help me?
Also,
I don't mind if I have to use the HTML5 push function but is there a fall-back solution for the browsers that don;t support HTML5?
Why did I put WITH A TWIST in the title? Well, my requirements are different to the questions I have seen so far. Correct me if I'm wrong and I will change it.
Thanks for your help in advance!
The simple answer is no. That's why they added pushState.
However, it looks like you are trying to accomplish a fairly common scenario known as flash messaging. This is often done using the user's session to store a message to show on the next request (and then delete it).
Example:
function doImportStuff() {
// ...
$_SESSION['message'] = 'important stuff was done';
// ...
}
function showBoringPage() {
// ...
if (isset($_SESSION['message']) {
echo '<b>' . $_SESSION['message'] . '</b>';
unset($_SESSION['message']);
}
// ...
}
The only method I know of is this:
if (history && history.pushState){
history.pushState(null, null, '/new/url');
}
But this is HTML5 and won't work in your case..
For old browsers - and you: History.js

php echo javascript function after an ajax call doesnt work?

So I ran into a problem and I couldn't really find a good solution anywhere. And I'm sure more people run into this problem.
I tried to have an Ajax script call to a php-script which echoes a JavaScript function again but this function wont run or activate. It however does show up in the code if you do inspect element.
So the html and Ajax is as follows. Its dummy code since my own is a bit more complicated. so any syntax errors I made here are not the solution since this works for other parts of my code.
<html><headbodyetc>
<div id='change'>
//is supposed to alert or call another js function after
//verifying something with a database for instance.
<button type='button' onclick='ajaxbelow();'>alert</button>
</div>
<script type='text/javascript'>
function ajaxbelow(){
//AJAX code as found on w3schools.com/php/php_ajax_php.asp
//calls the change.php
</script>
</etc></html>
The php code that gets called is very simple.
//This shows up in the html-code after clicking the button but doesnt run.
echo"<script type='text/javascript'>alert('doenst work?')</script>";
So I am looking for a solution which makes me able to run a JavaScript or jquery function after an Ajax call, or the main reason why this doesn't work. Since I couldn't find it.
Inb4 why call the alert via php? Because I need to verify something first with the db on the server-side in my actual code.
So after combining and testing some of the comments I figured out my own answer.
You cant create new javascript within the php echo. You can however echo an onload that calls an existing function. Onload only works for the following tags:
"body", "frame", "frameset", "iframe", "img", "input type="image", "link", "script", "style".
However in this case after testing some of them like "script" and "img" it still didn't work with all tags, but it did with the "style" tag. I didnt test all other tags though.
So that changed my code to:
<html><headbodyetc>
<div id='change'>
//is supposed to alert or call another js function after
//verifying something with a database for instance.
<button type='button' onclick='ajaxbelow();'>alert</button>
</div>
<script type='text/javascript'>
//function to be called
function test(){
alert("now it works");
}
function ajaxbelow(){
//AJAX code as found on w3schools.com/php/php_ajax_php.asp
//calls the change.php
</script>
</etc></html>
and the php-code will then become
echo"<style onload='test();'></style>";
and now it does run the function.
edit this doesn't seem to work for IE, looking for a solution right now.
^
EDIT: By default, IE Browsers "DENY" the ability of scripts to throw prompts. So to enable this functionality, you must go to [Tools/ Internet Options/ Security / Custom Level / "Allow websites to prompt for information using scripted windows"] and enable that... Once you refresh, you will see your alert in IE :)
Just add slashes before single quote as given below
<?php echo '<script type="text/javascript">alert(\'doenst work?\')</script>'; ?>
You could use eval() to evaluate the returned javascript. The script tags wont be required if this method is used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Try this:
http://www.webdeveloper.com/forum/showthread.php?184830-Ajax-echo-script-problem
Basically the reason why nothing happens is because you are just sticking content in the DOM. Javascript is an event driven language and since nothing is telling the javascript to run at this point, its just sitting there doing nothing. If that code were there when the browser loaded the page, then the browser parsing the code is what would tell it to run. So, what you need to do is evaluate any scripts that come back

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources