Ajax call not working properly when used with Recaptcha - javascript

I am using PHP and AJAX together in my website to fetch data from a JSON URL and to display it on the webpage. When I use it without implementing recaptcha, it works fine but when I integrate Google's Recaptcha, the results get displayed only when the captcha puzzle is solved twice everytime. I am not sure where the bug actually lies and I even tried to implement a custom captcha and in that case also it is the same. Here is the code with recaptcha,
Captcha and Ajax code snippet :
<?php
if ($resp != null && $resp->success): ?>
echo"hi";
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(), function(response) {
$("#success").html(response);
});
return false;
});
});
</script>
<?php
else:
echo "Failed";
?>
Full code :
http://pastebin.com/UynEiYng

This part should be moved to retrieve_train_between_stations.php.
require_once "recaptchalib.php";
// your secret key
$secret = "My secret key";
// check secret key
$reCaptcha = new ReCaptcha($secret);
$resp = false;
if (isset($_POST["g-recaptcha-response"])) {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($resp) {
//display the record
} else {
echo 'Recaptcha can not be verified.';
}
The if/else should be removed and prevent the default event for the script
<script>
$(document).ready(function(){
$("#submit").click(function(event){
event.preventDefault();
$.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(), function(response) {
$("#success").html(response);
});
return false;
});
});
</script>

Related

How do I redirect the user with PHP after using jQuery's preventDefault() on a form?

I'm using jQuery, AJAX and PHP to validate most of the forms on my website. The actual input validation is done via PHP (I thought this would be best to prevent users from bypassing validation using the browser source code inspector to edit scripts), but I use jQuery and AJAX to load errors into an error message div below the form's submit button.
All of this works fine, but when a form is successfully submitted I'd like to call header('Location: foo.php') to send my user back to a certain page. However, since I'm using preventDefault(), my new page is being loaded into the error message div, making the browser window look like it has two pages on top of each other (the current url doesn't change either).
Is there a fix to this? I thought I might be able to unbind the event in the PHP file by including a script after the PHP code is done, but I was not successful.
jQuery:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
//this is where the PHP is loading the new page, along with error messages
$(".form-message").load("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
});
});
});
End of PHP file:
<?php
//if successful, exit the script and go to a new page
$submissionSuccessful = true;
exit(header('Location: /index.php'));
?>
<reference path="/javascript/jquery-3.3.1.min.js"></reference>
<script type="text/javascript">
var submissionSuccessful = "<?php echo $submissionSuccessful; ?>";
if (submissionSuccessful)
{
$("#title, #content").css(
{
"border": "2px solid #24367e"
}
);
$("#title, #content").val("");
}
</script>
The approach I talk about is similar to this
$(document).ready(function () {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
// AJAX POST request to PHP
$.post("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
}).done(function (response) {
// response is a JSON document
if (response.error) {
// Here you basically modify the UI to show errors
$(".form-message").text(response.error)
} else {
// Here you basically modify the UI to show success
$("#title, #content").css({ "border": "2px solid #24367e" });
$("#title, #content").val("");
location.href = '/index.php' // REDIRECT!
}
});
});
});
And in the server end
<?php
if ($someSuccessCondition) {
$response = ['success' => true];
} else {
$response = ['error' => 'The Error Message'];
}
echo json_encode($response);
exit();

How do I resend data from previous url after reCAPTCHA passed in the same page?

Data sent from this
www.example.com/modules/liaise/index.php?form_id=xxx
In normal condition, after submit, the page redirects to
www.example.com/modules/liaise/index.php
and sends mail.
Wantedly, I placed the reCAPTCHA in the same file (index.php).
Google captcha :
require_once "recaptchalib.php";
// your secret key
$secret = "secret key";
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
//send mail
} else {
echo '
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div id="html_element"></div>
<script>
var onloadCallback = function() {
grecaptcha.render("html_element", {
"sitekey" : "sitekey",
"callback" : correctCaptcha
});
};
var correctCaptcha = function(response) {
location.reload();
};
</script>';
}
Whenever I pass reCAPTCHA and page reloads, reCAPTCHA shows again.
I know data from previous page www.example.com/modules/liaise/index.php?form_id=xxx is still there by using
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
Is there any way by which I can resend data from previous url after reCAPTCHA is passed in the same page?
I am newbie in coding. Please be specific.
Thank you so much!
If your talking about re-sending your data as mail you can use something like this:
if (isset($_POST['form-input'])) {
// Send mail
}
and every time you reload the page and the Post data is not null or blank, it will run that code.
If you are wanting the reCAPTCHA to reload as success, I would say that's defeats the security of reCAPTCHA
Also I see that you have a typo esle should be else.

