I have a html form that is supposed to submit data to a php file through jquery ajax. the code can be seen below.The problem I am having is that on clicking submit, the ajax seems not to be passing data to php as the console.log under the done() function returns a $data object showing that all fields are empty (i.e returning the error messages when the fields are empty). I am simply not getting where the problem is. When I submit the form without using ajax i.e disabling the entire $('form').submit (...) block, the success message returns true. the ajax blocks always returns false
<form id="sds_contact_form" class="sds_form" action="form_submit.php" method="post">
<!-- name -->
<div class="sds_input_group sds_half_field">
<label for="sds_sender_name">full name*</label>
<input id="sds_sender_name" name="sds_customer" type="text" placeholder="eg John smith" required />
<span id="sds_customername_error" class="sds_error_span"></span>
</div>
<!-- email address -->
<div class="sds_input_group sds_half_field">
<label for="sds_sender_email">email*</label>
<input id="sds_sender_email" name="sds_form_email" type="email" placeholder="eg j.smith#example.com" required />
<span id="sds_email_error" class="sds_error_span"></span>
</div>
<!-- subject -->
<div class="sds_input_group">
<label for="sds_email_subject">subject*</label>
<input id="sds_email_subject" name="sds_form_subject" type="text" placeholder="e.g need an app designed" required />
<span id="sds_subject_error" class="sds_error_span"></span>
</div>
<!--enquiry -->
<div class="sds_input_group">
<label for="sds_sender_enquiry">enquiry*</label>
<span id="sds_enquiry_error" class="sds_error_span"></span>
<textarea id="sds_sender_enquiry" name="sds_form_enquiry" placeholder="enter details here" rows="15" required></textarea>
</div>
<!-- submit button -->
<button name="sds_submit_enquiry" type="submit" class="sds_form_button sds_button">send</button>
</form>
This is the jquery code
//form data submission
$('form').submit(function(event){
var form_data = {
'customer_name' : $('#sds_sender_name').val(),
'customer_email' : $('#sds_sender_email').val(),
'email_subject': $('#sds_email_subject').val(),
'enquiry': $('#sds_sender_enquiry').val()
};
console.log(form_data);
$.ajax({
url :'form_submit.php',
type:'POST',
data:form_data,
dataType:'json',
}).done(function(data){
console.log(data);
}).fail(function(xhr, ajaxOptions, thrownError){
console.log("ERROR:" + xhr.responseText+" - "+thrownError);
});
event.preventDefault();
});
This is the PHP Code in form_submit.php
<?php
$data = array();
$errors = array();
//get form data
$customer_name = $_POST['sds_customer'];
$customer_email = $_POST['sds_form_email'];
$email_subject = $_POST['sds_form_subject'];
$enquiry = $_POST['sds_form_enquiry'];
//validate name
if(empty($customer_name)){
$errors['customer_name'] = 'name is required';
}
//validate email
if(empty($customer_email)){
$errors['customer_email'] = 'email is required';
}else{
if(!filter_var($customer_email,FILTER_VALIDATE_EMAIL)){
$errors['customer_email'] = 'email provided is invalid';
}
$customer_email = filter_var($customer_email,FILTER_SANITIZE_EMAIL);
}
//validate form subject
if(empty($email_subject)){
$errors['email_subject'] = 'subject is required';
}else{
$email_subject = filter_var($email_subject,FILTER_SANITIZE_STRING);
}
//validate form comments
if(empty($enquiry)){
$errors['enquiry'] = 'please enter your enquiry';
}else{
$enquiry = filter_var($enquiry,FILTER_SANITIZE_STRING);
}
if(!empty($errors)){
$data['success'] = false;
$data['errors'] = $errors;
}else{
$data['success'] = true;
$data['message'] = "Your email has been sucessfully sent. Thank you for your enquiry. Exepect a response soon!";
//further data processing here....
}
echo json_encode($data);
?>
Your problem is about parameters names At jquery the parameter is defined as:
var form_data = {
'customer_name' : $('#sds_sender_name').val(),
'customer_email' : $('#sds_sender_email').val(),
'email_subject': $('#sds_email_subject').val(),
'enquiry': $('#sds_sender_enquiry').val()
};
At PHP, you are using a sds prefix (as write in the form):
//get form data
$customer_name = $_POST['sds_customer'];
$customer_email = $_POST['sds_form_email'];
$email_subject = $_POST['sds_form_subject'];
$enquiry = $_POST['sds_form_enquiry'];
Your parameters should match with AJAX, not with form (as below).
$customer_name = $_POST['customer_name'];
$customer_email = $_POST['customer_email'];
$email_subject = $_POST['email_subject'];
$enquiry = $_POST['enquiry'];
Or just use serialized on form:
$.ajax(
data: $("#sds_contact_form").serialize(),
/*** others parameters ***/
$("#sds_contact_form").serialize() // returns all the data in your form
$.ajax({
type: "POST",
url: 'form_submit.php',
data: $("#sds_contact_form").serialize(),
dataType:'json',
success: function(data) {
console.log(data);
}
});
In you php file Unserialize your data
unserialize($data);
Related
sorry that I start this topic. I know that there were a lot of topics in this matter. But still I can not deal with it, because I need the success / failure messages to be displayed as below:
<!-- Form in modal -->
<?PHP if(isset($_SESSION['error_msg'])){echo $_SESSION['error_msg']; unset($_SESSION['error_msg']);}?>
<?PHP if(isset($_SESSION['success_msg'])){echo $_SESSION['success_msg']; unset($_SESSION['success_msg']);}?>
<form id="test-form action="test.php" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="submit" name="save-test-form" value="Save">
</form>
/* test.php */
<?PHP
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$_SESSION['success_msg'] = 'All is well.';
}else{
$_SESSION['error_msg'] = 'Enter the email.';
}
}else{
$_SESSION['error_msg'] = 'Enter the name.';
}
}
?>
And jquery?
My point is to submit this form without reloading the page (because it's in the modal window) and I have to display success / failure messages in the form (also without reloading the page). I do not know how to do it.
I will be grateful for the help and explanation of how to do it step by step.
Your PHP script is executed on page reload, so when using Ajax you must manually show messages from server:
// PHP
$response = [];
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$response['success'] = 'All is well.';
}else{
$response['error_msg'] = 'Enter the email.';
}
}else{
$response['error_msg'] = 'Enter the name.';
}
echo json_encode($response); // Format array as json and output it
die(); // No other output, just JSON
}
// jQuery
$.ajax({
url: '',
method: 'POST',
dataType: 'json',
data: {},
success: function (response) {
if (typeof response.success !== 'undefined') {
$('#responseMessage').text(response.success);
} else {
$('#responseMessage').text(response.error_msg);
}
}
})
I am trying to send email in PHP using AJAX in a simple contact form. I have the following codes for a simple form, PHP code for submit button and AJAX script.
When I am trying to send email it is not sending any email and always firing the AJAX error msg. I am not very well in AJAX integration with PHP.
Below is my code
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
I would move the php part to another file:
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
And in another email.php
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
You must be stop the default flow of that form by using event.preventDefault(); and you can pass the form as multipart/formdata or form-data and check the developer tools -> network -> fetch/xhr -> payload/ formdata. then you create a seperate page in php and do the mail process in that page and change the form action link to that page
In html
<form method="post" class="myform" action="mail.php">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).on('submit', '.myform', function(e){
e.preventDefault();
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: new FormData($(".myform")[0]),
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
if (result.status == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
</script>
In php - mail.php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
if($send_email)
{
$response = ['status' => 'success'];
}
else
{
$response = ['status' => 'error'];
}
echo json_encode($response);
}
So, the top answer works, but as #Mithu said, for some reason it always says:
'Error Sending email!'
After 30 minutes of exploring the situation I understood that for some reason it returns from PHP not 'success' but ' success' with 2-4 spaces in front of the word 'success' or 'error'.
So, all you need is to exclude these spaces, for that we need to change 'succes' to 'this is success' and 'error' to 'this is error'(just to make spare letters in the front) and then we need to divide this string to words and to extract the last word. It will always be 'success' or 'error' regardless how much spaces the script will add or how much letters it will remove accidentally. And also you need to make another if else statement in the PHP to check FALSE instead of TRUE.
Also I've added a few lines which check if the fields are filled or not. And if they are not filled then you get a message 'Please fill in the forms.'.
So here how it looks and works for me:
Importing jquery library (you need to place it into the header):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
HTML (you need to put it there where you want to have the contact form):
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
JS (you need to put it in the footer):
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
// if it can't find email.php just chahge the url path to the full path, including your domain and all folders.
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
let d = result.split(" ");
let y = d.slice(-1)[0];
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
if (y == 'success'){
$('.output_message').text('Message Sent!');
}
else if (y == 'miss'){
$('.output_message').text('Please fill in all the fields above.');
}
else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
email.php (you need to create this file in the same folder where you have your index.php):
<?php
// here we check if all fields are filled.
$required = array('name', 'email', 'message');
$error = false;
foreach($required as $field) {
if (empty($_REQUEST[$field])) {
$error = true;
}
}
//if something is not filled(empty) and error is true
if ($error) {
echo 'this is miss';
}
// if everything is filled then we execute the mail function
else {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$fullmessage = "Sender's name: ".$name."\n"."Message: \n".$message;
// Set your email address where you want to receive emails.
$to = 'contact#yourdomain.com';
$subject = 'Message from YOUR E-MAIL.COM';
$send_email = mail($to,$subject,$fullmessage,$email);
if ($send_email == false) {
echo 'this is error';
} else {
echo 'this is success';
}
}
?>
So,this code steadily works for me, but maybe it is not very proffessionaly made, because I am a begginer in JS and PHP.
I don't know how can i apply this to my login page, once captcha success response on ajax then submit form.
Here's my html form(i leave action null because i'm still in testing)
<form action = "" method = "post">
<input type = "text" id = "email" name = "email">
<input type = "password" id = "pass" name = "password">
<div class = "form-group col-lg-6">
<div class="g-recaptcha" data-sitekey="MY_KEY"></div>
</div>
<input type = "button" id = "submit" value = "submit">
</form>
Here's how i understand ajax on captcha sending captcha word.. if captcha success submit form if failed i will give an alert.
$('#submit').click(function() {
var captcha = "captcha";
$.ajax({
url: "captcha.php",
method: "post",
data:{captcha:captcha},
success:function(data){
if(data=='success'){
$('form').submit();
}
}
else{
alert('captcha failed. try again');
}
});
});
my captcha.php how i receive $_POST['captcha']
<?php
if($_POST['captcha']){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = 'MY_SECRET_KEY';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if($data->sucess==true){
echo "success";
}
else{
echo "failed";
}
}
?>
please help me to understand how will it work and how can it be done using AJAX
THANK YOU IN ADVANCE :)
UPDATE
i just notice how can i $_POST['g-recaptcha-response']; ??
You can use this code:
HTML Code:
<form action="" method="POST" id="loginForm">
<input type="text" id = "email" name="email">
<input type="password" id="pass" name="password">
<textarea type="text" name="message"></textarea>
<div class="g-recaptcha" data-sitekey="10LDDpf0ehtMZY6kdJnGhsYYY-6ksd-W"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
JavaScript
$(document).ready(function() {
var loginForm = $("#loginForm");
//We set our own custom submit function
loginForm.on("submit", function(e) {
//Prevent the default behavior of a form
e.preventDefault();
//Get the values from the form
var email = $("#email").val();
var pass = $("#pass").val();
//Our AJAX POST
$.ajax({
type: "POST",
url: "login.php",
data: {
email: email,
password: pass,
//This will tell the form if user is captcha varified.
g-recaptcha-response: grecaptcha.getResponse()
},
success: function(response) {
console.log(response);
//console.log("Form successfully submited");
}
})
});
});
PHP Code:
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '10LDDpf0ehtMZY6kdJnGhsYYY';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
//captacha validated successfully.
$email = !empty($_POST['email'])?$_POST['email']:'';
$password = !empty($_POST['password'])?$_POST['password']:'';
echo "captacha validated successfully.";
else:
echo "Robot verification failed, please try again.";
endif;
else:
echo 'invalid captcha';
endif;
else:
//Nothing
endif;
?>
I am using re-captcha validation using jQuery / ajax as per below :
<script src="https://www.google.com/recaptcha/api.js" >;
<form method="post" name="contactForm">
<input type="text" name="fname"/>
<input type="text" name="lname"/>
<input type="text" name="Phone"/>
<div class="g-recaptcha" data-sitekey="[site_key]" data-callback="onReturnCallback" data-theme="dark"></div>
<input value="submit" type="submit"/>
</form>
Validation / ajax :
//Initialize jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var onReturnCallback = function(response) {
var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';
$.ajax({ 'url' : url,
dataType: 'json',
data: { response: response},
success: function(result) {
var res = result.success.toString();
alert(res);
if (res == 'true') {
document.getElementById('g-recaptcha').innerHTML = ' Your Success Message';
}
}
});
};
</script>
I'm totally lost here. Can anyone check what is going wrong with the form I'm trying to create here? It should send data with Ajax in WP custom theme without storying anything in the DB.
The console gives me an error that "firstname is not defined", line 67 of jQuery - data:{name:firstname, email:email, message:comment,action:'validate_form'} , but truly, I believe it will be more than that.
<form class="form">
<div class="form__item form__item_no-margin">
<input type="text" name="firstname" placeholder="What's your name?*" class="firstname" required>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<input type="text" name="email" placeholder="What's your email address?*" class="email" required>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<textarea name="comment" placeholder="Please, leave a message!*" class="textarea" required></textarea>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<input type="button" name="submit" value="Send" class="submit-btn">
<p class="error-message error-message_main val-error">All the required fields have to be filled out.</p>
<p class="success-message val-success">Thanks. I'll contact you ASAP!</p>
</div>
</form>
And some jQuery:
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(e){
e.preventDefault();
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
var ajaxUrl = "/wp-admin/admin-ajax.php";
if(name === "" || email === "" || message === "") {
jQuery(".val-error, .error-message").show();
jQuery("html, body").animate({
scrollTop: jQuery(".val-error").offset().top
}, 700)
}
else {
jQuery.ajax({
url: ajaxUrl,
method:"POST",
data:{name:firstname, email:email, message:comment,action:'validate_form'},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
PHP in the functions.php file:
add_action('wp_ajax_myaction', 'my_action_callback');
add_action('wp_ajax_nopriv_myaction', 'my_action_callback');
function my_action_callback(){
$name= trim($_POST["firstname"]);
$email = trim($_POST["email"]);
$comment = trim($_POST["comment"]);
$page_title = "New form submission";
$message = "Name: $name \nEmail: $email \nMessage: $comment";
mail('some#email.com', $page_title, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: some#email.com" );
wp_die();
}
UPDATE
Attached is the fresh version in codepen. PHP is down below.
https://codepen.io/anon/pen/RVWaJY
add_action('wp_ajax_myaction', 'validate_form_callback');
add_action('wp_ajax_nopriv_myaction', 'validate_form_callback');
function validate_form_callback(){
$name= trim($_POST["firstname"]);
$email = trim($_POST["email"]);
$comment = trim($_POST["comment"]);
$page_title = "New form submission";
$message = "Name: $name \nEmail: $email \nMessage: $comment";
mail('some#email.com', $page_title, $message, "Content-type:
text/plain; charset=\"utf-8\"\n From: some#email.com" );
wp_die();
}
Think it may just be this typo:
var name = jQuery(".firstname").val();
The variable passed to data
name:firstname,
Let me know if that solves your problem. If not, I will look again. : )
The first issue with the code you've posted, as you've already identified, is the error in the console.
You're creating a variable name (ln 4) and then trying to reference it as firstname (ln 19). You're doing the same thing in the PHP callback. The object in the AJAX request sets the value as name yet you're trying to retrieve it with firstname.
The same problem applies to comment. The best approach would be to pick a label and use it consistently. Mixing comment and message will only lead to confusion.
The second issue is with the action. Your JS code sets the action as validate_form but your callback fires on myaction.
JS Updates:
. . .
var firstname = jQuery( ".firstname" ).val();
var email = jQuery(".email").val();
var comment = jQuery(".textarea").val();
. . .
method:"POST",
data: {
firstname: firstname,
email: email,
comment: comment,
action: 'validate_form'
},
PHP Updates:
add_action( 'wp_ajax_validate_form', 'validate_form_callback' );
add_action( 'wp_ajax_nopriv_validate_form', 'validate_form_callback' );
function validate_form_callback() {
Hello your data parameter need to be instead like this, you have inverted the way is suppose to be writting, your variable should be on the right side and the name you are going to use to call it in the php code should be in the left side:
data:{firstname:name, email:email, comment:message, action:'validate_form'},
remember that your variable your are passing are:
var name = jQuery(".firstname").val(); var email = jQuery(".email").val(); var message = jQuery(".textarea").val();
and in your php you are going to call like this:
$name= trim($_POST["firstname"]); $email = trim($_POST["email"]); $comment = trim($_POST["comment"]);
I am trying to get get my form to submit without having the page refreshing everytime
However, when I insert the ajax and place the php into a new file the form doesnt submit and I dont understand why?
Any advice would be appreicated!
PHP
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['phone'], $_POST['message'])){
//Post data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
//mail settings
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
$header = "From: $email";
if($_POST) {
if($name == '' || $email == '' || $phone == '' || $message == '') {
echo $feedback = "<font color='red'> *Please Fill in All Fields!";
}
else {
mail($to, $subject, $body, $header);
echo $feedback = "<font color='green'> *Message sent! You will receive a reply shortly!";
}
}
}
else{
echo $feedback = "<font color='red'> Missing Params";
}
?>
AJAX
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#submitBtn").click(function( event ) {
//values
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
event.preventDefault();
});
});
</script>
HTML CODE HERE: http://www.codeply.com/go/e3jAo1WrPl
The .bind() function may be the way to go with this form, since it binds the action of clicking the button to the event handler.
It also may be beneficial to have the event.preventDefault() before your ajax call.
$(document).ready(function(){
$("#submitBtn").bind([boundElement],function( event ) {
event.preventDefault();
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
return true;
});
});
I would recommend double-checking the syntax for the bound element in the .bind() parameters. It is single quote marks for referring to a named form element
Example HTML:
This might help you with your problem:
$(document).ready(function() {
$("#contact").submit(function(event) {
event.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
message = $('#message').val(),
occasion = $('#occasion').val(),
dataString = $(this).serialize();
$.ajax({
url: 'php.php',
type: 'post',
data: dataString,
})
.done( function( html ) {
$( '#feedback' ).html( html );
})
.fail( function( response ) {
console.log( response );
});
});
});
Firs of all, you have the form and the submit button, so when you press the button, the event 'submit' is triggered, so you prevent the event to be fired, then you do your coding, the variables, but I cannot understand why you declare all those, if you don't use them, but that's up to you.
Here is a suggestion with using a button in stead of a submit. I commented out the preventDefault, because it is unnecessary in this case -- we are not actually submitting the form. This gives us more control.
The request is submitted. In this case, it obviously fails. In your case, whether or not it fails is going to depend on what you have going on server side.
http://plnkr.co/edit/txuxaFUkgFq9SFDcqUdp
<form action="http://www.yahoo.com" id="contactForm" method="get" target="_blank">
<div class="innerForm">
<label for="name">Name:</label>
<input id="name" name="name" type="text" />
<label for="phone">Phone:</label>
<input id="phone" name="phone" type="text" />
<label for="email">Email:</label>
<input id="email" name="email" type="text" />
<label for="occasion">Occasion:</label>
<input id="occasion" type="text" name="occasion" />
<label id="messageLabel" for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button id="test">test</button>
<!--input type="submit" value="Submit" id="submitBtn" name="submit" onclick="return chk();"/ -->
</div>
<div id="feedback"></div>
</form>
$(document).ready(function(){
$("#test").click(function (event) {
//values
alert("test clicked");
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var message = document.getElementById('message').value;
var occasion = document.getElementById('occasion').value;
var dataString = $("#contactForm").serialize();
$.ajax({
type: "get",
url: "http://www.yahoo.com",
data: dataString,
success: function (html) {
alert("success");
//$('#feedback').html(html);
},
error: function(result){
alert("failure");
}
});
//event.preventDefault();
});
});