I'm using the jQuery Form plugin to submit AJAX requests. It's a simple contact from using this PHP script: http://pastie.org/725652 - the only validation happens inside the PHP.
Here's my Javascript code to trigger the whole thing:
$('#contactform').ajaxForm({
target: '#error',
beforeSubmit: function() {
$('#error').append('<p class="loading">Sending your message...</p>');
},
success: function() {
$('#error p.loading').fadeOut();
$('#error').fadeIn('slow');
}
});
Unfortunately, it doesn't seem to work. The PHP works perfectly, sends the email and returns the success message, but the AJAX magic isn't working for some reason. Obviously what I want to achieve, is to display the message returned by the PHP script via AJAX in the <div id="error />
I used the same script many times and never had any problems with it, now I can't figure out why it doesn't work. Here's the markup for the contact form.
<form id="contactform" class="group" method="post" action="submitemail.php">
<fieldset>
<div><label for="first-name">First Name</label>
<input type="text" name="first-name" value="Jeremy" /></div>
<div class="alt"><label for="last-name">Last Name</label>
<input type="text" name="last-name" value="Anderson" /></div>
<div><label for="email">E-mail <span>(never published)</span></label>
<input type="text" name="email" value="jeremyanderson#mywebsite.com" /></div>
<div class="alt"><label for="url">Website</label>
<input type="text" name="url" value="http://www.mywebsite.com" /></div>
<label for="question">Message</label>
<textarea name="question" id="" cols="30" rows="10">Thinking of something to say...</textarea>
<input type="submit" name="submit" id="submit" value="Send E-mail" />
<div id="error"></div>
</fieldset>
</form>
Here's the code of the jQuery plugin if it can be any help. http://pastie.org/726175
If anyone could look at the whole thing and provide some tips why would it not work, I would be very grateful, thanks in advance!
you must include the parameters in which are the response from PHP:
EDIT:
try with these changes, in this example I'm separating the message "loading" with the response message.
HTML:
<form id="contactform" class="group" method="post" action="submitemail.php">
<fieldset>
<!-- fields -->
<input type="submit" name="submit" id="submit" value="Send E-mail" />
<div id="error"><span id="eloading"></span><span id="eresponse"></span></div>
</fieldset>
</form>
Javascript:
$('#contactform').ajaxForm({
target: '#eresponse',
beforeSubmit: function() {
$('#eresponse').hide('slow');
$("#eloading").append("<p class=\"loading\">Sending your message...</p>");
},
success: function(responseText, statusText) {
alert("test status: " + statusText + "\n\nresponseText: \n" + responseText);
$("#eloading").empty();
$('#eresponse').show('slow');
}
});
It didn't do the trick :( It still
goes to the submitemail.php file with
the success message instead of showing
the message in #error. – Justine 39
mins ago
If this happens that means the function attached to the submit event didnt end with
return false;
i beleive with ajaxForm this is done automagically so that means there is an error in your code somewhere. If you dont have firebug installed, install it and keep an eye on the console make sure:
jquery is loading ok
there are no
errrors setting up the ajax
interaction or in any other js on
the page that may stop it
Related
Trying to implement a recaptcha on my Contact form for my website and I'm having trouble getting anything to go through unless I set the score to 0.0. Even 0.1 kicks it over to spam. There are so many examples of how to implement, and I've tried several of them but not had any luck (as several are for different versions too, which makes it hard for us noobs).
In any event, here is a stripped down version of the form html page I'm trying to use:
<head>
<script src='https://www.google.com/recaptcha/api.js?render=KEY'></script>
</head>
<body>
<form name="contactform" action="send_form_email.php" method="post">
<div class="input-group">
<span class="input-group-label">Name</span>
<input name="realname" class="input-group-field" type="text" value="Your Name Here" maxlength="50" onFocus="this.value=''">
</div>
<div class="input-group">
<span class="input-group-label">Email</span>
<input name="email" class="input-group-field" type="email" value="Your E-Mail Here" maxlength="50" onFocus="this.value=''">
</div>
<div class="input-group">
<span class="input-group-label">Message</span>
<textarea name="message" rows="10"></textarea>
</div>
<input type="Submit" class="button" value="SEND"><input type="Reset" class="button" value="RESET">
</form>
<script>
$(function(){ //wait for document ready
grecaptcha.ready(function() {
grecaptcha.execute('KEY', {action: 'contactUs'}).then(function(token) {
// Verify the token on the server.
});
});
});
</script>
</body>
So then I have a PHP form called send_form_email.php that I'm using to take care of all the hard work:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'SECRET_KEY';
$recaptcha_response = $_POST['g-recaptcha-response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->score >= 0.0) {
// This is just where I take care of formatting the email and sending it to me, which is working just fine... well while the score is set to 0.0
}
} else {
// otherwise, let the spammer think that they got their message through
header('Location: success.htm');
exit();
}
}
?>
So this is where I run into my issue. In the code above I have it set to 0.0 and that is the ONLY way right now emails come through at all. But of course this lets through spam or real messages because it's basically off. As I said, if I set it to even 0.1 it isn't passing the score check and is never sending the email. I'm sure it's something simple that I'm missing or I'm not passing the information correctly or something, but the google documentation isn't very helpful. So I'm hoping someone can point out what I've missed?
Thanks!
Finally found an answer here that gave me exactly what I was looking for. Some simple example code that works! (why can't google do that?) It wasn't listed as the 'accepted' answer, it is the one below that but the accepted answer just tosses you toward a git that is ridiculously confusing for noobs.
Here is my edited my code above from above:
<head>
<script src='https://www.google.com/recaptcha/api.js?render=YOUR_KEY_HERE'></script>
</head>
<body>
<form name="contactform" action="send_form_email.php" method="post">
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
<input type="hidden" name="action" value="validate_captcha">
<div class="input-group">
<span class="input-group-label">Name</span>
<input name="realname" class="input-group-field" type="text" value="Your Name Here" maxlength="50" onFocus="this.value=''">
</div>
<div class="input-group">
<span class="input-group-label">Email</span>
<input name="email" class="input-group-field" type="email" value="Your E-Mail Here" maxlength="50" onFocus="this.value=''">
</div>
<div class="input-group">
<span class="input-group-label">Message</span>
<textarea name="message" rows="10"></textarea>
</div>
<input type="Submit" class="button" value="SEND"><input type="Reset" class="button" value="RESET">
</form>
<script>
$(function(){ //wait for document ready
grecaptcha.ready(function() {
grecaptcha.execute('YOUR_KEY_HERE', {action: 'contactUs'}).then(function(token) {
// Verify the token on the server.
document.getElementById('g-recaptcha-response').value = token;
});
});
});
</script>
</body>
Then the revised PHP form called send_form_email.php that I'm using to take care of all the hard work:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'YOUR_SECRET_KEY';
$recaptcha_response = $_POST['g-recaptcha-response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url.'?secret='.$recaptcha_secret.'&response='.$recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->score >= 0.5) {
// Basically if the score is equal to or better than the above, you have a good one and can send your email off and this is just where you would do that
}
} else {
// otherwise, let the spammer think that they got their message through
header('Location: success.htm');
exit();
}
}
?>
I've got it showing a 0.5 score for now, but you should of course check your admin on google and see what scores you are getting and adjust as needed.
I have written a HTML form and script to validate the form. The issue is that whenever I go to submit the form I get redirected to a page that tells me "Your file was not found".
Is there a specific way I have to call the script? or any way I can force it to run without redirecting me?
<form id="bioform" action="/action_page.php">
<label>Biography</label><br>
<textarea placeholder="Enter bio here" name="bio" rows="10" cols="50"></textarea><br><br>
<label>Update Biography Picture</label><br><br>
<input type="file" name="bioimage"><br><br>
<button type="submit" onclick="function()">Update</button><br>
</form>
<script>
$(document).ready(function () {
$('#bioform').validate({
rules: {
bio {
required: true,
minlength: 5,
},
}
messages: {
bio {
required: 'Please enter a biography.',
minlength: 'Please enter a valid biography.',
},
}
});
});
</script>
Add enctype="multipart/form-data" to form tag
<form id="bioform" action="/action_page.php" enctype="multipart/form-data">
<label>Biography</label><br>
<textarea placeholder="Enter bio here" name="bio" rows="10" cols="50">
</textarea><br><br>
<label>Update Biography Picture</label><br><br>
<input type="file" name="bioimage"><br><br>
<button type="submit" onclick="function()">Update</button><br>
</form>
Is the forward slash when specifying where it sends to necessary? For instance:
<form id="bioform" action="/action_page.php">
Should be replaced with:
<form id="bioform" action="action_page.php">
Since you're using jQuery, try using this:
e.preventDefault()
The e.preventDefault() method stops the default action of an
element from happening. For example: Prevent a submit button from
submitting a form. Prevent a link from following the URL.
Also, you need to add method attribute inside the <form> tag with value POST and also the enctype="multipart/form-data" since you're dealing with file upload.
Go to this fiddle and check if it works for you: https://jsfiddle.net/z0db4vq0/1/
I am new to web designing. Now, I have created a form, and if the user input doesn't meet the requirements I display error message, and if it does I do some mysql commands to enter the info to the database. Now one way to do this is to code the php file into the html and use this command,<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> like described [here][1]
But I don't want to put the script in the same file. How do I do that in another php file such that if user input is invalid, it will return to the homepage with the error message updated?
Here is my code
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="register.css">
</head>
<h1>Register as A new user</h1>
<div id="signup">
<form id="registration_form" action="registration.php" method="post">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
<span class="errorMessage"></span>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
</div>
What should be in the registration.php? Like the link, I do everything, I set a flag to the error, Now if the flag is true I return the user to the homepage with the error messages, and if false, I show a message saying registration successful. How do I do the part,"return to homepage with the appended error message"?
All your validation and bulletproofing should be in the registration.php
stuff like this:
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['name'])) {
die('Must pass \'name\');
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['email'])) {
die('Must pass \'email\');
}
if(!isset($_GET['passwd'])) {
die('Must pass \'password\');
} else {
//do cool stuff here
}
Don't forget your JS validation as well for the front end. I really hope this helps and gives you a bit of direction.
put your validation codes in "validate.php" or any file name you like
then change the action to validate.php to
then in validate.php if validation matches the requirements.
header("Location: registration.php");
if not match
header("Location: back to the httml with form.php");
You can learn form validation here : http://allitstuff.com/registration-form-in-php-with-validation/
I have this in my PHP code, and it currently does the login request in the same login.php page but now i want to do it with Ajax. Basically I have this in the login.php
echo '<form method="post" ><div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" name="submitlogin" class="button" />
</div>';
I would like to still use this but have a login_request.php or something where i can send the username and password validated and then change the <div id=login> to say you are logged in!</div> I can do it the conventional way, with the form post .. but now I would like to try it with Ajax.
Any help will be much appreciated.
Regards
What have you tried so far? This is how I would start:
This should get you started:
HTML:
<form id="loginForm">
<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="button" value="Submit" id="submitlogin" class="button" />
</div>
</form>
jQuery:
$("#submitlogin").click(function() {
inputs = //grab then inputs of your form #loginform
$.ajax ({
url: "urltoyourloginphp.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
}
});
})
I wrote this a while ago, it's not quite a full ajax login (i.e. at the end it does still redirect you), but it may serve as a basis for a full ajax login. As a plus you actually don't need https (that was the whole point of this little project).
https://github.com/eberle1080/secure_http_login/blob/master/login.php
The high level steps go something like this:
Ask the server for a seed value (a salt) using an ajax request
Hash the password + seed using a sha1 sum
Ask the server to verify the username and salted + hashed password
If it's valid, the server sets a session cookie indicating that the user is logged in
The server responds to the ajax request with a success / fail message
jQuery has built in .post() and .serialize() methods for wrapping up a form.
$.post("login.php", $("#loginForm").serialize(), function(data) {
//pass information back in with data. if it's JSON, use $.parseJSON() to parse it.
alert('either logged in or errored');
);
You will also need to edit your form so it has an id, like: <form id="loginForm">...
I don't know PHP but will give you an example of how I would have done it with vbscript (classic asp) so you may try to adapt it to PHP as needed.
I, in my applications, don't use the form tag since I first used ajax. So, here we go:
login html page:
include jquery
<script type='text/javascript' src='your-jquery-url'></script>
<script type='text/javascript'>
function tryLogin() {
var inputs='userName='+$('logInUsername').val()+
'&userPassw='+$('logInPassword').val();
//notice that I changed your name= to id= in the form
//notice the '&' in the '&userPassw=
$.post('your-login-validation-page',inputs,function(data) {
eval('var json='+data);
if (json['success'] == 'true') {
$('#loginForm').html('<p>Congratulations! You\'ve been logged in successfully</p>')
} else {
alert(json['errorMessage']);
$('#logInUsername').focus();
}
});
}
</script>
<div id='loginForm' >
<label for="login">User Name</label>
<input type="text" id="logInUsername" />
<label for="Password">Password</label>
<input type="password" id="logInPassword" />
<button onClick='tryLogin(); ' >LOGIN</button>
</div>
login-validation-page
[in vbscript]
user = request.Form("userName")
passw = request.Form("userPassw")
"if is there this user" (coded as if there was a database look up...)
"if the password = passw" (coded as comparing the values)
response.write "{'sucess':'true'}"
else
response.write "{'success':'false','errorMessage':'wrong password'}"
end if
else
response.write "{'success':'false','errorMessage':'user not found'}"
end if
---> end of login-validation-page
When i click my login button, it just reloads the page for some reason. it should alert the string i echo from my php page.
This is my login.js code:
$(document).ready(function(){
$('#login').click(function(){
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
$.post('login.php',{username:"bob",password:"pass"}, function(data){
alert(data);
});
});
});
my login.php:
<?php
echo "message";
?>
and my form:
<form id="loginForm" action="" method="post">
<fieldset id="body">
<fieldset>
<label for="username">Username</label>
<input type="text" name="username" id="username" />
</fieldset>
<fieldset>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</fieldset>
<button id="login">login</button>
<label for="checkbox"><input type="checkbox" id="checkbox" />Remember me</label>
<br />
<p id="msgLoginStatus" style="display:none"></p>
</fieldset>
<span>Forgot your password?</span>
</form>
There are no errors in browser console. I tried this also using $.ajax, it returned an error, i tried putting the error variable in an alert, but when it alerted, it was an empty string. Anyone have an idea whats wrong?
Your login button has an ambiguous action - add type="submit" like this:
<button id="login" type="submit">Login</button>
Now if you really want to execute an explicit POST with JavaScript, call e.preventDefault so the browser's automatic "submit" action will be suppressed.
e.preventDefault();
$.post(...);
But it will probably be better to let the form submit itself. To do this specify the correct action="login.php" attribute in the form:
<form id="loginForm" action="/login.php" method="post">
Keep your existing "click" handler on the login button, just remove the "$.post" part and let the browser handle the posting. You'll still get the nice "processing..." text.
Even better, handle the "submit" event on the form instead of the "click" event on the button:
$('#loginForm').submit(function(e) {
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
});
This way you'll get the nice updates whether the user submits the form using the button or by pressing "enter" on the keyboard.
Try:
$('#login').click(function(e){
e.preventDefault();
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
$.post('login.php',{username:"bob",password:"pass"}, function(data){
alert(data);
});
});
That prevents a "normal" submit from happening (which, I take, is why you are not getting any errors).
See http://api.jquery.com/event.preventDefault/
Add e.preventDefault(); to the clck handler (and grab the event object in the handler as e).
Or you can Just set the button type = 'Button' and not Submit. THis will also run your code
<button id="login" type="button">Login</button>
In this way you don't have to halt the browser's event