I've created a form using a bit of jquery, ajax and php.
The ajax, validation and php processing works well.
I came up with the following code to hide my form after submitting, but I don't know if this is the good way to do that. I would like your advise.
Below the js script with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
$("#formstatus").hide().html(response).slideToggle(600);
}
});
});
});
</script>
The above code will call the php to validate and populates the div#formstatus to notify the user if the form is sent or not.
Within my process.php, I will hide the form if there are no errors found using echo js script.
// If no errors found echo succes message
if (!($formerrors)) :
//Hide the form
echo '<script type="text/javascript">
$(document).ready(function(){
$("#contact_form").hide();
});
</script>';
// display success message
echo '<div>
Your message has been sent. <br />
Thank you for contacting us!
</div>';
Etc....
To sum up:
Should I use this method to hide my form? (Because it does work)
Note. I'm new to jquery and ajax :)
I think it would be better to return a JSON object which contains the information relevant to the request.
For example:
if (!($formerrors)){
echo json_encode(array(
'success'=> true,
'message'=> 'Your message has been sent. <br> Thank you for contacting us!'
));
}
else{
echo json_encode(array(
'success'=> false,
'message'=> 'Error processing form',
'errors'=> array(
'phone'> 'A phone number is required'
)
));
}
This will be easy to work with on the client side (jQuery will automatically parse the json)
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
if(response.success){
$("#formstatus").hide().text(response.message).slideToggle(600);
}
else{
jQuery.each(response.errors,function(){ ... });
}
}
});
});
});
I think you'll find you have more manageable code if you separate display concerns from functional concerns. For php I agree with Walkerneo.
Javascript AJAX Success Handler
success: function(response) {
var response = $.parseJSON(response);
if(response.status === 'true') {
$("#formstatus").hide().html(response.message).slideToggle(600);
$("#contact_form").hide();
} else {
$("#formstatus").hide().html(response.message).slideToggle(600);
}
}
PHP
if(!$formerrors) {
exit(json_encode(array('status' => 'true', 'message' => 'Your message has been sent. \n Thank you for contacting us!')));
} else {
$message = '<p class="error">' . implode('</p><p>', $formerrors) . '</p>';
exit(json_encode(array('status' => 'false', 'message' => $message)));
}
I recommend avoiding this method. You should instead return information about the status and message to display to the user. For example, here's how you can do it without reloading the page.
demo (non-blank data will be accepted)
We prevent the default event, so that the page doesn't reload. Because of the below HTML changes, we also can make or code more general.
$('form').submit(function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
cache: false,
type: 'POST',
url: 'URLHERE',
data: $(this).serialize(),
dataType: 'jsonp',
success: function(response) {
We display the error or success message here. Depending on the status field, we make the text green or red, and decide whether to hide the form or not.
$("#formstatus").hide().text(response.msg).show(600);
if (response.status === "success") {
$this.hide();
$("#formstatus").css({color: "green"});
}
else {
$("#formstatus").css({color: "red"});
}
}
});
return false;
});
Our PHP simply returns a JSON object.
function callback($data){
$json = json_encode($data);
return $json;
}
if ($valid === true) {
echo callback(
array(
"msg" => "Your message has been sent.\nThank you for contacting us!",
"status" => "success"
)
);
}
else {
echo callback(
array(
"msg" => "Please fill in all fields.",
"status" => "error"
)
);
}
The HTML is also changed to use a submit button, which allows us to target the form instead of the button. The code may now be transported more easily.
<div id="formstatus"></div>
<form>
<input placeholder="First Name" name="name">
<input placeholder="Email" name="email">
<input placeholder="Comment" name="comment">
<input type="submit">
</form>
Related
I've figured out that wp_ajax_my_action only works if it's placed in a plugin.
Does anyone know if it's possible to run it in my theme's functions.php?
Yes you can :
In your page template :
var AjaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
$.ajax({
type: "POST",
url: AjaxUrl,
data: {
action: 'your_action'
},
Inside your functions.php :
function your_action() {
//write your code here
}
add_action('wp_ajax_your_action', 'your_action');
add_action('wp_ajax_nopriv_your_action', 'your_action');
Pass action in Html form
<form name="myform">
<input type="hidden" name="action" value="custom_action">
<input type="text" name="get_first_name" >
<input type="submit value="submit">
</form>
Your jQuery look like this
<script>
jQuery(document).ready(function ()
{
var $this = jQuery(this); // Cache this
jQuery.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>', // Let WordPress figure this url out...
type: 'post',
dataType: 'JSON', // Set this so we don't need to decode the response...
data: $this.serialize(), // One-liner form data prep...
beforeSend: function () {
// You could do an animation here...
},
success: function (data)
{
if (data.status === 'success') {
alert("Success");
// Here, you could trigger a success message
} else {
// fail
}
}
});
});
</script>
put this code in function file
function custom_action_function()
{
$first_name = $_POST['get_first_name'];
/* fetch your form variable here */
if('your condition') // your condition if success
{
echo json_encode(array('status' => 'success', 'message' => 'Message Sent.'));
exit;
}
else
{
echo json_encode(array('status' => 'error', 'message' => 'Message not sent'));
exit;
}
}
add_action('wp_ajax_custom_action', 'custom_action_function'); // Call when user logged in
add_action('wp_ajax_nopriv_custom_action', 'custom_action_function'); // Call when user in not logged in
I have following form processing php script.
<?php
$G['hotel_email']="xxxx#xxxx.com";
$G['hotel_name']="xxx xxx";
$G['language']="en";
$T['lbl_form_sent_successfully']="H";
# Recipients: comma separated
$G['form_contact_mail_recipients'] = $G['hotel_email'];
$G['form_contact_mail_subject'] = $G['hotel_name'] . ' - Contact Weddings [' . $G['language'] . ']';
# CHECK IF FORM SENT. AJAX. RESPONSE IN JAVASCRIPT TO INTERACT IN THE FORM.
if (!empty($_POST)) {
$js = '';
# ALTERNATIVE CAPTCHA, IT MUST NOT BE FILLED
if (!empty($_POST['title'])) { exit; }
# FORM MAIL TO SENT
unset($_POST['title']);
unset($_POST['submit']);
$message = date("l, F j, Y, g:i a")." [GMT] \n\nFORM DETAILS\n\n\n";
foreach ($_POST as $field => $value) {
$message .= ucfirst(str_replace('_',' ',$field)).': '.$value."\n\n";
}
$message .= "\n\n\n";
mail($G['form_contact_mail_recipients'], $G['form_contact_mail_subject'], $message, "From: ".$_POST['email']."\r\n");
echo "success";
}
?>
The form is being submitted using following JavaScript
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("#ba-form-contact form").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
First_Name: "required",
Surname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
}
},
submitHandler: function() {
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
return false;
}
});
});
</script>
The last echo statement does't work and I don't get any error msg.I do get email with all the info alright.I think nothing work after the mail function, I tried like var_dump, but nothing. What could be the error here?
As per your ajax request, you are not using success method here in ajax request, you need to add success method as:
jQuery.ajax({
url: YourURL,
type: "POST",
data: jQuery("#ba-form-contact form").serialize(),
dataType: "html",
success: function(response) {
alert(response); //this will return the response
},
beforeSend: function()
{
// loading if you need before ajax success
}
});
return false;
Here success: function(response) { will return the success message.
You do not know that it is the echo that does not work.
What you do know is that the script executes, and the jQuery function does not issue output. And that's where half the problem is.
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
The above does not do anything with the output, so logically nothing happens.
Try this:
jQuery.post({
'<?=$_SERVER['REQUEST_URI']?>',
jQuery("#ba-form-contact form").serialize()
}).done(function(retval) {
// Debug (better use console.log actually)
alert(JSON.stringify(retval));
// Do what you want with retval.message (check retval.status also)
alert(retval.message);
});
and in the PHP, which must output nothing else, end with:
header('Content-Type: application/json');
die(json_encode(array(
'status' => 'success',
'message' => 'The mail was sent',
)));
(I have changed from HTML to JSON output since this allows to send more structured data, with negligible additional complexity).
I have Jquery/Ajax Code which sends Text Fields Data to PHP Script. But i don't know how i can receive that data and process for Validation.
Here is the Ajax Code:
$("#button").click(function (e) {
var dataa = $("#survay").serialize();
var data = $("#yourName ,#emailAdress , #phoneNumber , #zipCode").serialize();
$.ajax({
type: "POST",
url: 'processRequest.php',
data: dataa,
beforeSend : function(){
$('.eDis').empty().append('<div class="loader"><img src="images/32.gif" /> Loading...</div>').show();
},
success: function (html) {
if(html !='1') {
$('.eDis').empty().append(html).addClass("actEr");
setTimeout(function(){
$('.eDis').removeClass("actEr")}, 5000);
}
if(html == '1') {
$('.eDis').empty().append('<div class="success">Your Message has been sent</div>').addClass("actEr");
window.location ='../thank-you.html';
}
if(html =='0') { $('.eDis').empty().append('Error..').addClass("actEr"); setTimeout(function(){
$('.eDis').removeClass("actEr")}, 3000);
}}
});
});
processRequest.php should be PHP script which will handle all the texts fields data.
If above Text fields data is valid then i want it to Proceed further and redirect the page to thank-you.html
.eDis is CSS class, which i want to use to display valid,Invalid fields information.
It is in HTML.
Based on your information, I can't give you exact code, but, this is what you can do:
<?php
if(isset($_POST['itemName']) && isset($_POST['anotherItemName']) /* ...and so on */){
if($_POST['itemName'] == $validSomething)
echo 'WOW!';
}
else
echo 'error';
?>
What you are "echoing" is what you get in "success" data in your javascript.
So this is my idea, I have a login jquery dialog on my homepage that blocks anyone from using the webpage (behind the login form dialog). I use ajax to submit the information entered to a php page which then checks if the username/password combo exists in the database. If it does, I return true and then close the dialog box (allowing access to the site).
How do I use ajax to check if my php script (from the executed page) returns true or false?
I was assuming the success/error options of the ajax function were checking this, but the below code doesnt seem to work.
$('.login').dialog({
closeOnEscape: false,
title: false,
modal: true,
width: 'auto',
show: {effect: "fade", duration: 1500},
title: 'Login',
buttons: {
"Login": function() {
$.ajax({
async: false,
type: 'POST',
url: 'sql/login.php',
success: function(){
alert( "Success!");
},
error: function(){
alert( "Failed!" );
},
dataType: "html"
});
}
}
});
$(".login").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
What I did was to put an echo at the end of my php with the variabel that is put in true or false, the I did this function inside the success option it is like this:
success: function(response){
if(response){
alert( "Success!");
}else{
alert( "Failed!" );
}
}
This worked for me, and you can put this in the php
if($myvar){
$anothervar=1;
}else{
$anothervar=0;
}
echo $anothervar;
so you can do this:
success: function(response){
if(response==1){
alert( "Success!");
}else{
alert( "Failed!" );
}
}
this is the way that I do it and it works fine
Hope it is useful
No. The success and error options relate to the success or failure of the XHR request. You need your php script to output something and check that. For example if your php script outputs "ok" (i.e. echo("ok");) if the verification is successful, you would use an ajax request such as this one
$.ajax({
url: 'sql/login.php',
success: function(data) {
if(data=="ok") {
alert('Login successfull.');
} else {
alert('Login failed.');
}
}
});
In your login.php:
if($_POST['data']){
$curData = $_GET['country'];
$query = "SELECT * FROM yourTable
WHERE tblData = '$curData'";
$result = mysql_query($query) or die;
if($result>0)
echo "<p class='checkExistance'>Data Exists</p>";
else
echo "<p class='checkExistance'>Data doesnt Exist</p>";
}
In your javascript:
function isSuccess(){
if($('.checkExistance').text() === "Data Exists"){
success($('.checkExistance').text()); //alert success!
}else{
success($('.checkExistance').text());
}
}
Did not really check if that works, but you pretty much get the idea. On AJAX call, do this:
$.ajax({
//
..
success:isSuccess
});
or
success:function(){
if($('.checkExistance').text() === "Data Exists"){
success($('.checkExistance').text()); //alert success!
}else{
success($('.checkExistance').text());
}
}
Make sure you implement alert() within the success() function..Hope that helps.
According to your information I assumed that your php page will do a validation and you make them return true or false within the php script
There are 2 problems in your code
1.your php page will return true or false within itself,in the other hand they won't send the result to ajax result unless you send them out like Tomm's said above
2.success() and error() of $.ajax are determined by the success of request NOT BY RESULT which mean that even if your php echo "false" it will trigger success() event because THE REQUEST IS SUCCESSFULLY SENT.
I'm trying to use ajax within my contact form in a codeigniter app. I have it to where the ajax call is made, but no post data is being sent to the server. I can't figure out why. Please help.
I do have some returns in there, but they do nothing. Also, $this->input->post('name') is null.
Form view
<?php
echo form_open('welcome/submit_contact');
echo form_error('name');
echo form_label('Name', 'name'"');
echo form_input('name', set_value('name'), 'id="name);
echo form_error('email');
echo form_label('Email', 'email');
echo form_input('email', set_value('email'), 'id="email"');
echo form_error('phone');
echo form_label('Phone', 'phone');
echo form_input('phone', set_value('phone'), 'id="phone"');
#echo '<h5>Do not start with "1" and no dashes.</h5>';
echo form_error('message');
echo form_label('Message', 'message');
echo form_textarea('message', set_value('message'), 'id="message"');
$submitData = array(
'name' => 'submit',
'value' => 'Submit',
'id' => 'button'
);
echo form_submit($submitData);
echo form_close();
?>
<script type="text/javascript">
$(function() {
$('form').click(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('welcome/submit_contact'); ?>",
type: "post",
data: form_data,
success: function(msg) {
$('form').prepend('<h5 class="good">Message sent!</h5>');
$('h5.good').delay(3000).fadeOut(500);
alert(msg);
}
});
// prevents from refreshing the page
return false;
});
});
</script>
Controller function
function submit_contact()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h4 class="bad">', '</h4>');
$name = $this->input->post('name');
echo "name = ".$name;
$this->form_validation->set_rules('name', 'Name', 'trim|required|alpha_dash|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('phone', 'Phone' , 'trim|integer|exact_length[10]|xss_clean');
$this->form_validation->set_rules('message', 'Message', 'trim|required|max_length[1000]|xss_clean');
// there are validation errors
if($this->form_validation->run() == FALSE)
{
return "error";
}
else // there are no validation errors
{
/*************************
need to actually send the email
*************************/
return null;
}
}
EDIT: I've updated the code in my question. Basically now if there are validation errors, how would I get them to display on the form? I'm assuming I would return a value from my controller and then have a statement in my ajax success that if msg == "error" display the errors elseif msg == null, display success message. But how would i tell my view to display those errors based on an ajax success variable?
i think you should put id on input and textarea not on label i.e.
$data = array
(
"name"=>'message',
"value"=>'message',
"id"=>'message'
)
form_textarea($data);
if you set the id on the label then jquery will pick up nothing from what the user inserted and also codeigniter validation won't work correctly. This is why your post result to be NULL
the same for other input field
EDIT
you are asking data via ajax so return a nice json object (remove all your debug prints first):
// there are validation errors
if($this->form_validation->run() == FALSE)
{
echo(json_encode("validate"=>FALSE));
}
else // there are no validation errors
{
/*************************
need to actually send the email, then send you mail
*************************/
echo(json_encode("validate"=>TRUE));
}
then test it on your ajax success function to display positive or negative message
<script type="text/javascript">
$(function() {
$('form').click(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('welcome/submit_contact'); ?>",
type: "post",
data: form_data,
dataType: "json"
success: function(msg)
{
if(msg.validate)
{
$('form').prepend('<h5 class="good">Message sent!</h5>');
$('h5.good').delay(3000).fadeOut(500);
}
else
//display error
}
});
// prevents from refreshing the page
return false;
});
});
</script>