cant post value using ajax in zend framework 2

I'm using ajax to post a value as given below,
but data I post wont reach the controllers ajaxAaction
view script (which is a tpl file)
<input type="text" id='taska'>
<button id='submitTo'>button</button>
script
$(document).ready(
function(){
//controller via ajax
$("#submitTo").click(function() {
var message = $('#taska').val();
if (message != '') {
//run ajax
//alert ('not empty');
$.post('index/ajax',
{'message' : message},
//callback function
function (respond) {
//put respond in class show-msg
$(".show-msg").html(respond);
}
);
}
});
and the action
public function ajaxAction() {
//get post request (standart approach)
$request = $this->getRequest()->getPost();
//referring to the index
//gets value from ajax request
$message = $request['message'];
// makes disable renderer
$this->_helper->viewRenderer->setNoRender();
//makes disable layout
$this->_helper->getHelper('layout')->disableLayout();
//return callback message to the function javascript
echo $message;
}
} );
$.post('index/ajax', is the part where I think the error is.
Am I defining the controller and action in the wrong way?
I've been stuck here for a while.
please help
try it with $this->basePath() in <?php echo $this->basePath();?>index/ajax
Solved it by prefixing the rootPath as below
if (message != '') {
//run ajax rootPath
{/literal} $.post("{eval var=$rootPath}/index/ajax", {literal}
{'message' : message},
//callback function
function (respond) {

Javascript, AJAX & PHP working in Chrome but not in Firefox, Safari, IE

UPDATE:
I've found out what's been causing this problem. The webpage has a piece of Javascript contained inside its body which is preventing the Javascript body onload= function from executing in Firefox, Safari and IE. Chrome is able to run both without problems. To solve this I've tried moving the script inside <head>..</head> however that script will not work for me there, it seems like it needs to be inside the body (I've tried calling it from an external .js file too but it won't work from there either). This is the body onload function along with the problematic script:
<html>
<head>
//some Javascript & Style files are included here..
</head>
<body onload="getUserDetails()">
<script>
window.onload = function() {
$('#selectAllFriends').change(function(){
if (this.checked) {
$('#mfsForm :checkbox').each(function() {
this.checked = true;
})
}
else {
$('#mfsForm :checkbox').each(function() {
this.checked = false;
})
}
});
}
</script>
//rest of page body is contained here...
</body>
</html>
This script is needed as part of a Facebook Multi-Friend Selector. I think maybe the problem is to do with running window.onload and body onload= at the same time? Is there a way to maybe delay the Multi-Friend Selector script for a couple of seconds to let the body onload= function to run first, and would that resolve the problem?
Original Question:
I have a Javascript function which gets called on page load. Inside this function there’s a call to Facebook’s Graph API, this call gets user details from Facebook, and then passes them by an AJAX post to a PHP script.
This is the Javascript I'm using:
function getUserDetails() {
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
if (response.error) {
console.log('Error - ' + response.error.message);
}
else {
var userid = response.id;
var userfirst_name = response.first_name;
var userlast_name = response.last_name;
var useremail = response.email;
var usergender = response.gender;
$.ajax({
url: 'insertdetails.php',
data: {'userid' : userid,
'userfirst_name' : userfirst_name,
'userlast_name' : userlast_name,
'useremail' : useremail,
'usergender' : usergender},
type: "POST",
success: function(response){
if(response==1){
alert( "Insert Successful!");
}
else{
alert( "Insert Failed!" );
}
}
});
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
}
Originally the PHP script contained two basic Insert statements which inserted these details into two tables in my database. This worked perfectly, but it wasn’t secure, so yesterday I wrote a PDO prepared transaction statement instead. I later found out that my database engine (MyISAM) doesn’t support PDO transaction statements, so I decided instead to run two queries (that would insert data into the two tables) inside the same PHP script instead (I know this isn’t best practice but I couldn’t find a way to get PDO transactions to work with MyISAM).
This is the part that’s confusing to me: when testing the new PHP file, I find that it works perfectly when I open the page in Chrome, however it doesn’t work with Firefox, IE, or Safari.
The PHP script
<?php
$servername = "myserver";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters for 1st insert
$stmt = $conn->prepare("INSERT INTO user (fb_id, f_name, l_name, email, gender)
VALUES (:fb_id, :firstname, :lastname, :email, :gender)");
$stmt->bindParam(':fb_id', $userid);
$stmt->bindParam(':firstname', $userfirst_name);
$stmt->bindParam(':lastname', $userlast_name);
$stmt->bindParam(':email', $useremail);
$stmt->bindParam(':gender', $usergender);
// insert a row
$userid = $_POST['userid'];
$userfirst_name = $_POST['userfirst_name'];
$userlast_name = $_POST['userlast_name'];
$useremail = $_POST['useremail'];
$usergender = $_POST['usergender'];
$stmt->execute();
// prepare sql and bind parameters for 2nd insert
$stmt = $conn->prepare("INSERT INTO orders (fb_id, cb, gb, invite)
VALUES (:fb_id, :cb, :gb, :invite)");
$stmt->bindParam(':fb_id', $userid);
$stmt->bindParam(':cb', $cb);
$stmt->bindParam(':gb', $gb);
$stmt->bindParam(':invite', $inviteo);
// insert a row
$userid = $_POST['userid'];
$cb = "1";
$gb = "10";
$inviteo = "0";
$stmt->execute();
echo "1";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Once the insert statements are completed I send an echo back to the Javascript function, and then a Javascript alert appears on screen to tell me if the insert was successful or not. This works perfectly in Chrome, but I don’t get any alert with the other three browsers, and nothing gets entered into the database when I try to use them. The fact that there’s no alert telling me it’s not successful makes me think that the error is in the Javascript not working with the browsers, but then again, it was working perfectly on all browsers before I switched the PHP to PDO.
I've made sure that Javascript is enabled, pop-ups aren't blocked, and I've tried looking at the console in Firefox but I don't see what could be wrong.
Any help or advice on this would be great. Thank you in advance!

Jquery if statement not working even if the statement is true

I have a simple if statement where when i send this certain data to the database, i want the php code to send bake a code that tells javascript its ok to continue, but if the php script sends back a bad code, javascript is to now move forward and display a certain text or something.
The php code works fine but for some reason my javascript files would not work at all.
My javascript is suppose to ajax request to parse.php and receive the data that parse.php sends back to it, if parse.php says 200 its suppose to load in specific items.
Here is the code for one of my systems:
$(document).ready(function(){
$("#chatForm").submit(function(){
var chatHash = $("#chatHash").val();
var body = $("#chatPoster").val();
var by = $("#userBy").val();
if(chatHash != "" && body != ""){
$.post('parse.php',{chatHash: chatHash, body: body, userBy: by},function(data){
if(data == "200"){ // Right here is where its messing up
$("#chatPoster").val("");
$.get('getChatMessages.php?hash=' + chatHash,function(data2){
$(".allMsgs").html(data2);
});
} else {
alert('Critical error');
}
});
} else {
alert('Error');
}
});
});
Here is the code for the parse.php page:
$chat = new ChatSystem;
if(isset($_POST['chatHash']) && isset($_POST['body']) && isset($_POST['userBy'])){
$chat->sendMessage($_POST['userBy'],$_POST['chatHash'],$_POST['body']);
}
Here is the code from the class ChatSystem that the parse.php page is referring to:
public function sendMessage($user,$hash,$body){
global $db;
$date = date("Y-m-d");
$time = date("H:i:s");
$timestamp = "$date $time";
if(empty($user) == false && empty($hash) == false){
$db->query("INSERT INTO chat_messages VALUES('','$user','$body','$timestamp','','0','$hash')") or die("error");
echo '200';
}
}
Even though my php code works perfectly the javascript still messes up. My php code sends back 200 like i ask it to but yet the jquery messes it up
Have a look here, http://api.jquery.com/jquery.post/.
You need a second parameter to the success callback function to be able to catch the response status code.
I.E. function(data,statusCode){ // check the status code here}

Categories