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();
});
});
Related
Site pulled on WordPress.
The usual forms on the site work, but in the modal window does not.
The console shows nothing. The send button does not respond.
Broke my head. Help find the problem.
Code JS:
$(document).on("submit", "form", function () {
var formID = $(this).attr('id');
var formNm = $('#' + formID);
$.ajax({
type: "POST",
url: 'mail.php',
data: formNm.serialize(),
success: function (data) {
$(formNm).html(data);
},
error: function (jqXHR, text, error) {
$(formNm).html(error);
}
});
return false;
});
Html form on pop-up (id different):
<form action="mail.php" method="POST" id="formModal1">
<input type="text" name="t-number" placeholder="Ваш телефон" required />
<input type="submit" placeholder="Получить консультацию" />
</form>
Php :
<?php
if (isset($_POST['t-number'])) {$phone = $_POST['t-number'];}
if (isset($_POST['email'])) {$email = $_POST['email'];}
$address = "";
$mes = "Тема: Заказ обратного звонка!\nТелефон: $phone\nE-mail: $email";
$sub='Заказ';
$mail='Заказ <Центр юридической помощи>';
$send = mail ($address,$sub,$mes,"Content-type:text/plain; charset = utf-8\r\nFrom:$mail");
ini_set('short_open_tag', 'On');
?>
I am trying to implement a modal AJAX form. But when I press "Submit" I only receive empty body emails. I guess I have bugs in PHP code.
HTML:
<form class="form" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="text" name="phone" placeholder="Phone">
<input type="submit" value="Submit" >
</form>
Jquery:
$(".form").submit(function() {
var this1= $(this);
var form_data = $(this).serialize();
if (is_empty(this1)){
$.ajax({
type: "POST",
url: "feedback.php",
data: form_data,
success: function (res) {
swal("Thank you", "very much", "success");
$('.black_layout').fadeOut(200);
$('.main_form_wrapper').fadeOut(200);
this1.trigger('reset');
}
});
}
return false;
});
PHP in feedback.php file:
parse_str($_POST['form_data'], $formdata);
$name = $formdata['name'];
$phone=$formdata['phone'];
$formcontent="From: $name \n Phone: $phone";
$recipient = "email#gmail.com";
$subject = "MAIL HEADER";
mail($recipient, $subject, $formcontent) or die("Error");
EDIT:I am also not getting a "Thank you" message for some reason.
You have an error during sending form data with ajax request. here is your code which is working fine :
JQuery :
$(".form").submit(function() {
var this1= $(this);
var form_data = $(this).serialize();
alert(form_data);
//if (is_empty(this1)){
$.ajax({
type: "POST",
url: "feedback.php",
data: {'form_data' : form_data },
success: function (res) { alert(res);
//swal("Thank you", "very much", "success");
$('.black_layout').fadeOut(200);
$('.main_form_wrapper').fadeOut(200);
this1.trigger('reset');
}
});
//}
return false;
});
I have a contact form php+jquery+HTML.the form div is hidden in index.HTML,until contact button is presses.Jquery works,Ajax call posts needed data to php,which echoes a response.The problem is when php echoes,instead of remaining on same page without refreshing,browser redirects to contact.php,where the echo is showed correctly.I think the Ajax part won't catch the response from server,although syntax is the same in all tutorials.please assist.
html part:
HTML
<div id = 'contact_form'>
<div id = 'result'></div>
<form id="contactform" action="js/contact.php" method="POST" enctype="multipart/form-data">
<div class="row">
<input id="name" class="input" name="name" type="text" required = 'true' value="" size="30" placeholder='Nome'/>
</div>
<div class="row">
<input id="email" class="input" name="email" type="text" required = 'true' value="" size="30" placeholder = 'Email'/>
</div>
<div class="row">
<textarea id="message" class="input" name="message" rows="7" cols="50" required = 'true' placeholder = 'Messagio'></textarea>
</div>
<input id="submit_button" class = 'myButton' type="submit" value="Manda messagio" />
</form>
</div>
</div>
JS
$('#submit_btn').click(function(){
var user_name = $("input#name").val();
if (user_name == "") {
$("input#name").focus().addClass('active');
return false;
}
var user_email = $("input#email").val();
if (!$("input#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("input#email").focus().addClass('active');
return false;
}
var msg = $("textarea#message").val();
if (message == "") {
$("textarea#message").focus().addClass('active');
return false;
}
var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function(d) {
console.log(d);
}
});
return false;
});
PHP
<?php
$toEmail = "x#gmail.com";
$subject = "dal tuo sito ";
$mailHeaders = "From: " . $_POST["name"] . "<". $_POST["email"] .">\r\n";
if(mail($toEmail,$subject,$_POST["message"], $mailHeaders)) {
echo "Mail Sent";
} else {
echo "Problem in Sending Mail";
}
?>
If you want to keep the same button you can change your js.
$('#submit_btn').click(function(e){
e.preventDefault();
//YOUR CODE HERE
}
Because you used a submit type input, I recommend you change the submit input for a link like button. And also remove the action attr from the form:
HTML
Send
JS
<script>
$('#btn').on("click", function(){
//Your ajax here
//var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: {name: user_name, email: user_email, message: msg}
}).done(function(response){
console.log(response);
});
});
</script>
The goal is that once a the submit button is clicked, instead of going to send.php, it will just keep the page, I don't even want the page reloaded. If you guys have another way of doing this, that would be perfectly fine too.
My Ajax code
$("#sendtxt").click(function(e) {
e.preventDefault();
var phonenum = $("#phonenum").val();
var provider = $("#provider").val();
var message = $("#message").val();
$.ajax({
type : 'POST',
data : dataString,
url : 'send.php',
success : function(data) {
alert(data);
}
});
});
My Form code
<form name="reqform" action="" method="post">
<h1>Phone Number:
<input name="phonenum" id="phonenum" type="text" class="txtbox-style" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required/>
<select name = "provider" id ="provider" class="txtbox-style" required>
<option value="#sms.mycricket.com">Cricket Wireless</option>
</select>
<br/>
Message:
<input name="message" id="message" type="text" class="txtbox-style"/>
<br/>
How many times?
<input name="amount" id="amount" type="number" min="1" max="20" class="txtbox-style" required/>
<br />
<input type="submit" id="sendtxt" name="sendtxt" class="btn-style" value="Start Sending" />
</h1>
</form>
My send.php
<?php
$to = $_POST["phonenum"];
$provider = $_POST["provider"];
$subject = 'Hi';
$message = $_POST["message"];
$headers = 'From: Hello' . phpversion();
mail($to . $provider, $subject, $message, $headers);
?>
Your data attribute wasn't correct, there was nothing being sent. You can try it like this, this will work:
You have to have jQuery included in your page, you can do this with this line and place it above your script:
<script>
$(document).ready(function(){
$('input[name="phonenum"]').keyup(function(e) {
if (/\D/g.test(this.value)) {
// Filter non-digits from input value.
this.value = this.value.replace(/\D/g, '');
}
});
$("#sendtxt").click(function(e) {
e.preventDefault();
var phonenum = $("#phonenum").val();
var provider = $("#provider").val();
var message = $("#message").val();
$.ajax({
type : 'POST',
data : {
provider : provider,
// ^key that appears in post
message : message,
// ^var you fetched before from the input
phonenum : phonenum
},
url : 'send.php',
success : function(data) {
alert(data);
console.log('Success');
},
error : function(xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
});
});
</script>
EDIT:
Check your console for errors (F12 in chrome), if there's an error, it will look like this, or similar:
If ajax succeeds, there will be at least "Success"
ANOTHER EDIT:
Put your form out of the <h1> tag, use it like this:
<h1>Phone Number:</h1>
and delete the </h1> at the end of your form...
I prefer binding form's submit event (Because user may hit enter on focused <input> element, not submitting by clicking <input type="submit">), additionally there is an easier data colletion approach:
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
data : $(this).serialize(),//Here we collect all entered data
url : 'send.php',
success : function(data) {
alert(data);
}
});
});
I think that the best Approach is to use the jquery $.post method
$("form").submit(function(e) {
e.preventDefault();
$.post('send.php', $( this ).serialize()).done(function(data){
alert(data);
});
}
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.post/
** update **
example js fiddle:
http://jsfiddle.net/de71ju0r/1/
I have a small commenting system that I have modified and try implement into the site. It's in 'ajax'. When the jQuery with HTML is embedded into the page the commenting system works fine - i.e. when the user clicks on a submit button the code returns 'false', stops the page from refreshing and submits data. BUT when I implemented the code within my site and placed it in a seperate .js file the code for some reason doesn't work properly. I mean - the page after the onclick refreshes. Why is that so ? The code is not changed at all - when on its own, it works but not in the index.php site when implemented. I tried to change input type to 'button' and call a function from onclick - the page doesn't refresh but also doesn't insert the input..I'm running out of ideas as to why it is that so. Here's the code:
$(document).ready(function () {
$(".submit").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var comment_area = $("#comment_area").val();
var dataString = 'name=' + name + '&email=' + email + '&comment_area=' + comment_area;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if (name == '' || !emailReg.test(emailaddressVal) || comment == '') {
alert('Please enter valid data and type in message'); return false;
}
else {
$.ajax({
type: "POST",
url: "comments.php",
data: dataString,
cache: false,
success: function (html) {
$("#com_list").append(html);
$("#com_list").fadeIn("slow");
$("#flash").fadeOut('fast');
}
});
} return false;
});
});
//END
//COM LIST
//HTML / PHP
<div class="slider">
<form id="comment_form" name="comment_form" method="post" action="#"
enctype="multipart/form-data">
<input type="text" id="name" name="name" maxlength="16"/> Name<br /><br/>
<input type="text" id="email" name="email"/> Email (will not show)<br /><br/>
<textarea id="comment_area" name="comment_area" maxlength="1000"></textarea><br /><br/>
<input type="submit" class="submit" name="submit_comment" value="submit"/> &
nbsp;comment or <a href="index.php" id="cancel"
onmousedown="$('.slider').hide();$('#com_list').show();"><u>cancel</u></a>
</form>
</div>
//comments.php
if($_POST) {
$name=$_POST['name'];
$email=$_POST['email'];
$comment_area=$_POST['comment_area'];
//$lowercase = strtolower($email);
//$image = md5( $lowercase );
$insert = mysqli_query($connect,"INSERT INTO comments (name,email,comment,com_date)
VALUES ('$name','$email','$comment_area',curdate())");
}
////////////////
Thanks for any suggestions..
aha!
there is an error in your js:
in my console i'm getting "comment is not defined "
if(name=='' || !emailReg.test(emailaddressVal) || comment=='')
and earlier you have:
var comment_area = $("#comment_area").val(); //<--
change this to comment and it'll get past that at least.
EDIT: a little background. when firefox hits an error, sometimes it'll swallow it, and just stop running any javascript after that error, so your return false and or prevent default code isn't fire, so it's still going to post the form and refresh the page.
Change this line:
$(".submit").click(function () {
To this:
$("#comment_form").submit(function () {
The submit event gets triggered on the <form> element, not on the submit button.
Keep your damn code clean, so you can understand what you are cooking...
This will work for you:
$(document).ready(function(){
$("#comment_form").submit(function(e){
e.preventDefault(); // stop refresh
var name = $("#name").val();
var email = $("#email").val();
var comment_area = $("#comment_area").val();
var dataString = 'name='+ name + '&email=' + email + '&comment_area=' + comment_area+'&submit_comment=true';
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(name=='' || !emailReg.test(emailaddressVal) || comment==''){
alert('Please enter valid data and type in message');
} else{
$.ajax({
type: "POST",
url: "comments.php",
data: dataString,
cache: false,
success: function(html){
$("#com_list").append(html);
$("#com_list").fadeIn("slow");
$("#flash").fadeOut('fast');
}
});
}
});
$('#cancel').click(function(e){
e.preventDefault();
$('.slider').hide();
$('#com_list').show();
});
});
Here is some more clean code...
<div class="slider">
<form id="comment_form" name="comment_form" method="post" action="#" enctype="multipart/form-data">
<input type="text" id="name" name="name" maxlength="16"/> Name<br /><br/>
<input type="text" id="email" name="email"/> Email (will not show)<br /><br/>
<textarea id="comment_area" name="comment_area" maxlength="1000"></textarea><br /><br/>
<input type="submit" class="submit" name="submit_comment" value="submit"/> comment or <u>cancel</u>
</form>
</div>
Here is some other clean and SECURE code
<?php
if(isset($_POST['submit_comment'])){
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$comment_area = mysql_real_escape_string($_POST['comment_area']);
//$lowercase = strtolower($email);
//$image = md5( $lowercase );
$query = 'INSERT INTO comments (name,email,comment,com_date) '.
"VALUES ('$name','$email','$comment_area',CURDATE())";
$insert = mysqli_query($connect, $query);
}
?>