Google ReCaptcha without PHP plugin - ajax

I understand the cross-domain error when using ajax to try to obtain information from another website but according to jQuery you should be able to use a jsonp request instead. I am stumped on how to achieve this when trying to display recaptcha. The issue is I am unable to use the plugin to achieve this, which would make it so much easier.
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
function showRecaptcha() {
Recaptcha.create("// removed for example", 'captchadiv', {
tabindex: 1,
theme: "red",
callback: Recaptcha.focus_response_field
});
}
jQuery(document).ready(function(){
showRecaptcha('recaptcha_div');
jQuery('#contact-form').submit(function(){
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
var ip = "<?php print $_SERVER['REMOTE_ADDR'] ?>";
var private = "// removed for example";
var requestUrl = "http://www.google.com/recaptcha/api/verify?privatekey=" + private + "&remoteip=" + ip + "&challenge=" + challenge + "&response=" + response;
jQuery.getJSON(requestUrl, function(json) {
alert("what");
});
})
});
</script>
<form id="">
// Form stuff
</form>
<div id="captchadiv"></div>
<input type="submit" name="submit" id="form-submit">
How should I call this to googles server and obtain the correct callback. It's basically going to return a true or false. I either get the infamous Access-Control-Allow-Login or or an error regarding plain/text. Anyone with suggestions?

1) Google does not support JSONP output. Why? Go to 2).
2) reCAPTCHA is meant to be validated on server side code. Why? Go to 3).
3) Spammers can easily bypass your client side validation code, thus rendering any CAPTCHA solution pointless.

You can try this way, Invisible reCAPTCHA
https://developers.google.com/recaptcha/docs/invisible

Related

reCaptcha blocked frame (SOP?)

