Print PHP message to form through Ajax/Jquery - php

I have a jquery/bootstrap form. My php is checking against the database if an email address is already in use.
If the email address is in use, the following is called but to a new window.
echo'<p class="error">An account already exists for this email address. Please use a different email address</p>';
This all works fine but now I want the error message to show up on the Jquery form. I can't seem to wrap my head around how to do this.
I know I have to use this handler, but I don't know where to put the error message or how this code knows which error message to read from the php. Additionally, I would like the error message to show up next to the email field of the form
$(document).ready(function() {
$('#form').submit(function() {
$.ajax({
type: 'POST',
url: "process.php",
data: dataString,
success: function() {
}
})
return false;
});
});

Processing the error message can be performed in the success property. The function can accept a data argument (the response from process.php).
success: function(data){
//does data contain p.error?
//get the contents of p.error, display it on the current page
//for example:
if( $(data).find("p.error.name").length ){
//process name error here
nameError = $(data).find("p.error.name").text();
console.log(nameError);
}
if( $(data).find("p.error.email").length ){
//process email error here
emailError = $(data).find("p.error.email").text();
console.log(emailError);
}
}
The success function defined above assumes process.php looks something like this:
<div>
<p class="error name">Please enter a name.</p>
<p class="error email">Your email address is invalid.</p>
<!-- some other stuff here -->
</div>

Related

Return success/failure variable with ajax from php script

I'm a really new coder and struggling with a task I'm now working on and trying out for days.
I searched Google and Stack Overflow but can't find a (for me understandable) solution to my problem:
I created a Twitter Bootstrap landing page and there a modal shows up when clicked. In this modal I have a form with a newsletter subscription:
<form id="newsletter" method="post">
<label for="email">Email:</label><br/>
<input type="text" name="email" id="email"/><br/>
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
Now I want to insert the data into a mySQL DB and do some basic validation that returns errors or a success message. The script works fine without ajax, but probably needs alterations on what it returns for ajax?
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
}
if($error) {
$error= "There was an error in your signup,".$error;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
}
}
}
After a lot of reading ajax seems to be the way to do it without the bootstrap modal closing after submit (to suppress default event).
The insertion into the DB works fine, also the validation.
But I can't manage to get the different error messages displayed (stored in the $error variable of the php file) or alternatively the $message in case of success.
This is the jquery script:
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
data: {email: $("#email").val()},
success: function(message) {
$("#result").html(message);
},
error: function(error) {
$("#result").html(error);
}
});
I try to display the value of the error and message variable in the php script within the #result span.
Any help is appreciated. Please formulate it very straight forward since I'm really new to this field.
Thank you a lot in advance.
Edit:
Added some to the php file to create an array and store the messages within:
$response = array();
$response['success'] = $success;
$response['error']= $errors;
exit(json_encode($response));
But have still some trouble to get the ajax to work. Tried the shorthand $.post instead of $.ajax but can't them now even to get to work posting data...
$("#sub").submit(function (){
event.preventDefault();
$.post("newsletter.php", {email: $("#email").val() });
});
Quick time is much appreciated. I'm stuck after hours of testing and can't find the error. If I submit the form regularly it works fine, so the php/mysql part isn't the problem.
I also realized that when I click the "#sub" button, it still tries to submit the form via get (URL gets values passed). So I'm not sure if the event.preventDefault(); isn't working? jQuery is installed and working.
The $.ajax error function gets called when there is a connection error or the requested page cannot be found
You have to print some text out with the php and the ajax success function gets this output. Then you parse this output to see how it went.
The best practice is this:
php part:
$response = array();
$response['success'] = $success;
$response['general_message'] = $message;
$response['errors'] = $errors;
exit(json_encode($response));
js/html part:
$.post("yourpage.php", a , function (data) {
response = JSON.parse(data);
if(response['success']){
//handle success here
}else{
//handle errors here with response["errors"] as error messages
}
});
Good luck with your project
You need to echo your messages back to your AJAX. There is no place in you PHP code where the messages are going back to the message variable in your AJAX success.
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
echo $error; die;
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
echo $error; die;
}
if($error) {
$error= "There was an error in your signup,".$error;
echo $error; die;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
echo $error; die;
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
echo $message; die;
}
}
}
I basicly just had the same case. I structured my code a little bit different but it works so...
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
dataType: 'json',
data: {email: $("#email").val()},
})
.success(function(message) {
$("#result").html(message);
}),
.error(function(error) {
$("#result").html(error);
})
on server side I used C#(asp.net) and just returned a Json
return Json(new { Message = "Something...", Passed = true}, JsonRequestBehavior.AllowGet);
Oukay, finally I managed to solve the problem with the great inputs here. I did the following:
PHP:
$response = array();
$response['success'] = $success;
$response['error'] = $error;
exit(json_encode($response));
JS:
$("#newsletter").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'newsletter3.php',
method: 'post',
data: {email: $('#email').val()},
success: function(data) {
var response = JSON.parse(data);
console.log(response);
if (response['success']) {
$("#error").hide();
$("#success").html(response['success']);
$("#success").toggleClass("alert alert-success");
} else {
$("#error").html(response['error']);
if(!$("#error").hasClass("alert alert-danger"))
$("#error").toggleClass("alert alert-danger");
}
}
});
});
The functionality is now that you click on a button and a modal pops-up, then you can enter your email and the php script validates if its valid and if it's already in the db. Error and success messages get JSON encoded and then are displayed in a span that changes color according to bootstrap classes danger or success.
Thank you very much for helping me, I'm very happy with my first coding problem solved :)
I use this on my ajax
request.done(function (response, data) {
$('#add--response').html(response);
});
and this on the PHP
die("Success! Whatever text you want here");

