using reCAPTCHA with ajax....javascript loading problem - javascript

I trying to implement reCAPTCHA in one of my forms,...but i am using ajax as the submission. (More specifically the prototype ajax.updater)
Once I submit and error check my form I try to load the reCAPCHTA widget thingy (in my updated div element) which basically just calls a javascript file like so:
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6Le6SwUAAAAAAIWm8wCRFd8SrI-H0R1Yx4Tkw2Ks"></script>
However the JS file is not being read?...and i've tried all combination of evalScripts:true and evalJS:'force' etc. in the ajax.updater.....however i don't think I have a very good understanding of why the js file isn't processing :(
If anyone can shed some light on this issue I will be very appreciative.
Thanks, Andrew

This doesn't address your exact problem, but 'Dark Side of the Carton' has some excellent code for validating reCAPTCHA via jQuery AJAX which might help.
In summary:
Add the following Javascript:
$(function() {
function validateCaptcha() {
var challengeField = $('input#recaptcha_challenge_field').val(),
responseField = $('input#recaptcha_response_field').val();
// alert(challengeField);
// alert(responseField);
// return false;
var html = $.ajax({
type: 'POST',
url: 'ajax.recaptcha.php',
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if (html.replace(/^\s+|\s+$/, '') == "success") {
$('#captchaStatus').html(' ');
// Uncomment the following line in your application
return true;
} else {
$('#captchaStatus').html(
'Your captcha is incorrect. Please try again'
);
Recaptcha.reload();
return false;
}
}
// Modified as per comments in site to handle event unobtrusively
$('#signup').submit(function() {
return validateCaptcha();
});
});
Then add the ajax.recaptcha.php file which: "outputs only the word “success” if the captcha matches and a message and the response from reCaptchta if it fails. This is important because we are looking for the word success in our validateCaptcha() function."
require_once('/inc/recaptchalib.php');
$publickey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // you got this from the signup page
$privatekey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$resp = recaptcha_check_answer(
$privatekey,
$_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']
);
if ($resp->is_valid) {
?>success< ?
} else {
die(
"The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")"
);
}
The example is in PHP, but I adapted it easily to work with Zope/Python

Be careful using any sort of client-side script, such as JavaScript, for validation. You have no control over the end-user's browser. The purpose of a CAPTCHA is to prevent automated submissions of a form. Anyone sophisticated enough to set that up isn't going to have a problem overriding your JavaScript validation and CAPTCHA checking. For example, they could set validateCaptcha() to always return true, bypassing your careful checks - or just disable JavaScript.
That being said, there's nothing wrong with performing the entire form submission with ajax and using the results of the CAPTCHA check to determine if the form gets processed or not.
The important point is that the decision of whether or not to handle the form has to be made on the server-side, not the client-side.
Why client-side validation is not enough

to answer my own question...
there is a reCAPTCHA AJAX api....which is pretty easy way to get around this problem:
link text
Also,..the documentation on the http://www.prototypejs.org/api/ajax/updater site.....talks about the evalscript option and how is only puts any javascript through the native eval() function....which kind of screws me over trying to implement error checking with WMD...but that's another story.
Andrew

If that's the literal code snippet you're using, you haven't closed the tag... so it wouldn't be evaluated.

call Recaptcha.reload(); on callback event in your Ajax code., it will reload new Recapcha every time that Ajax submitted

Hi Friend i found the answer
https://developers.google.com/recaptcha/docs/display?hl=es#AJAX
And in this how validate
http://blog.reaccionestudio.com/comprobar-recaptcha-con-ajax-usando-jquery/
Success for you

Securing AJAX calls with reCaptcha
function performAJAX() {
let captcha = $('[name=g-recaptcha-response]');
$.ajax({
url: 'ajaxHandler.html',
data: {
captcha: (captcha.length?captcha[0].value:''),
// other data fields
},
});
}

I have had similar issues with getting reCaptcha to play nicely when loaded into the page using jQuery's .load() method. Here is a page that has a novel solution: http://www.maweki.de/wp/2011/08/recaptcha-inside-a-with-jquery-ajax-or-load-dynamically-loaded-object/
Basically the reCaptcha API uses document.write method to display the reCaptcha. When you get jQuery invloved this won't work. Use this PHP code in place of loading recaptcha.js
<?php
$api = file_get_contents('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
$api = str_replace('document.write','$("body").append',$api);
echo $api;
?>
It just does a find for document.write and replaces it with $(selector).append.
Made my implementation work.

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

HTML form with PHP - submitting and staying on same page [duplicate]

This question already has answers here:
PHP form - on submit stay on same page
(11 answers)
Closed 5 years ago.
I have a form on a website (www.mywebsite.com). I have a PHP script that sends me an e-mail with information when somebody submits a form on my website. But with action="submitform.php" in the form, it updates the site to the URL www.mywebsite.com/submitform.php. I would like it to stay on the main site (index).
The solution for this: I added header("Location: http://mywebsite.com"); die(); to my PHP code. In this way, users will be redirected to the main site when they have submitted code.
However, this pose a new problem.
Whenever someone submit the form, I would like to display a message such as "Mail has been sent". To make this work, I tried to have a small JavaScript code, basically
document.getElementById("message").innerHTML = "Mail has been sent."
... and <div id="message"></div> to my HTML code. Which works...... However, due to my PHP script redirecting me to my website (with header) when someone is submitting the form, the message will only be displayed for like half a second or something.
Anyone know any workarounds for this? Thanks in advance. I can provide more detail if needed, but my problem should be clear from this. Hope anybody is able to spot my mistake...
I use javascript and ajax for most of my form post. Works wonderful.
Ajax can grab the form information in a form object or pass it as an array. URL is your php proc page, there it will come back with whatever you "print/echo" in a data object that is passed into the success function.
Use this in your HTML,
<input type="button" onclick="submitForm();" value="Submit">
Javascript,
function submitForm(){
//Validate INPUT first. Then grab the form.
form = new FormData($('#frmIdHere')[0]);
$.ajax ({
type: 'POST',
dataType: 'text',
url: url,
data: form,
success:data => {
//Success message here.
//clear form here.
},
error: () => {
// error message here.
}
});
}
php process file use,
$inputFromForm = (isset($_REQUEST["NameOfInputFromForm"])) ? strip_tags($_REQUEST["NameOfInputFromForm"]) : "-";
Without using Ajax (which means you can send the form without refreshing the page), you have two options. Either send the form to a different file, process it, and redirect back - but with a GET parameter to indicate success or failure. Alternatively, just post to the same page (so the handling of the form happens in the same page - I recommend the first alternative).
If you want to use the post-redirect-get pattern, you would use
header("Location: /?status=success");
exit;
when the form was successfully handled in your submitform.php file.
Then you just check what the message in $_GET['status'] was, and display the message accordingly in your index.php file.
if (isset($_GET['status']) && $_GET['status'] == 'success') {
echo "Your message was successfully sent!";
}
This logic can be developed further to have different parameters, to post messages for success and failure, if that's needed for the application.
assumption: you want the user to stay on the page with the form.
in that case you probably don't return false / stop event propagation in your calling code.
let's say, you call your ajax like this:
<form onsubmit="submitform(this);" ...>[form]</form>
onsubmit does the following, it executes anything that is in it's attribute value (submitform(this)) and if it returns some non-false value, it will actually do the action of the form, as if the onsubmit wouldn't have existed. I assume this is exactly what's happening in your case.
To avoid this:
<form onsubmit="submitform(this); return false">[form]</form>
the return false will stop the form from being submitted, after it was already submitted by ajax. this also has the benefit of still working, if the user has javascript disabled.
if my assumption is false however ...
if you want to refresh the page, don't even use ajax and just add a parameter to the url that triggers the message to show. or add the message to the session in php and clear it out of there after displaying.
To doing this, You can use a SESSION var to store message send type (success or failed) and test it everytime on main page, if exist, display message and unset $_SESSION var !
Like this :
MAIN
if(isset($_SESSION['message'])){
if($_SESSION['message'] == 'success'){
echo "Yeah !";
}else{
echo "Problem";
}
unset($_SESSION['message']);
}
MESSAGE
if(mail()){
$_SESSION['message']='success';
}else{
$_SESSION['message']='error';
}
You can set interval and then redirect them to desired page.
<script>
setInterval(function(){ window.location.href="http://mywebsite.com" }, 5000);
</script>

Why am I getting this Internal Server Error in the Laravel Framework?

I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.

How to find the URL of an external site's Javascript submit

I will do my best to try to explain this.
I am scraping a website for it's elements to then output in a different format. The problem that I am experiencing is the way that this site directs the user throughout the site is through a Javascript redirect.
When checking the 'a href' tag, this is the Javascript that shows up
javascript:doParamSubmit(2100, document.forms['studentFilteredListForm'], 'SSC000001MU9lI')
The SSC000001MU9lI changes for each element that it redirects to.
Is it possible to find a URL using this Javascript, so that I can reach the HTML page externally?
EDIT: Here is the doParamSubmit and doSubmit classes:
function doParamSubmit(event, form, parameter) {
form.userParam.value = parameter;
doSubmit(event, form);
}
function doSubmit(event, form)
{
// Make sure if something fails that the form can be resubmitted
try
{
// If this form has not been submitted yet... (except for IE)
if (allowSubmit == true && form != null && (submitted == false || isInternetExplorer6() || isInternetExplorer7()))
{
submitted = true;
form.userEvent.value = event;
// Fix for IE bug in which userEvent becomes a property array.
if (form.userEvent.length)
{
form.userEvent[0].value = event;
}
// Disable the form so the user can't accidentally resubmit the page
// (NOTE: this doesn't disable links (e.g. <a href="javascript:...">)
disableForm(form);
// If there is a populate form function, call it. If there are spell check fields on the
// page, populateForm is used to set hidden field values.
if (this.populateForm)
{
populateForm();
}
saveScrollCoordinates();
// resetSessionTimeout();
try
{
form.submit();
}
catch(e)
{
// Exceptions thrown here are only caused by canceling the submit in onbeforeunload, so ignore.
submitted = false;
}
}
if (allowSubmit == false)
{
alert(grabResource("message.pageLoading"));
}
}
catch(e)
{
submitted = false;
throw e;
}
}
I see 2 approaches.
You use a javascript enabled browser such as http://nrabinowitz.github.io/pjscrape/. I am not sure if you intend to just follow the links or instead grab the URL for some other use so your mileage may vary.
Find the doParamSumit() function in their page/scripts and analyze it to understand how it gets the URL - the one you have as an example looks like it grabs the action from a form perhaps? Once you know how the function work you might be able to harness that info in your scraping by using some regex to find URLs that match the doParamSubmit pattern and going from there. It's hard to say without seeing the function itself as well as the other links like it though.
Regardless of which method you choose I would begin by understanding the function - look for it in the code or loaded js files (you can also you things like javascript debuggers on most browsers to help you find it) and see what happens - it might be super obvious.
Also keep in mind that this might be a POST for a form - in which case the result of you following that link may not work if it expects valid form data.
Edit I see that you posted the function. It simply submits the form listed in the second parameter i.e. 'studentFilteredListForm'. While I don't think your scraping will go to far chasing forms you can still get the URL either with javascript if your scraper lets you (something like $('form[name=studentFilteredListForm]').attr('action') or using whatever language your are using for the scraper i.e. find the form and extract the action url (remembering that if there is no action it is probably posting back to the current URL)
But again... you might first manually get the URL of the form and see where that gets you. You might just get a page with form errors :)

How to store HTML attributes that trigger javascript commands properly to mysql using ajax?

I have problems when saving html5 data from a page into mysql through an ajax request and trying to retrieve it back with ajax. HTML attributes that trigger some javascript such as
<onload> or <iframe> will be stored as <on<x>load> and <if<x>rame> in the database and thus screw up the page when loading it.
Here's a short description of what I am trying to accomplish: I want registered users to have the ability to highlight text on my site and get the highlighted text back after refreshing the page, relogging etc.
What I have done so far: I implemented a javascript highlight library on my server that allows users to highlight text. That works well.
By clicking a button, those data are then saved into mysql through jquery ajax post. See specific code here:
Javascript
$(document).ready(function() {
//saves highlighted data in var "highlighted"
$('#savehighlights').click(function() {
var highlighted = $('.tabcontent.content1').html();
//send data to server
$.ajax({
url: 'highlight.php',
type: 'POST',
data: {highlighted: highlighted},
dataType: 'html',
success: function(result) {
console.log(result);
}
});
});
Saving the data to mysql works generally, but it looks as if certain commands are disabled through the process (e.g. onload becomes on<x>load5). The data are stored in the database as longtext and utf8_bin. I also tried blob, but problem remains. I also tried different dataTypes with Ajax such as 'text' and 'script'. 'Text' causes the same problem and 'script doesn't work at all. I also tried the ajax .serialize function, but no luck either.
I really don't know what to do about it and I am not sure what is causing the problem, Ajax or mysql? I was searching the web for an answer, including many articles in stackoverflow (which normally always give me the answer), but this time I am stuck. Either I don't know enough about it to look for the right question, or I just don't have any luck this time. So, any help would be greatly appreciated.
I was requested to add some more information. Here it is:
I am actually doing this on my local server (localhost) with XAMP, so security issues should not be a problem, right? If it is of any help, I am doing this in a Tiki Wiki CMS. The php script that is called through ajax (highlight.php) is the following:
require_once ('tiki-setup.php');
include_once ('lib/highlights/highlightslib.php');
$highlighted = $_POST['highlighted'];
$highlightslib->save_highlights($user, $highlighted);
The highlightslib library is here:
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
class HighlightsLib extends TikiLib
{
function save_highlights($user, $highlighted) {
$saveHighlights = $this->table('tiki_user_highlights');
$saveHighlights->insert
(array(
'user' =>$user,
'highlightId' =>'',
'data' =>$highlighted,
'created' =>$this->now,
)
);
return true;
}
};
$highlightslib = new HighlightsLib;

Categories

Resources