I hope this isn't a duplicate; the other similar questions I read didn't help me solve my problem.
I'm receiving a blank response (i.e. data = "") from a jQuery Ajax call to my PHP script, used to validate a user's submitted CAPTCHA value. I'm using Cryptographp for my CAPTCHA, and it works as expected, so I'm thinking it's most likely an error either in my Ajax call or the PHP script.
Firebug showing correct POST values ('code' is the submitted CAPTCHA value to test):
code a
email a#a.com
emailtext a
firstname a
lastname a
phone
Ajax function called onsubmit to determine whether or not to submit the form:
function validateCaptcha()
{
// Assume an invalid CAPTCHA
var valid = false;
// The form containing the CAPTCHA value
var data_string = $('form#emailform').serialize();
// Make the Ajax call
$.ajax({
url: "captcha.php",
data: data_string,
type: "POST",
async: false,
success: function (data) {
if (data == "true")
{
valid = true;
}
alert ("data: " + data);
}
});
return valid;
}
captcha.php
<?
$cryptinstall="crypt/cryptographp.fct.php";
include $cryptinstall;
// Begin the session
session_start();
//Check if CAPTCHA values match
if(chk_crypt($_POST["code"]))
return true;
else
return false;
?>
My expectation is that the above snippet should return a response of simply "true" or "false," but perhaps this is not the case.
Any help pointing out my error would be greatly appreciated!
You need to use "echo" instead of "return" and write is as a string. return is for returning results of functions.
<?
$cryptinstall="crypt/cryptographp.fct.php";
include $cryptinstall;
// Begin the session
session_start();
//Check if CAPTCHA values match
if(chk_crypt($_POST["code"]))
echo "true";
else
echo "false;
?>
From your captcha.php you are not echoing/printing anything so it's returning nothing. Just replace your return true; and return false; with echo.
Browser can only receive something when you'll print something from the script.
if(chk_crypt($_POST["code"])) echo true; // 1
else echo false;// 0
or
if(chk_crypt($_POST["code"])) echo 'true'; // true
else echo 'false';// false
Related
I have been using php and ajax to validate if an email inserted in my form exists in my database.
I am using jquery to send the email value to my php file and return a message if the email is found. My code is working fine but I want if an email is found the cursor be on focus on the #usu_email field until the email be changed. After this, it should allow me to continue to next field.
This is the jquery code I am using:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
success: function(data, textStatus) {
if (data !== null) {
$("#eresult").html(data);
$("#usu_email").focus();
}
},
});
};
My problem is that if and email does not exist in my database the cursor keeps doing focus on my #usu_email field and does not allow me to continue to next field.
I will appreciate any help about this problem because I know very little about jquery.
First... Your condition if (data !== null) always will be true since there always will be a data provided... Be it an empty string.
The only case where there will be no data is on Ajax error... And the condition won't even be evaluated because the success callback won't execute.
Next, I assume that your Ajax request is triggered on $("#usu_email") blur... Else, I don't know how you achieve «does not allow me to continue».
Modify it in this way to compare a response:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
datatype: "json",
success: function(data) { // There is only one argument here.
// Display the result message
$("#eresult").html(data.message);
if (data.email_exist == "yes") {
$("#usu_email").focus();
}
if (data.email_exist == "no") {
// Something else to do in this case, like focussing the next field.
}
},
});
};
On the PHP side, you have to provide the json response. It would look like something like this:
<?php
// You have this variable to compare against the database
$email = $_POST[usu_email];
// You say it is working.
// ...
// Then, you certainly have a result... Say it's $found (true/false).
// Build an array of all the response param you want to send as a response.
if($found){
$result[email_exist] = "yes";
$result[message] = "The submitted email already exist.";
}else{
$result[email_exist] = "no";
$result[message] = "A success message about the email here.";
}
// Add this header to the returned document to make it a valid json that doesn't need to be parsed by the client-side.
header("Content-type:application/json");
// Encode the array as a json and print it. That's what is sent in data as an Ajax response.
echo json_encode($result);
?>
Be carefull not to echo anything else. Not even a blank space or a line return.
Depends on what type of data you're expecting (simple text response or JSON), but at first i would start to replace your if(data !== null) with if(typeof data != "undefined" && data !== null && data != "") because the returned response might just be empty and not NULL.
If it doesn't work you should consider adding your php code to the question so we can figure out exactly what it returns when no matching email is found.
Ajax call is not working in entire site. But works fine in localhost. I cannot able to debug this issues.
I have used ajax entire website. I totally fed up.
Anyone please help me to fix this bug!!
One of my Sample Ajax Code:
function advanced_addTopic(cid) {
$.ajax({
url: "assets/php/checkSubtopicStatus.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {'cid':cid}, // Data sent to server, a set of key/value pairs (i.e. form fields
success: function(data) // A function to be called if request succeeds
{
if(data==="True"){
$("#subtopicDiv").html($("#subtopicDiv"+cid).html());
$("#advanced_testid").val(cid);
var hiddenCourse=$("#createTest").attr('class');
$("#courseHidden").val(hiddenCourse);
$("#advanced_addquestionModal").modal('show');
$("#subtopic").focus();
$("#question").focus();
var tempVal=$("#getID").text();
$("#advanced_courseHidden").val(cid);
} else {
alert("Create subtopics to insert questions!");
}
}
});
My PHP Code is here:
<?php
class loginValidation {
function validate()
{
ob_start();
session_start();
include "../../connection.php";
$id=$_POST['cid'];
$query = mysql_query("select * from advanced_subtopic where testid='$id'");
if(mysql_num_rows($query)>0) {
echo "True";
}
else {
echo "False";
}
}
}
$loginValidation=new loginValidation;
$loginValidation->validate();?>
My Concosole Log
CONSOLE RESPONSE
Instead of
(data==="True")
we should code like
($.trim(data)=="True")
Should trim the data to avoid unwanted space.
Problem solved.
I have a registration form for my website that requires a user to fill in ~6 fields, with their email as their username on the system. When a user registers, I want to first check if they are not already a registered user in our system, and if they are, redirect them to the login page. If they are not registered, registration should proceed to the registration page.
I've been trying to do this with the following ajax code, but it doesn't work - if the user is already registered, it still proceeds to the registration page:
function Chkreg()
{
var uemail = document.registration.email;
var not_reg;
$.ajax({
async: false,
type: "POST",
url: "chkreg.php",
data : "email="+uemail.value,
dataType: "json",
success: function (data) {
var success = data['success'];
if(success == false){
var error = data['message'];
alert(error);
window.location.href="login.php";
not_reg = false;
return false;
}
if(success == true) {
not_reg = true;
return true;
}
}
});//end ajax
return not_reg:;
}//end function
The form itself is defined as follows:
`<form name='registration' method="POST" action="registration/register.php" onsubmit="return Chkreg();">`
so, a false return from the Chkreg function should not post to register.php, but Chkreg() seems to always return true.
Any ideas how to fix it, or an alternate way to do this?
Because you're doing the ajax call with async:false, you don't need the return true or return false inside of it. That could be where things are going wrong, since you are returning from the anonymous function in the ajax call, not Chkreg(). Just returning not_reg outside of the ajax call will work.
That said, I would declare not_reg = false when you initialize the var. That way it's false until proven true. Or vice-y-versa -- I can't tell because of the negation in the variable name.
Also, inside of your (success == false) if-block, you are executing
window.location.href = "login.php";
which immediately redirects the user to login.php. You may want to alter the flow entirely and change the inline js for the form's onsubmit event
onsubmit="Chkreg(); return false;"
Then, inside Chkreg(), you could submit the form with javascript if they are not a registered user already.
Also, === and !== are preferred over == and != (especially when establishing if a variable is true or false, in case your values can be interpreted as truthy).
Lastly, Developer Tools are your friend (or Firebug). What response is the server giving when chkreg.php is being requested?
Check what the actual response is with firebug (or whatever your browsers dev kit)....I would be what you want is
if (success == "false") {
I've been on a problem for hours without finding any issue...
I have a registration form for users to create accounts. When the submit button is pressed a validateForm function is called.
In this function I do some javascript tests that work, but then I need to verify that the username is available. For this I created an external PHP file and call it using $.ajax.
Here is part of the code :
function validateRegistration(){
// Some tests....
// Check if username is already used
// Call external php file to get information about the username
$.ajax({
url: 'AjaxFunctions/getUsernameAjax.php',
data: "username=" + $("#username").val(),
success: function(data){
// Username already in use
if(data == "ko"){
// Stop validateForm()
}
// Username not used yet
else{
// Continue tests
}
}
});
// Other tests
}
My question is how can I make validateForm() return false from inside the $.ajax ?
Could I for instance declare a js variable before the Ajax part and set it with Ajax ?
I guess the answer is obvious but I'm absolutely new to Ajax and I can't get it...
Thanks a lot for your help!
To achieve this you can either do a synchronous ajax call like described in this answer, but that's something which is incredibly dangerous for the performance of your website.
Alternatively - and this is the right way - you should have an external variable whether the username is available, as soon as the user inputs something you do the request and if it's valid you change the variable otherwise you show an warning message. Next in your validateRegistration() function you only check the external variable (+ possible some form of callback, depending on where you call it from). The advantage being that the user can still continue doing things (like filling out the rest of the form) whilst the request is pending.
You could make a synchronous ajax call, instead of an asynchronous, as you're doing now. This means that the Ajax call will complete before the next lines of code are executed.
To do so in jQuery, just add async: false to your request object:
var someVariable;
$.ajax({
url: 'AjaxFunctions/getUsernameAjax.php',
data: "username=" + $("#username").val(),
success: function(data){
// Username already in use
someVariable = "something";
if(data == "ko"){
// Stop validateForm()
}
// Username not used yet
else{
// Continue tests
}
},
async: false
});
alert(someVariable); // should alert 'something', as long as the ajax request was successful
In the php, if you print out JSON like:
echo json_encode(array("ko"=>"good"));
shows up as:
{
"ko":"good"
}
then in the function it would be
if(data.ko == "good"){
//do stuff
}
This is how I normally do it. You can get the variable by using the name you used in the JSON so you can have other things if you need.
If the goal is to check a username availability, how about checking it as or just after the username is typed in. For example you could either bind it to the keyUp event for keystrokes or the blur event for when you leave the text box.
This would mean that by the time the user gets to the submit button, that part of the form would already be validated.
The traditional solution here is to pass a callback function to validateRegistration which expects a boolean value. Have the Ajax function call the callback function when it completes.
The onsubmit handler expects a return value immeidately, so performing an asynchronous test within your submit event handler is a fairly unituitive way to do things. You should instead perform the test as soon as possible (e.g. as soon as the user enters a username) and then store the result of username validation in a global variable, which is later checked at submit time.
// global variable indicating that all is clear for submission
shouldSubmit = false;
// run this when the user enters an name, e.g. onkeyup or onchange on the username field
function validateRegistration(callback) {
shouldSubmit = false;
// number of ajax calls should be minimized
// so do all other checks first
if(username.length < 3) {
callback(false);
} else if(username.indexOf("spam") != -1) {
callback(false)
} else {
$.ajax({
....
success: function() {
if(data == "ko") {
callback(false);
} else {
callback(true);
}
}
});
}
}
Now call validateRegistration with a function argument:
validateRegistration(function(result) {
alert("username valid? " + result);
if(result) {
$("#username").addClass("valid-checkmark");
} else {
$("#username").addClass("invalid-xmark");
}
shouldSubmit = result;
});
Now use the global variable shouldSubmit in your form's submit event handler to optionally block form submission.
I've never done this before, and I haven't found much help on Google or StackOverflow yet.
Here's what I have: A password input:
<input type="text" placeholder="password" name="pass" id="password" />
and some jQuery to check the password:
<script>
$('form').submit(function(){
input = $('#password').val();
var finish = $.post("pass.php", { request: "opensesame" }, function(data) {
return (input==data) ? true : false;
});
if(finish){
alert('sent');
}else{
alert('not sent');
}
return false;
});
</script>
And a password-dispensing php page (pass.php):
<?php
if(isset($_POST['request'])&&$_POST['request']=="opensesame"){
echo 'graphics';
}
?>
Now, I can get it to alert 'graphics', but I can't get it to match the data with the input value to check if it's the right password or not.
What am I doing wrong, and what are the potential dangers to authenticating a password in this way?
The "A" in "AJAX" stands for asynchronous.
The code after you call $post will execute before the contents of the $post function. The value of finish will always be a jqXHR object, the result of (input==data) ? true : false will be ignored.
More clearly:
var finish = $.post("pass.php", { request: "opensesame" }, function(data) {
// THIS EXECUTES SECOND, and the return value is discarded
return (input==data) ? true : false;
});
// THIS EXECUTES FIRST, with finish set to a jqXHR object
if(finish){
...
You need to rethink your methods of password checking, or use synchronous postbacks by adding the following before your $.post calls:
$.ajaxSetup({async:false});
Or by using $.ajax and passing async: false:
jQuery.ajax({
type: 'POST',
url: "pass.php",
data: { request: "opensesame" },
success: function(result) { ... },
async: false
});
The first thing to do would be to clean up the code, it's too obscure, I'm afraid.
I'd write it as follows:
<script>
$('form').submit(function(event){
event.preventDefault(); // stop the form from submitting
var passwd = $('#password').val();
var finish = $.post("pass.php", { request: passwd }, function(data) {
if(data){
alert('Success!');
}else{
alert('Failure :(');
}
});
});
</script>
Things to note here:
AJAX POST is asynchronous, you can't check for a variable right after changing it in the callback, you need to process stuff inside the callback.
You must verify the password on the server, not in javascript!!
Adding to the previous bullet, don't write your password inside the javascript!
And on the server:
<?php
if(isset($_POST['request']) && $_POST['request']=="opensesame"){
echo 'true';
}else{
echo 'false';
}
?>
Things to note here:
You used isset() to check for the existence of the variable, good call. Keep doing it.
jQuery POST expects a javascript value from the server (unless you tell it otherwise).
This is why my code prints either 'true' or 'false', this translates to a boolean value in javascript.
I would advise returning an object with error details, such as the one below:
<?php
$result = array('success'=>false, 'reason'=>'Unknown error.');
if(isset($_POST['request'])){
if(trim($_POST['request'])!=''){
if($_POST['request']=='opensesame'){
$result['success'] = true;
$result['reason'] = 'Welcome home!';
}else $result['reason'] = 'Password is wrong';
}else $result['reason'] = 'Password must not be empty';
}else $result['reason'] = 'Expected parameter "request"';
echo json_encode($result);
?>
You have to serialize your input fields to all the data to your script:
$.post("pass.php", { request: $('form').serialize() }, function(data) {
// ...
As long as you are on your own server I don't see much potential dangers, as it sends a POST-request which a normal form would do anyway.
Its quite unsafe to send data like this, anyone can intercept and read the data which you send by ajax and the value returned by ajax using firebug or other such tools. So you should serialize or sanitize the fields and also encrypt the data before sending them.
& the code to alert after checking finish will be executed before the response comes from ajax (note that it is asynchronous) thus you would get an object stored in the finish variable.