I've currently got a working form right now that just uses a conditional to check if it's been submitted and processes the form on the same page: https://gist.github.com/adrianrodriguez/48cd90067a63691adc6a
But obviously the caveat is that it refreshes the page. Which in reality is fine, I just used a little bit of JS to fadeIN the results after the form echos it with
style="display:none"
And that's sorta fine...but I want to spice it up and use ajax.
Below is the js without ajax (just using validation.js for validating)
JS UPDATED WITH ANSWER
$(document).ready(function(){
// Jquery Form Functions
$('#redeem').validate( { // initialize the plugin
rules: {
fullname: {
required: true
},
cardnumber: {
required: true,
digits: true
},
email: {
email: true,
required: true
},
confirmation: {
email: true,
required: true,
equalTo: "#email"
}
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = "<p>All fields in red must be filled*</p>";
$("#redeem .message").html(message);
$("#redeem .message").show();
} else {
$("#redeem .message").hide();
}
},
submitHandler: function (form) { // for demo
//form.submit();
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
dataType: "json", // Recognize JSON Data
success: function(data) {
$.each(data, function(key, value) {
// Loop with key and value from conditional
console.log(key + " " + value);
});
}
});
return false;
}
});
if ($('.result')) {
$('.result').fadeIn(400);
}
});
I know how to process with ajax using:
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(data) {
console.log(data);
}
});
return false;
And it works fine, but the problem I run into is when I want to echo specific strings based on some of the conditionals in the form.
A) I can't echo the information out since the form is separate from the page it's processed on...
B)...and I don't know how to pull in that information to the current page it's being processed on.
Is this even possible? If so, how? Or do I just need to stay with what I have going on now?
Here is a video of what I have working now (without ajax): http://screencast.com/t/196P9ugso2L and notice how if a page is long it won't feel like the form is being processed real time (instead of refresh). Like I said, in all honestly, I just want to give a better user experience and spice things up.
UPDATE
PHP with array (which I think I am doing wrong, I tried three different ways, all failing noob style).
<?php
include('db-connect.php');
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$cardnumber = $_POST['cardnumber'];
$select = "SELECT * FROM cardholders WHERE cardnumber = $cardnumber";
$selectfrom = mysql_query($select);
if ($info = mysql_fetch_assoc($selectfrom)) {
if ($fullname == $info['name'] && $info['used'] == 0) {
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// $headers .= 'CC: $email' . "\r\n";
$headers .= 'From: Comanche Nation Casinos <no-reply#comanchenationcasinos.com>';
$confirmation = '<h1>Hi ' . $info['name'] . ' you\'ve won <b>$' . $info['amount'] . '</b> in Comanche Credit!</h1>
<p>Thank you for being such a valuable C Club member. Print or Show this email and redeem this at your Comanche Nation Casino.</p>
<p>Save this email just incase something happens so that the staff can ensure your reward at the kiosk.</p>';
// mail("web#icgadv.com", "Care Center Gala Sponsorship Request", $staff, $headers);
// mail($email, "Care Center Gala Sponsorship Request Confirmation", $confirmation, $headers);
// $message = "<p>Congratulations!" . $info['name'] . "!</p> <p>You've won! Please check your email for your winnings and futher information.</p>";
$winner = true;
$message = array( 'winner' => true, 'message' => 'This is a test');
$updateUser = "UPDATE cardholders SET email='$email', used=1 WHERE cardnumber = $cardnumber";
$update = mysql_query($updateUser);
} else if ($fullname != $info['name'] && $info['used'] == 0) {
// $message = "Sorry but your name does not match the name in our database.";
$noname = true;
$message = array( 'winner' => true, 'message' => 'This is a test');
} else {
// $string = "<p>Sorry but this offer has already been redeemed to this account</p>";
$redeemed = true;
$message = array( 'winner' => true, 'message' => 'This is a test');
}
} else {
// $message = array( 'status' => true, 'message' => "<p>Sorry but this card number does not exist.</p>" );
$invalid = true;
$message = array( 'winner' => true, 'message' => 'This is a test');
}
echo json_encode($message);
?>
As #TomToms posted above the problem is you need to pass a result back from the Ajax page called, the one processing. As mentioned, you do this using a JSON array. I will give you a brief example of this below:
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
dataType: "json",
success: function(data) {
console.log(data);
}
});
Note the added dataType, this states you are expecting a JSON string back, and will convert it into an array in data for you.
On you processing page, the form.action you would have this:
// ... code that loads form information and all your current processing.
$example = array(
'prize' => true, // true or false on whether they get the prize.
'status' => 'Show Status Message' // put any message for the show status box here.
);
echo json_encode($example);
Now if you look in console at the end data will be an object with the prize and status in it.
I'd also recommend you have a look through the JSON website for more information on JSON.
If I understand your question correctly what you need is to send back a JSON array with a status code for each field or something along those lines and then parse that in your javascript to warn the user appropriately.
As per documentation, .ajax() always goes inside of the submitHandler callback function.
Replace this...
submitHandler: function (form) { // fires on submit when form is valid
form.submit(); // regular submit action
}
With something like this...
submitHandler: function (form) { // fires on submit when form is valid
$.ajax({
url: $(form).action,
type: $(form).method,
data: $(form).serialize(),
success: function(data) {
console.log(data);
}
});
return false; // block the default form action
}
Related
I made a contact form(custom) that uses AJAX to send out the message. Now I am unclear on how to validate the form.
AJAX Request:
$("#contact-form").on("submit", function (e) {
e.preventDefault();
var action = "contact_form";
$("#submit, #clear").prop("disabled", true);
$("#submit").html("Sending");
$.ajax({
url: $(this).attr("action"),
method: "post",
data: {
name: $("#name").val(),
email: $("#email").val(),
phone: $("#phone").val(),
subject: $("#subject").val(),
message: $("#message").val(),
action: action,
},
success: function () {
$("header").append(
"<div id='alert' class='alert alert-success alert-dismissible fixed-top' role='alert' >" +
"<p class='text-center'>Success</p>" +
"<button type = 'button' class='close' data-dismiss = 'alert'>×</button>" +
"</div>"
);
$("#submit, #clear").prop("disabled", false);
// $("#contact-form input,textarea").val("");
grecaptcha.reset();
$("#submit").html("Send");
},
error: function () {
$("header").append(
"<div id='alert' class='alert alert-danger alert-dismissible fixed-top' role='alert' >" +
"<p class='text-center'>Error</p>" +
"<button type = 'button' class='close' data-dismiss = 'alert'>×</button>" +
"</div>"
);
$("#submit, #clear").prop("disabled", false);
grecaptcha.reset();
$("#submit").html("Send");
},
});
});
});
Functions.php:
function contact_form() // this is the action data variable we set in ajax
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// preparing parameters for wp_mail();
$to = "mail#example.com";
$msg = "
Name: $name
Email: $email
Phone: $phone
$message
";
// sending mail using wp_mail function
wp_mail($to, $subject, $msg);
wp_die(); // must use wp_die() to avoid unwanted output from wordpress
}
// in first parameter prefix function name with wp_ajax_
// this action is required in order to recieve data sent from ajax
add_action( 'wp_ajax_contact_form', 'contact_form' );
add_action( 'wp_ajax_nopriv_contact_form', 'contact_form' );
Now what I usually do when I am not trying to use ajax is preform validaiton in the php file and for example if captcha is invalid I append status to GET method and return error. If anyone can point me in the right directon on how to validate in php file and return info to frontend or should I do the validation in the js file? I'm quite confused there is so many articles on the web I honestly have no idea where to look.
P.S Everything is working perfectly just left to validate it.
Validate both ways. JS validation makes for a smooth UX and takes care of most concerns regarding valid email addresses, non-empty fields etc.
PHP validation will ensure that your functions don't error out and can allow you to do some server side checks (like exact message hasn't been sent before etc)
In php, do your validation checks and prepare a json response of any errors, then echo that back (rather than proceed with the code) if there are errors. In JS catch the errors in your success block - which right now doesn't listen for any response.
PHP:
if ($errors) {
echo json_encode(array('status' => 'error', 'message' => 'Your email message has objectionable content'));
wp_die();
}
if (!wp_mail($to, $subject, $msg)) {
echo json_encode(array('status' => 'error', 'message' => 'Your email message did not send for some reason'));
wp_die();
}
echo json_encode(array('status' => 'success');
wp_die();
Your JS
// ajax...
$.ajax({
... your props
dataType: 'json',
success: function (response) {
if (response && response.status == 'error'){
$('errors').html("Sorry, your message did not get sent due to these errors: " + response.message);
return;
} else {
// .. success
I have a contact form on my website with a jQuery ajax call, but I don't see the .php page when I click on the button.
Here's the ajax call:
var data = {
name: $("input.userName").val(),
email: $("input.userEmail").val(),
tel: $('input.userPhone').val(),
message: "Projet de "+$("input.userName").val() + ", Tel : " + $('input.userPhone').val(),
body: body
};
$.ajax({
type: "POST",
url: "acerola.php",
data: data,
success: function(data){
console.log('ajax sucessfully sent');
}
});
With acerola.php:
<html>
<head><title>PHP Mail Sender</title></head>
<body>
<h1>OUIIiiii</h1>
<?php
echo "<h1>Coucou</h1>";
/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$name = $HTTP_POST_VARS['name'];
$email = $HTTP_POST_VARS['email'];
$tel = $HTTP_POST_VARS['tel'];
$message = $HTTP_POST_VARS['message'];
$body = $HTTP_POST_VARS['body'];
/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!preg_match("/\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
echo "<h4>Invalid email address</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
echo "<h4>No subject</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ( /* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
mail("plu#gmail.com", "Demande de devis web", $message . $body, "From:" . $email)
) {
echo "<h4>Thank you for sending email</h4>";
echo "<div>Thank you for sending email</div>";
} else {
echo "<h4>Can't send email to $email</h4>";
}
?>
</body>
</html>
I would like the user to be redirected to acerola.php. But the user stays on the original page.
After the ajax response, fire a redirect with javascript.
$.ajax({
type: "POST",
url: "acerola.php",
data: data,
success: function(data){
console.log('ajax sucessfully sent');
window.location.replace('URL HERE')
}
});
I'm trying to send a form build with CodeIgniter via AJAX and trying to get the response with JSON. However, I only see the respond when I open my developer tab (I'm not even sure, if that's actually a respond since it's showing both of the json data's).
All it shows, is the loading spinner, and after that it vanishes.
Code have been tested without AJAX and it works, so there can't be errors in PHP.
Here's my controller for resetting the password:
<?php
Class Users extends CI_Controller {
public function forgot_pass()
{
if(!$this->input->post('to_email'))
{
exit("No data");
}
$this->load->model('user');
$email = $this->input->post('to_email');
$email_addr = $this->user->get_email_address($email);
if(empty($email_addr))
{
echo json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again"));
}
$this->load->helper('string');
$new_password = random_string('alnum', 8);
$this->load->library('phpass');
$update_password = array( 'password' => $this->phpass->hash($new_password));
$update_password = $this->user->update_password($email, $update_password);
$this->load->library('email');
$config['newline'] = '\r\n';
$this->email->initialize($config);
$this->email->from('your#example.com', 'Your Name');
$this->email->to($email);
$this->email->subject('New password');
$this->email->message("Hey, " .$email_addr['name']. ". Your new password is: " .$new_password);
if($this->email->send())
{
echo json_encode(array('pls'=>1, 'msg' => "Password has been sent to given e-mail address"));
}
}
}
?>
And here's my AJAX call written with jQuery:
$(document).ready(function() {
$("form#forget_pass_form").on('submit', function(e){
e.preventDefault();
$("#loading_spinner").show();
var from = $(this);
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data: $(from).serialize(),
}).done(function(data) {
if(data.pls == 0) {
$("#forgot-pass-success").hide();
$("#forgot-pass-error").show();
$("#forgot-pass-error").fadeIn(1000).html(data.msg);
}
if(data.pls == 1) {
$("#forgot-pass-error").hide();
$("#forgot-pass-success").show();
$("#forgot-pass-success").fadeIn(1000).html(data.msg);
}
$("#loading_spinner").hide();
});
return false;
});
});
Firstly, can you try setting the correct header in the Controller?
header('Content-Type', 'application/json');
Or better yet:
$this->output->set_content_type('application/json');
As a side note, you should make sure you are always returning JSON data, so I would remove the exit() message and put a default JSON response at the bottom of the method.
Don't forget, when you echo your JSON, you can put return; afterwards to stop any more code running afterwards in that method.
Most of your code is ok. But you need to change some lines, both in your js, and controller.
Change 1(In Ajax function)
Change your ajax function and add dataType: "json" option
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
dataType: "json",
data: $(from).serialize(),
}).done(function(data) {
....
});
Change 2 (In controller)
exit("No data");
to
exit(json_encode(array('pls'=>0, 'msg' => "No data")));
Change 3 (In controller)
echo json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again"));
to
exit(json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again")));
explanation
First change tell your script to handle the response data as Json
Second change is to keep all your return type same, if not when you sending only the no data response you are not handling this option from youe js.
And the last change make sure you stop further processing when sending email fails, and stop from showing both json.
I would like to suggest you about json return.
First in your ajax you have to use dataType: 'json'
$.ajax ({
url: from.attr('action'),
type: from.attr('method'),
data: $(from).serialize(),
dataType: 'json',
}).done(function(data) {
..your code..
});
CodeIgniter have output class, why don't you use output class to respond to ajax from CI.
$output = array('pls' => 1,
'msg' => "Password has been sent to given e-mail address"
);
$this->output->set_content_type('application/json')
->set_output(json_encode($output));
Use output class, this is more efficient then echo
I hope it will helps you for better code style.
I have a form that is using php to email myself with enquiries. I have some jquery that is filling in details into a div,
How can I pass the Jquery var to PHP via ajax? (I've read that that is the best way?)
Here's how's it's emailing me with php:
<? if(isset($_POST['submit'])) {
$to = "rob#domain.com";
$header = 'From: rob#domain.com';
$subject = "Quotation";
$enquiry_first_name = $_POST['enquiryfirstname'];
$enquiry_last_name = $_POST['enquirylastname'];
$enquiry_title = $_POST['enquirytitle'];
$enquiry_organisation = $_POST['enquiryorganisation'];
$enquiry_address = $_POST['enquiryaddress'];
$enquiry_country = $_POST['enquirycountry'];
$enquiry_email_address = $_POST['enquiryemailaddress'];
$enquiry_telephone = $_POST['enquirytelephone'];
$enquiry_additional_comments = $_POST['enquiryadditionalcomments'];
$body = "You have an quote request from the website:
Name: $enquiry_title $enquiry_first_name $enquiry_last_name
Type of organisation: $enquiry_organisation
Address: $enquiry_address, $enquiry_country
E-Mail: $enquiry_email_address
Tel: $enquiry_telephone
Comments: $enquiry_additional_comments
Kind regards";
mail($to, $subject, $body, $header);
echo "Thank you for your enquiry.";
} ?>
Here's the jquery that is outputting data into a div:
function makeSummary() {
var summary = [];
$steps.not(":last").each(function (i, step) {
$step = $(step);
summary.push('<p><b>' + $step.data('name') + '</b></p>');
var $ch = $step.find('input[type="checkbox"]:checked');
if (!$ch.length) {
summary.push('<p>No items selected</p>');
} else {
$ch.each(function (i, ch) {
summary.push('<p>' + $(ch).val() + '</p>');
});
}
});
return summary.join('');
}
1) Make a hidden input field.
2) Pass the jQuery var content to the hidden input field
$('.selector').change(function(){
//replace the value here.
});
3) Get it in php with $_POST['hiddenname']
E: Here is an example: http://jsfiddle.net/yLuNu/4/
It's using a dropdown to store a value in a hidden field. You can use any output and store it inside of the hidden field.
E2: Since I didn't really get what you want to pass to the hiddenfield: If you have a function and only want the output to save inside the hiddenfield:
What exactly do you want to pass to your script? I saw a checkbox so I thought you wanna use the change func. In case you only want to return the output of a function
$('input#hiddenfield').val($VAR)
while var is the output of your function. Just add this at the end of your existing func..
Just use AJAX and render a hidden input to your form, before submitting it.
Javascript:
$.ajax({
url:'/my/url',
type: 'POST',
dataType: 'json',
data: {
"some-var": "some-value"
},
context: $('form#my-form'), // now use $(this) inside event functions
complete: function(jqXHR, textStatus) {
console.log(jqXHR.responseText);
//this function gets called every time (not only on success or error)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
//do something if call fails!
},
success: function(data, textStatus, jqXHR) {
if(data && data.value) {
if($(this).find("#my-field").length) {
$(this).find("#my-field").val(data.value);
}
else {
$hidden = $("<input>")
.attr("type", "hidden")
.attr("name", "my-field")
.val(data.value);
$(this).append($hidden);
}
//submit form
$(this).submit();
}
}
});
And you AJAX processing PHP File qould look like this.
PHP:
<?php
$data = array(
"value" => "default"
);
if($_POST["some-var"]=="some-value") {
$data = array(
"value" => "something"
);
}
echo json_encode($data);
?>
Just to give you an idea how to solve this!
You will need to do some validation and filtering by yourself!
My solution is using onClick event to call a PHP page, post parameters and return result using AJAX. I insert parameter right at time calling PHP page using specified URL.
Here is my Javascript:
function uploadContact() {
var name, email, phone, badgeid;
if(window.localStorage.length > 0)
{
name = window.localStorage.getItem('name');
email = window.localStorage.getItem('email');
phone = window.localStorage.getItem('phone');
}
else
{
name = $('input[name=fullname]').val();
email = $('input[name=email]').val();
phone = $('input[name=phone]').val();
}
$.ajax({
url: 'UpdateContactList.php?name=' + name + '&email=' + email + '&phone=' + phone,
type: $form.attr('method'),
dataType: 'json',
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},
error: function() {
$form.before("<p>There was an error processing your request.</p>");
}});
}
My PHP code to get parameters:
<?php
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array( 'fullname' => $_POST['name'], 'email' => $_POST['email'], 'phone' => $_POST['phone']);
//These line is for testing only, remove it when done testing
$test = $_POST['name'] . ' ' . $_POST['email'];
echo "<script>alert('$test');</script>";
// always return true if you save the contact data ok or false if it fails
$response['status'] = updateContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
header("Content-type: application/json");
echo json_encode($response);
exit;
}
...
function updateCacheFile($filename)
{
$filename = "contact";
$filename = $filename . ".appcache";
$cachefile = fopen ($filename, "a+");
....
file_put_contents($filename, $cache_content);
}
Please notice 2 problems:
I can call directly PHP page with parameters from browse address link, do this will return nothing. Is it normally?
Call from javascript. The testing line (call an alert message box) won't work, no message appeared. But the cache file still updated, which means PHP page is called and do things like writing files.
There is 2 files to be written in this PHP page. Both of them were written correctly but the parameters won't show up and no message box show.
Please instruct me what went wrong here.
P/S: small detail, Is parameter with space can be pass correctly? Because I expected users input their full name, such as 'Bill Jobs'.
Thanks to Stackoverflow community.
echo "<script>alert('$test');</script>";
// always return true if you save the contact data ok or false if it fails
$response['status'] = updateContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
header("Content-type: application/json");
echo json_encode($response);
All headers must be executed before you begin echoing or otherwise flushing output.
header("Content-type: application/json");
echo "<script>alert('$test');</script>";
// always return true if you save the contact data ok or false if it fails
$response['status'] = updateContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
echo json_encode($response);
$.ajax({
url: 'UpdateContactList.php',
data:{'name':name,'email': email,'phone':phone,'badgeid ':badgeid },
type: $form.attr('method'),
dataType: 'json',
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},
error: function() {
$form.before("<p>There was an error processing your request.</p>");
}});
Try sending your info in the data param of the ajax and setting the type to post. Like this...
$.ajax({
url: 'UpdateContactList.php',
type: 'post',
dataType: 'json',
data: {'key1': value1, 'key2':value2},
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},