I'm implementing reCaptcha, and I'm using an Ajax call to a PHP page of mine to check the validity of the captcha, without a page refresh.
I have this jQuery code:
$.post('php/captcha.php', $('#captchaPost').serialize(), function(data){
if(data != "Valid")
{
$('#captchaError').show();
$captchaFlag = "Invalid";
}
else
{
$('#captchaError').hide();
$captchaFlag = "Valid";
}
});
And this PHP code for the post handler:
<?php
require_once('recaptchalib.php');
$privatekey = "1234567890";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_REQUEST["recaptcha_challenge_field"],
$_REQUEST["recaptcha_response_field"]);
if (!$resp->is_valid)
{
// What happens when the CAPTCHA was entered incorrectly
echo "Error";
}
else
{
echo "Valid";
}
?>
I checked the response using Firebug and the PHP script always returns "Error", even when I type in the correct Captcha. The form seems to POST correctly, according to the server, although I don't see how to check what was posted in the form. I am not using the PHP function to build the reCaptcha form; I got the HTML from Google's docs on this. Any help?
Try using this code:
function validateCaptcha()
{
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
var html = $.ajax({
type: "POST",
url: "php/captcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html != "Valid")
{
$('#captchaError').show();
$captchaFlag = "Invalid";
}
else
{
$('#captchaError').hide();
$captchaFlag = "Valid";
}
}
It doesn't look like you were sending the data correctly in your jQuery.
Edit
Also make sure to call validateCaptcha() on the button. For instance:
onSubmit="javascript:validateCaptcha()"
Related
I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
I wanna make header location like stackoverflow system has. After posting, it will load the page based on lastinsertid. I tried to use php, it works, but I wanna change it using ajax jquery because of its single page. Could I use ajax jquery in this case? how to make it work?
here's the code :
PHP
if($sumn>0 && $sump>=0) {
echo "banned";
}
else if($sumn==0 && $sump<=3) {
echo "oot";
}
else{
$insert=$db_con->prepare("INSERT INTO tb_post (id_user,title,description,created_date) VALUES(:id_user,:title,:description,NOW())");
$insert->bindParam(":id_user",$id_user);
$insert->bindParam(":title",$title);
$insert->bindParam(":description",$description);
$insert->execute();
$id_post=$db_con->lastInsertId();
if ($insert->rowCount()>0) {
$post = $db_con->prepare("SELECT * FROM tb_post WHERE id_post=:id_post");
$post->execute(array(":id_post"=>$id_post));
$row=$post->fetch(PDO::FETCH_ASSOC);
$title = clean_url($row['title']);
$detail ="../discuss/".$row['id_post']."/".$title;
header("location:$detail");
echo 'success';
}else {
echo 'fail';
}
ajax jquery
$.ajax({
url: 'create_process.php?page=send_post',
type: 'post',
data: 'title='+title+'&description='+description,
success: function(msg){
if(msg=='success') {
window.location='/'; //This the problem.. need to know how to use header location based on lastinsertid
}
else if(msg=='banned') {
$("#dis-mes").html('<div class="allert alert-danger">Banned</div>');
}else if(msg=='oot'){
$("#dis-mes").html('<div class="allert alert-danger">OOT</div>');
}else {
alert('failed');
}
}
});
instead of using a header, you should return the redirect url in the response.
the php response should be a json string like this :
{
status: "success",
url: "../discuss/".$row['id_post']."/".$title
}
in the javascript just check the content of msg.status and use msg.url in your window.location
If you still want to use headers, you can use this in your success function:
success: function(msg, textStatus, request){
if (msg == 'success') {
window.location = request.getResponseHeader('location'));
}
},
I'm trying to call some php code using ajax:
$(document).ready(function() {
$("#email_address").on("keypress", function() {
request = $.ajax({
url: '../verify_email.php',
data: {email: $("#email_address").val(),
submitted: true},
type: 'post'
});
request.done(function(response) {
//fooling around to see if this works
if(response) {
alert("valid email");
} else {
alert("invalid email");
}
});
request.error(function(response) {
alert("an error occurred");
});
});
});
However, the request.error function runs. I'm not too sure why. Here is the php code:
<?php
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo 'true';
} else {
echo 'false';
}
}
?>
Thanks in advance.
ugh, noob mistake. i had set the php url to be relative to the .js file instead of to the web page. it was supposed to be:
request = $.ajax({
url: 'verify_email.php'
instead of
request = $.ajax({
url: '../verify_email.php',
i figured it out with the use of Chrome's web inspector . i learned two new things today: what the url has to be relative to and how to use Chrome's web inspector. thanks all for your help
If your url work fine, in php try to return json ;)
<?php
$return = false;
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$return = true;
} else {
$return = false;
}
}
header('Content-Type: application/json');
echo json_encode(array('result' => $return));
die;
?>
And in javascript try:
request.done(function(response) {
//fooling around to see if this works
if(response.result) {
alert("valid email");
} else {
alert("invalid email");
}
});
I am building an inline code validation for a web form. With my current script, When a bad code is entered and it is being corrected (same length), POST data is not using the latest value. For example, I first enter "QFFE" and then correct it to "QFFF", but the latter is not stored in $_POST. See Firebug extract ("QFFF" passed but "QFFE" processed):
Here is the code (AJAX part):
var data = {};
$(document).ready(function() {
$('input[type="submit"]').on('click', function() {
resetErrors();
var url = 'process.php';
$.each($('form input, form select'), function(i, v) {
if (v.type !== 'submit') {
data[v.name] = v.value;
}
}); //end each
console.log(data);
$.ajax({
dataType: 'json',
type: 'POST',
url: url,
data: data,
cache: false,
success: function(resp) {
if (resp === true) {
//successful validation
alert("OK, processing with workflow...");
// $('form').submit();
return false;
} else {
$.each(resp, function(i, v) {
console.log(i + " => " + v); // view in console for error messages
var msg = '<label class="error" for="'+i+'">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(resp);
$('input[name="'+keys[0]+'"]').focus();
console.log('QD: error val');
}
return false;
},
error: function() {
console.log('there was a problem checking the fields');
}
});
return false;
});
});
function resetErrors() {
$('form input, form select').removeClass('inputTxtError');
$('label.error').remove();
}
And here my PHP script (process.php):
<?php
//List of accepted codes
$code_list = array("QWOLVE", "QFFF");
session_start();
if(isset($_POST)){
if (empty($_POST['promo_code'])) {
$_SESSION['errors']['promo_code'] = 'Please enter a promo code to access the beta site';
}elseif(! in_array($_POST['promo_code'], $code_list)){
$_SESSION['errors']['promo_code'] = $_POST['promo_code']." is not a valid code";
unset($_POST);
}
if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
// header('Location: redirect.php');
exit;
}
//This is when Javascript is turned off:
echo "<ul>";
foreach($_SESSION['errors'] as $key => $value){
echo "<li>" . $value . "</li>";
}
echo "</ul>";exit;
}else{
//Form validation successful - process data here:
echo json_encode(true);
}
}
?>
How can I make sure that the process.php is always using the latest form data?
I'm not sure why you store errors in the the session, but since you don't seem to clear that session, the next time you call the POST method $_SESSION['errors'] will still have the previous error in it (QFFE), hence the output.
I have created a form using ajax and php. The initial load and entering values into the form are all working fine, but where I am getting errors, is after the submit button has been pressed. Here is the markup for the form, and the ajax and php handlers:
relevant parts of form:
<form id="edit_time">
<!-----form fields here----!>
<button class="saveRecurrence" type="button" onclick="editTimeDriver('.$_GET['driver_id'].')">Save</button>
ajax part:
function editTimeDriver(driver_id) {
var time = "";
if (driver_id)
{
time += "&driver_id="+driver_id;
}
var data = $("#edit_time").serialize();
$.ajax({
url: "ajax.php?action=save_driver_event"+time,
dataType: "json",
type: "post",
data: data,
beforeSend: function()
{
$(".error, .success, .notice").remove();
},
success: function(json)
{
if (json["status"]=="success")
{
alert(json["message"]);
$("#edit_time")[0].reset();
}else{
if(json["error"]["date_from"]){
$("input[name=date_from]").after("<div class="error">"+json_time["error"]["date_from"]+"</div>");
}
}
}
});
}
This then passes to the php part which is:
$json = array();
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$date_from = tep_db_prepare_input($_POST['date_from']);
if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date_from)) {
$json['error']['date_from'] = 'Start Date is not valid!';
}
if (isset($json['error']) and !empty($json['error'])){
$json['status'] = 'error';
$json['message'] = 'Please check your error(s)!';
}else{
$json['status'] = 'success';
$json['message'] = 'Time Data has been successfully updated!';
}
}
echo json_encode($json);
Now for some reason, if the date_from field is left blank, and the form submitted, it doesn't come back with error message, instead it returns the success message. Can anyone tell me why it is not reading the errors?
Change your code by this one
onclick="editTimeDriver('<php echo $_GET['driver_id'] ?>'); return false;"
The return false statement prevent the form to be submitted using http (as you want to send an ajax request)
And You where doing something weird with your $_GET['driver_id']
Don't forget that php is running server-side