Got a Typo3 Installation where i've added Googles reCaptcha to a Form.
Did that already successful on other Typo3 installations, but this time, i get the blocked frame error in the Browser.
Blocked frame with origin "https://www.google.com" from accessing a cross-origin frame.
at um.f.hc (https://www.gstatic.com/recaptcha/api2/....)
This happens two times and after that, i get this massage in the frontend.
Please upgrade to a supported browser to get a reCAPTCHA challenge.
Alternatively if you think you are getting this page in error, please check your internet connection and reload.
Why is this happening to me?
This is happening in all Browsers i checked (Chrome, FF, IE11).
To include the reCaptcha i've adde the following to the Template:
<script src="//www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript">
var captchaCallback = function() { document.getElementById("captchaResponse").value = document.getElementById("g-recaptcha-response").value }
var onSuccess = function(response) {
var errorDivs = document.getElementsByClassName("recaptcha-error");
if (errorDivs.length) {
errorDivs[0].className = "";
}
var errorMsgs = document.getElementsByClassName("recaptcha-error-message");
if (errorMsgs.length) {
errorMsgs[0].parentNode.removeChild(errorMsgs[0]);
}
captchaCallback();
document.getElementById("fhcallback").submit();
};
</script>
<input type="hidden" id="captchaResponse" name="fhcb[recaptcha]" value="" />
<div id="recaptcha-demo" class="g-recaptcha" data-sitekey="[MYPUBLICKEY]" data-callback="onSuccess" data-bind="inp-submit"></div>
<button class="orderButton bold" id="inp-submit" ###submit_nextStep###>Senden</button>
And in PHP:
$secret = '[MYSECRETKEY]';
$url = 'https://www.google.com/recaptcha/api/siteverify';
$apiResponse = json_decode(\TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($url.'?secret='.$secret.'&response='.$this->gp[$this->formFieldName]), true);
if($apiResponse['success'] == FALSE) {
$checkFailed = $this->getCheckFailed();
}
The Form is not visible on pageload. Its a slide in at the right side of the page, after clicking its toggle element.
I'am out of ideas and the client is bugging me already.
I found the Issue. On this Installation, the JavaScript Library Mootools was included.
After removing the include of Mootools, no further problems with blocked Frames occurred.

jQuery mobile : Linking next page doesn't work on Windows phone using phonegap

Currently im building a application using phonegap & jQuery Mobile
I have done the version which is perfectly working on iOS & Android.But the same code does not work on windows phone.When i click any link,redirection to the respective page is not loading..Its still says "Error Page loading".
<!DOCTYPE html>
Test
<div id="bg">
<div style="padding-top:14%;width:100%;text-align:center">
<div style="float:left;text-align:center;width:50%"><img src="pics/btn_1.png" /></div>
<div style="float:left;text-align:center;width:50%"><img src="pics/btn_2.png" /></div>
</div>
<div style="clear:both"></div>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
Need help on this.
Solution
Add data-ajax=false or rel=external to your anchor tag. But, if you do this, you will lose transitions. This tells the framework to do a full page reload to clear out the Ajax hash in the URL. You could enable this if the incoming device is a windows phone if needed :
$(document).on("mobileinit", function () {
//check for windows phone
$.mobile.ajaxEnabled = false;
});
Else, make your code into a single page template. Here's a demo of that : http://jsfiddle.net/hungerpain/aYW2f/
Edit
Currently jQM doesn't support query string parameters. You could use the localStorage API to store the parameters in cache and retrieve them later. Assuming you want to go to index.html from here :
<img src="pics/btn_2.png" />
You'd add a click event for it :
$(document).on("click", "a", function() {
//gets qs=2 and changes it into ["qs",2]
var query = this.href.split["?"][2].split["="];
//construct an array out of that
var paramString = { query[0]: query[1]} ;
//store it in localstorage
locaStorage["query"] = JSON.stringify(paramString);
//continue redirection
return true;
});
In your index.html :
$(document).on("pageinit", "[data-role=page]", function() {
//store it in localstorage
var params = JSON.parse(locaStorage["query"]);
//now params will contain { "qs" : 2 }
//you could access "2" by params["qs"]
});
More info about localStorage here.
I had Also same issue and finally resolve it by using below code
my html page is index.html and i am writtinga all code in one html
Before
$.mobile.changePage( "#second", {});
After
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
url = url.replace(url.substring(url.lastIndexOf('/') + 1),"index.html#second");
$.mobile.changePage(url, { reloadPage : false, changeHash : false });
and suppose you have multiple html page then for more one page to another you can use
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
url = url.replace(url.substring(url.lastIndexOf('/') + 1),"second.html");
$.mobile.changePage(url, { reloadPage : false, changeHash : false });
There is no support of querystring in web application using phonegap for windows phone 7.
However we can replace ? with # or anything else to pass the data,
like convert
Sample.html?id=12312
to
Sample.html#id=12312

pass variables to php with ajax load()

I found some close answers for this, but none of them worked in my case. I have:
Input tag:
<input name="title" id="title">
Ajax:
<script language="javascript">
function example_ajax_request() {
$('#example-placeholder').html('<p><img src="/img/ajax-loader.gif" /></p>');
setTimeout('example_ajax_request_go()', 0);
}
function example_ajax_request_go() {
$j(document).ready(function () {
var inputField = $j('#inputText').val();
$j(".button").click(function () {
$('#example-placeholder').load('preview.php?title=' + title + ' .aClass');
}
</script>
Button to call the function:
<input type="button" onclick="example_ajax_request()" value="Preview" />
I'm trying to pass 'title' var from the input tag via ajax to 'preview.php'. This code above has errors and is not running, can you suggest correct one? Thanks!
You have not put in exact error messages (from your browser's console, please put them in and update your question). I am just putting across some suggestions/improvements:
Whenever you are passing GET parameters, always URIEncode the value(the xyz and value in url?abc=xyz&blah=value). In javascript there is a function call EncodeURIComponent(..). You would use it like:
'preview.php?title=' + EncodeURIComponent(title +' .aClass')
A possible typo, you have have a space in the URL, before the + ' .aClass'. If you need one, explicitly replace it with a + or %20.
Found a way. Here it is:
<script type="text/javascript">
function example_ajax_request() {
$('#example-placeholder').html('<p><img src="img/ajax-loader.gif" /></p>');
$('#example-placeholder').load("preview.php?title="+$('#title').val());
}
</script>
Thanks!

ajaxComplete/ajaxStop/ajaxSuccess not firing

I appreciate any and all help. I am a beginner with little jQuery/AJAX experience and I have been going crazy trying to figure out why I can't figure this out.
I'm writing a Facebook page application that has the user grant permissions and upload a video to the page. All of this works fine and dandy. This is not so much a Facebook API related issue as it is an ajax issue (at least I think).
Basically, I am trying to gain control of the page IN SOME WAY after the user uploads a video. I am using the [malsup jQuery Form Plugin][1] to have the resulting page (which is a page on Facebook displaying returned JSON values) load in a hidden iframe.
I am able to get ajaxStart to fire, and I've tested this by having it change the background color or print an alert message when I click "Upload". However, when the upload completes (and it does complete successfully), NOTHING ELSE HAPPENS. The returned JSON values load in the hidden iframe and the page sits there. I have tried getting ajaxComplete, ajaxStop and ajaxSuccess to fire, but none of them do for whatever reason.
So overall, here is what I am trying to accomplish:
- I want to redirect the user or make some hidden content appear after the file upload completes. I don't even care if there's errors. I just need SOMETHING to happen.
- I am using the jQuery Form Plugin because I am not unfortunately not advanced enough to figure out how to use that value and do something with it, but if anyone can steer me in the right direction, that would be appreciated.
And finally, here is my code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
iframeTarget: '#output2',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
// bind form using 'ajaxForm'
$('#theform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
</script>
<script type="text/javascript">
jQuery().ready(function(){
$('body').ajaxStart(function() {
$(this).css("background-color","red");
});
$('body').ajaxSend(function() {
$(this).css("background-color","blue");
});
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
$('body').ajaxStop(function() {
$(this).css("background-color","purple");
});
});
</script>
</head>
<body>
<?php
$app_id = "xxxxxxx";
$app_secret = "xxxxx";
$my_url = "xxxxxx";
$video_title = "xxxxxxxxx";
$video_desc = "xxxxxxxxx";
$page_id = "xxxxxxxx";
$code = $_REQUEST["code"];
if(empty($code)) {
// Get permission from the user to publish to their page.
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&display=popup&scope=email,publish_stream,manage_pages";
$current_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($current_url != $dialog_url)
{
echo('<script>window.location ="' . $dialog_url . '";</script>');
}
} else {
// Get access token for the user, so we can GET /me/accounts
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
$accounts_url = "https://graph.facebook.com/me/accounts?" . $access_token;
$response = file_get_contents($accounts_url);
// Parse the return value and get the array of accounts we have
// access to. This is returned in the data[] array.
$resp_obj = json_decode($response,true);
$accounts = $resp_obj['data'];
// Find the access token for the page to which we want to post the video.
foreach($accounts as $account) {
if($account['id'] == $page_id) {
$access_token = $account['access_token'];
break;
}
}
// Using the page access token from above, create the POST action
// that our form will use to upload the video.
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&access_token=". $access_token;
// Create a simple form
echo '<form action=" '.$post_url.' " method="POST" enctype="multipart/form-data" id="theform">';
echo 'Please choose a file:';
echo '<input name="file" type="file">';
echo '<input type="submit" value="Upload" id="button-upload" />';
echo '</form>';
}
?>
<iframe id="output2" name="output2"></iframe>
</body></html>
Thank you for your help!!
It seams you are getting an Ajax Error. I don't see any error handler in your code. Could you try to add an error handler as follows
<script>
$(document).ready(function(){
$(document).ajaxError(function(e, jqxhr, settings, exception) {
alert(exception);
})
})
</script>
I have played around with file uploads, and there are a complicated beast because of all the security that browsers have for protecting users file systems and whatnot.
On to your problem, I think that there is a good chance that your AjaxForm jQuery plugin doesn't connect properly to the global Ajax state for Jquery. Even if it did, I would say that tapping into the global Ajax state is a bad design. If you add any other ajax requests to this page, then your ajaxComplete, ajaxStop, etc. functions are going to start getting called.
Your better approach is to use the callbacks provided by the AjaxForm plugin. Lets focus on this first part of your code.
Does this work?
success: showResponse // post-submit callback
...
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
If so, could you replace this:
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
With this:
function showResponse(responseText, statusText, xhr, $form) {
$(this).css("background-color","green");
}
I believe that using the success: callback is the intended use of the AjaxForm plugin.
The jquery ajaxSend or ajaxStart throws some kind of an error and the document does not execute ajaxComplete. I tried to fix the bug for quite a while and was only able to find a workaround:
function hideAjaxIndicator() {
$('#ajax-indicator').hide();
}
$(document).ready(function () {
setTimeout(hideAjaxIndicator, 1000);
});
You can add this to .js file.

Update the content of a div via AJAX with jQuery when they're new events

I am doing a match "live timing" where an administrator sends to a database new inputs like: "Team A scores! 1-0". This is shown in a public website inside a <div /> and I want to get the new inputs and print it. I've never done something similar and I don't know what is the way to go.
I also have some doubts:
It's posible that the server sends the content to a X browser? So do the browser will only be on "idle"?
It's possible to only refresh when the user is active on the browser? Like Facebook does, if you're not present on the browser or moving your mouse over you don't get updates.
It's possible to append only to the <div /> the new items and not refresh all of it?
Thank you in advance!
You can use the ajax methods like this one:
$.getJSON('ajax/test.json', function(data) {
$('.result').html($('.result').html()+'<p>' + data.foo + '</p>'
+ '<p>' + data.baz[1] + '</p>');
});
or:
$.ajax({ url: "test.html", context: document.body, success: function(){
.......................................
}});
With a setTimeout call:
(function() {
$(document).ready(function() {update();});
function update() {
$.getJSON(.................);
setTimeout(update, 3000); }
}
)();
Then you could bind a mouseover event to the div that wraps your web, that would force an ajax call. You should use a control variable to know when the call is processing, so no to duplicate it.

Resources