Prevent Email Spam after using reCaptcha

All,
I've got a form on my page that I use to send emails. On the form page I have the following code:
<input type="text" name="Name" id="your_name" class="contact_form_input_text">
<input type="text" name="Email_Address" id="your_email" class="contact_form_input_text">
<input type="text" name="fill_me_out" id="fill_me_out">
<input type="button" value="Send" id="submit_contact_form_button">
The first text box is a lamecaptcha and I check it on the PHP side to make sure that it wasn't filled out. I also hide it using some JS with this:
jQuery(function(){
jQuery("#fill_me_out").hide();
});
I then have the following form validation before my page submits using jQuery validator:
jQuery("#contact_form").validate({
rules: {
Email_Address: {
required: true,
email: true
},
Name: {
required: true
}
},
messages: {
Email_Address: {
required: "Please enter an email address!",
email: "Please enter a valid email address!"
},
Name: {
required: "Please enter your Name!"
}
}
});
jQuery("#submit_contact_form_button").click(function(event) {
if (jQuery("#contact_form").valid()) {
challengeField = jQuery("input#recaptcha_challenge_field").val();
responseField = jQuery("input#recaptcha_response_field").val();
var html = jQuery.ajax({
type: "POST",
url: site_url + "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html == "success")
{
//$("#captchaStatus").html(" ");
// Uncomment the following line in your application
//return true;
jQuery("#contact_form").submit();
}else{
jQuery("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
return false;
});
If everything is filled out correctly the page then submits. I have the following check to check the lame captcha:
$lamecaptcha_check = $_POST['fill_me_out'];
if($lamecaptcha_check!=""){
echo '[box style="alert"]Why are you trying to spam us? It could be because you don\'t have Javascript enabled and filled out an incorrect box![/box]';
}else{
//Send the form using mail
}
To submit the form is a button and not a submit so it has to go through the jquery validation to do even be submitted. Somehow I'm still getting blank email messages to come through. Does anyone know anything else I can possibly do to prevent spam/blank email messages? I was thinking I should check the variables on the back end to make sure they are not blank but the form shouldn't even be submitted unless there are some values so I require a valid email address on the initial page. Any ideas are appreciated!
Thanks!
Just because you have a submit button go through jQuery to work, doesn't mean the form can't be submitted otherwise.
A spambot would probably examine the HTML of your form, look at the different fields, and then just send a POST request with the relevant information. It will not evaluate your jQuery.
If you want to do something like this, set the form's action="javascript:;", then update it in your jQuery to the actual value right before submitting.

Unable to simultaneously POST and JSON with ajax jquery

I suspect that this might be a server issue, but since I do not have access to our server, I was hoping maybe someone else had a fix or could explain to me exactly what is causing the problem.
The problem ....
Using JQuery AJAX I am unable to simultaneously POST data to a php file and receive json encoded data from the php file. If the json dataType is included I am unable to POST data from the form to the php file. If I do not specify the json dataType (i.e. comment it out) then I can POST data to the php file but cannot receive the json encoded data.
I've tried this with my own js/php code and for source code that I downloaded, in order to compare results in case it was just a mistake in my coding. Both are 'submit forms' and both exhibit the problems outlined above. In case its relevant, I include the downloaded source code below. My js/php code uses similar ajax requests.
javaScript:
<script type="text/javascript">
$(document).ready(function(){
$("#myForm").submit(function(){
dataString = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "postForm_ajax.php",
data: $("#myForm").serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg){
$("#formResponse").removeClass('error');
$("#formResponse").addClass(msg.status);
$("#formResponse").addClass(msg.status);
},
error: function(){
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>
the PHP:
<?php
//function to validate the email address
//returns false if email is invalid
function checkEmail($email){
if(!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
//if(eregi("^[a-zA-Z0-9_]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = explode("#",$email);
if(#getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(#fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
//response array with status code and message
$response_array = array();
//validate the post form
//$name = $_POST['name'];
//check the name field
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
//check the email field
} elseif(!checkEmail($_POST['email'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
//check the message field
} elseif(empty($_POST['message'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
//form validated. send email
} else {
//send the email
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail($_POST['email'], "SUBJECT LINE", $body);
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
?>
EDIT....One Solution
Ok...so I found a hack that works. I don't specify the dataType:'json', i.e. comment that line and the contenType line out. Then I'm able to POST the data. Still have the php file echo the json_encode($response_array). Then put the following code in the success function
var obj = jQuery.parseJSON(msg);
$("#formResponse").addClass(obj.status);
$("#formResponse").html(obj.message);
This is not as nice as being able to specify the dataType:'json' in the ajax call. If anyone has a better solution or can explain why this problem is occurring, let me know.
Thanks
According to me you are doing nothing wrong... except you are specifying to many things...
For eg:
dataType: "json",
is sufficient for ajax call to work.... there is no need for
contentType: "application/json; charset=utf-8",
in your code, if you add this line it returns the empty array in return for some reason (not very sure about the actual reason)....
But moment I specify just
dataType: "json",
it works like a charm where in return I get the object, which I need not parse.
edit:
What I tried is as followring... just change the input name to fname from name and it worked very well
<form id="myForm" name="myForm" method="POST"
action="postform_ajax.php">
name: <input type="text" name="fname" /> <br /> email: <input
type="text" name="email" /> <br /> message: <input type="message"
name="message" /> <br /> <input type="submit" />
<div id="formResponse"></div>
</form>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#myForm").submit(function() {
dataString = $("#myForm").serialize();
$.ajax({
type : "POST",
url : "postForm_ajax.php",
data : $("#myForm").serialize(),
dataType : "json",
success : function(msg) {
$("#formResponse").removeClass('error');
$("#formResponse").addClass(msg.status);
$("#formResponse").html(msg.status);
},
error : function() {
console.log('err', msg);
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>

No Ajax response even though PHP file set up correctly

I have a simple sign up mailing list form. It sends the user's email address to a store-address.php file. I use jQuery's ajax object to send a request to the php file and then receive a response.
The problem is I am not getting a response from the php file. I tried setting the cache to false in the request. I also tried send the information through the URL like so:
http://www.fifthtribe.com/inc/store-address.php?ajax=true&cache=false&email=test4%40gmail.com
When I do it that way it works and gives me a reponse. But when I do it through ajax it doesn't give me a response. This is from Firebug:
And here's snippets from my code:
HTML:
<div id="mlist">
<form id="mlist_form" method="POST" action="">
<input type="text" id="email" name="email" placeholder="Email" />
<input type="submit" id="submit_btn" value="Join" />
</form>
<div id="response"></div>
</div>
JQuery:
/* Add to mailing list */
$("#mlist_form").submit( function(e){
//$('#response').append('<div id="thanks-mce"><div id="mce-arrow"></div>Thanks for signing up!</div>');
var email = escape( $('#email').val() );
e.preventDefault();
data = {
"ajax" : "true",
"email" : email,
"cache" : "false"
}
$.ajax({
type: "POST",
url: 'inc/store-address.php',
data: data,
success: function( msg ){
// successfully signed up
$('#response').html( msg );
$('#email').val('');
},
error: function( err ){
// error while signing up
$('#response').html('Error: Is your email correct?');
}
});
return false;
});
PHP:
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us4');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "xxxxxxxx";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
You realize that your PHP script is using GET method but your jQuery code is using the POST method right?
If the information is being posted to PHP, PHP will need to use $_POST to retrieve it. This explains why the URL method using $_GET works but the jQuery POST doesn't.
Good luck!
It looks like you're using $_GET instead of $_POST. Try echoing out the contents of $_REQUEST to see what that holds.
Debug your script!
Place an alert in the success and error parts of your script and then you will know whether the AJAX is working.
If not, you can then work your way up the document and see where the problem is.
In addition, the error here is quite simple. You are using $_GET in PHP and you are POSTING your data using AJAX, this will not show an error. Although the PHP document will not process your request because it is not being fed any parameters.

jQuery to database - registration form with validation

I find this tutorial in 9lessons.com : http://www.9lessons.info/2011/01/gravity-registration-form-with-jquery.html
It's about a registration form with validation.
I want to send data to DB.
// Submit button action
$('#submit').click(function()
{
var email=$("#email").val();
var username=$("#username").val();
var password=$("#password").val();
if(ck_email.test(email) && ck_username.test(username) && ck_password.test(password) )
{
$("#form").show().html("<h1>Thank you!</h1>");
///// if OK
///// Show thanks
//// else
//// Error, try again
}
return false;
});
How can I do ?? I searched in internet in jQuery tutorial and I find much codes ...
This tutorial will walk you the entire process:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
It implements jQuery.post and calls a PHP script that will allow you to process the data.
You will need to use Ajax to submit the data to a backend script (such as PHP) to do the actual database interaction. I'd recommend using POST:
http://api.jquery.com/jQuery.post/
you can use jquery post method
$.post("test.php", $("#testform").serialize());
or for more detail visit this link
jquery form post method
Finally I inserted data form to database... I have a problem.. I forgot to verify if email is available or not !
I added this lines from an other tutorial in email verification to test if email exist in DB or not.
First I send email to check_availability.php
if mail exist an error message appear else, the password fiel must appear ...
Like you see in picture, I verify the existence of an email adress and availibality and unavailability message appear but not correctly ...
$('#email').keyup(function()
{
var email=$(this).val();
if (!ck_email.test(email))
{
$(this).next().show().html("Enter valid email");
}
else
{
//$(this).next().hide();
//$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
$.ajax
({
type: "POST",
url: "user_availability.php",
data: "email="+ email,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK')
{
/*$("#email").removeClass('object_error'); // if necessary
$("#email").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');*/
//////////////////
$(this).next().hide();
$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
//////////////
}
else
{
$("#email").removeClass('object_ok'); // if necessary
$("#email").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
The tow first comment lines are the default ines used to show the next field //$("li").next("li.password").slid ...
Like you see I add them in Ok test section ....

Categories