Form validated but no email send - javascript

have some problems with my form which is being validated correctly, but when clicking submit button no email is going out. Mail fucntion is enabled on server as i checked raw mail sending. What can be wrong here? See my code below
HTML and JS:
....
<!-- Bootstrap Css -->
<link href="bootstrap-assets/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/validator.min.js"></script>
<!-- Style -->
<link href="plugins/owl-carousel/owl.carousel.css" rel="stylesheet">
<link href="plugins/owl-carousel/owl.theme.css" rel="stylesheet">
<link href="plugins/owl-carousel/owl.transitions.css" rel="stylesheet">
<link href="plugins/Lightbox/dist/css/lightbox.css" rel="stylesheet">
<link href="plugins/Icons/et-line-font/style.css" rel="stylesheet">
<link href="plugins/animate.css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<!-- Icons Font -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script>
$(document).ready(function () {
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
console.log("rrrr");
} else {
console.log("fff");
// everything looks good!
event.preventDefault();
submitForm();
}
});
});
$(document).ready(function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
});
$(document).ready(function formSuccess() {
$("#msgSubmit" ).removeClass( "hidden" );
});
</script>
contact form:
<form role="form" id="contactForm">
<div class="row">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="Wpisz swoje imię, nazwisko" required="required">
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Enter email" required>
</div>
<div class="form-group">
<textarea id="message" name="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
</div>
<button type="submit" id="form-submit" class="btn-block">Wyślij wiadomość</button>
<div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div>
</div>
</form>
procrss.php:
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "george#hgtg.com";
$Subject = "New Message Received";
// send email
$success = mail($EmailTo, $Subject, $message, $email);
// redirect to success page
if ($success){
echo "success";
}else{
echo "invalid";
}
?>

The fourth argument of mail should be additional headers, not just the sender's email address. So you've to rewrite your function:
$headers = 'From: ' . $email . "\r\n";
$success = mail($EmailTo, $Subject, $message, $headers);
But I'd suggest you add the sender's email to the message body. Since the suggested solution is vulnerable due to missing checks on the sender's email address.
$message .= "\n\n" . 'From: '. $email;
$success = mail($EmailTo, $Subject, $message);

The second function isn't what you seem to think it is, it's just DOM ready handler that you have given a name to, and you should see an error in the console telling you that submitForm() is not defined.
Change it to just
function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
... etc
}
instead of
$(document).ready(function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
....
EDIT: open the console (F12), and add some logs to see what's happening
$(document).ready(function() {
$("#contactForm").validator().on("submit", function(event) {
if (event.isDefaultPrevented()) {
console.log("rrrr");
} else {
event.preventDefault();
submitForm();
}
});
$("#msgSubmit").removeClass("hidden");
});
function submitForm() {
$.ajax({
type: "POST",
url: "process.php",
data: $("#contactForm").serialize(),
success: function(text) {
console.log(text); // should be "invalid" or "success"
},
error : function() {
console.log('epic fail');
}
});
}

Hiding your "Message submitted" message and clearing the inputs after a specified time is straightforward.
You would do this with a call to setTimeout(). Something like this:
setTimeout( function() { myCleanupFunction(); }, 5000 );
That will call myCleanupFunction() after a 5 second wait.
Documentation on how to use setTimeout().
or what it looks like in the original code:
formSuccess() {
$("#msgSubmit" ).removeClass( "hidden" );
setTimeout( function() { myCleanupFunction(); }, 5000 );
}

Several of your javascript functions are being called at page load time, which is not what you are intending.
Only put functions in a $(document).ready() statement when you want those functions to run at page load time.
Here's a working version of your javascript, and a jsfiddle that replaces the $.ajax function with a test function called testAjax. All testAjax does is call your success function. (replace ajaxTest with $.ajax in production). You'll see that the jsfiddle behaves as you want.
function formSuccess() {
$("#msgSubmit" ).removeClass( "hidden" );
document.getElementById('msgSubmit').innerHTML = 'Message submitted!';
setTimeout( function () {
$("#msgSubmit" ).addClass( "hidden" );
}, 5000
);
}
// test version of ajax, replace with real "$.ajax()" in production
function ajaxTest( ajaxData ) {
// just a test, so call the success callback
ajaxData.success( 'success' );
}
function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
// replace 'ajaxText' with '$.ajax' in production
ajaxTest({
type: "POST",
url: "process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
$(document).ready(function () {
$("#contactForm").on("submit", function (event) {
// prevent default form submit
event.preventDefault();
// call our own submit
submitForm();
}
);
});

Related

PHP/Ajax Form Sumission

I have designed a Sidebar Floating Form with PhP/Ajax which is working and sending submission to my targeted email. Here is the Link: http://logohour.com/form.html but when a visitor fill and submit the form successfully it routes him to another page for the confirmation.
This shouldn't be like this and must be stick to the homepage with popup Message as per my coding:
<div id="sendingMMessage" class="statusMessage"> <p>Sending your message. Please wait...</p> </div>
<div id="successMMessage" class="statusMessage"> <p>Thanks for sending your message! We'll get back to you shortly.</p> </div>
Below you may find my Ajax & PHP for reference:
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example#gmail.com" );
define( "EMAIL_SUBJECT", "SiderBar Visitor Message" );
// Read the form values
$ssuccess = false;
$Name = isset( $_POST['Name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['Name'] ) : "";
$Email = isset( $_POST['Email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Email'] ) : "";
$Phone = isset( $_POST['Phone'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Phone'] ) : "";
$Country = isset( $_POST['Country'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Country'] ) : "";
$Select = isset( $_POST['Select'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Select'] ) : "";
$Message = isset( $_POST['Message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['Message'] ) : "";
// If all values exist, send the email
if ( $Name && $Email && $Phone && $Country && $Select && $Message ) {
$msgToSend = "Name: $Name\n";
$msgToSend .= "Email: $Email\n";
$msgToSend .= "Phone: $Phone\n";
$msgToSend .= "Sender Country: $Country\n";
$msgToSend .= "Sender Select: $Select\n";
$msgToSend .= "Message: $Message";
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $Name . " <" . $Email . ">";
$ssuccess = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $ssuccess ? "ssuccess" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $ssuccess ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$ssuccess ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
var messageDDelay = 2000; // How long to display status messages (in milliseconds)
// Init the form once the document is ready
$(init);
// Initialize the form
function init() {
// Hide the form initially.
// Make submitForm() the form's submit handler.
// Position the form so it sits in the centre of the browser window.
// When the "Send us an email" link is clicked:
// 1. Fade the content out
// 2. Display the form
// 3. Move focus to the first field
// 4. Prevent the link being followed
$('a[href="#contact_form"]').click(function() {
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
})
return false; });
// When the "Cancel" button is clicked, close the form
$('#cancel').click(function() {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);
});
// When the "Escape" key is pressed, close the form
$('#contact_form').keydown(function(event) {
if (event.which == 27) {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);}});}
// Submit the form via Ajax
function submitFForm() {
var contact_form = $(this);
// Are all the fields filled in?
if (!$('#Name').val() || !$('#Email').val() || !$('#Phone').val() || !$('#Country').val() || !$('#Select').val() || !$('#Message').val()) {
// No; display a warning message and return to the form
$('#incompleteMMessage').fadeIn().delay(messageDDelay).fadeOut();
contact_form.fadeOut().delay(messageDDelay).fadeIn();
} else {
// Yes; submit the form to the PHP script via Ajax
$('#sendingMMessage').fadeIn();
contact_form.fadeOut();
$.ajax({
url: contact_form.attr('action') + "?ajax=true",
type: contact_form.attr('method'),
data: contact_form.serialize(),
ssuccess: submitFFinished }); }
// Prevent the default form submission occurring
return false; }
// Handle the Ajax response
function submitFFinished(response) {
response = $.trim(response);
$('#sendingMMessage').fadeOut();
if (response == "ssuccess") {
// Form submitted ssuccessfully:
// 1. Display the ssuccess message
// 2. Clear the form fields
// 3. Fade the content back in
$('#successMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#Name').val("");
$('#Email').val("");
$('#Phone').val("");
$('#Country').val("");
$('#Selct').val("");
$('#Message').val("");
$('#content').delay(messageDDelay + 500).fadeTo('slow', 1);
} else {
// Form submission failed: Display the failure message,
// then redisplay the form
$('#failureMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#contact_form').delay(messageDDelay + 500).fadeIn(); } }
Below the simple ajax form submission. Hope it will help your need.
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(function () {
$('form#consultationForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'receivedConfirmation.php',
data: $(this).serialize(),
success: function (result) {
console.log(result);
$('#receivedStatus').attr('style','display:block');
$('#receivedStatus').html(result);
}
});
e.preventDefault();
});
});
</script>
<form id="consultationForm" method="post">
Firstname: <input name="fname" />
Lastname: <input name="lname" />
<div style='clear:both;'></div>
<input type="submit" name="submit" value="save"/>
<input type="reset" name="cancel" value="cancel"/>
</form>
<div id='receivedStatus' style='display:none;'></div>
receivedConfirmation.php
<?php
echo "<PRE>";
print_r($_POST);
echo "</PRE><br>";
//do your DB stuffs here and finally echo your response based on success or failure
echo "Thanks for sending your message! We'll get back to you shortly.";
echo "<br>Click your browser's Back button to return to the page."
?>
First you have to avoid the normal form submission for this form and you can do this by using normal button instead of submit button.
<input type="button" id="sendMMessage" name="sendMMessage" value="Submit">
Execute a javascript ajax submit code onclick of sendMMessage id.
and this will solve your problem.
Updated answer :
$( "#target" ).click(function() {
// put your ajax form submit code here
$.ajax({
type: "POST",
url: 'http://logohour.com/sidebar-form.php',
data: $("#contact_form").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data); // show response from the php script.
}
});
});
If you are still unclear about this I will explain you more detail.
thanks.

PHP Email says it sent, but when I open my inbox there is no message

I am trying to create a contact us form in jquery, ajax, and php. when i click the button in html jquery and ajax make the request to php and then i use the php mail() function to send the email. however, when i click "send" it says everything is ok and the ajax function success function runs alerting the user the message was sent. now, when i go to the inbox where it is supposed to be sent i don't get any email. i am running this on windows 7, ecowebhost.
here is the html form;
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src = "js/callmail.js"></script>
</head>
<body ng-app = "">
<div class = "container">
<form name = "contact">
<label for = "subject" class = "control-label">Subject:</label>
<input name = "subject" id = "subject" ng-model = "subject" required/>
<span class = "warning" ng-show="contact.subject.$touched && contact.subject.$invalid">You Must Enter a subject!</span>
<span class = "success" ng-show="contact.subject.$touched && contact.subject.$valid">Valid!</span>
<br/>
<label for = "body" class = "control-label">Body:</label>
<input name = "body" id = "body" ng-model = "body" required/>
<span class = "warning" ng-show="contact.body.$touched && contact.body.$invalid">Your email must have a body!</span>
<span class = "success" ng-show="contact.body.$touched && contact.body.$valid">Valid!</span>
<br/>
<label for = "signature" class = "control-label">Return Email:</label>
<input name = "signature" id = "signature" ng-model = "signature" type = "email" required/>
<span class = "warning" ng-show="contact.signature.$touched && contact.signature.$invalid">You must enter a valid return email!</span>
<span class = "success" ng-show="contact.signature.$touched && contact.signature.$valid">Valid!</span>
<br/>
<button ng-disabled = "contact.$invalid" id = "sendmail" type = "submit" class = "btn btn-success">Submit</button>
</form>
here is the ajax and jquery:
$(function() {
$("#sendmail").click(function() {
var data = {
to: "tyler.psu.grim#gmail.com",
subject: $("#signature").val() + ": " + $("#subject").val(),
message: $("#body").val(),
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function() {
alert("Message sent");
}
});
console.log(data);
});
});
and here is the php code:
<?php
if ($_POST["submit"]) {
$subject = $_POST["subject"];
$message = $_POST["body"];
$headers = "Reply to: " . $_POST["signature"];
mail("tyler.psu.grim#gmail.com", $subject, $message, $headers);
}
?>
Very new to each of these languages so i have absolutely no idea where to go from here.
$(function() {
$("#sendmail").click(function() {
var to = "tyler.psu.grim#gmail.com";
var subject = $("#signature").val() +": " + $("#subject").val(); //?? WHERE IS SUBJECT INPUT????
var message = $("#body").val();
var signature = $("#signature").val();
var data = {
to: to,
subject: subject,
message: message,
signature: signature
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(msg) {
console.log(msg);
}
});
console.log(data);
return false;
});
});
/////
if(isset($_POST["subject"])) {
$subject = $_POST["subject"];
$message = $_POST["body"];
$headers = "Reply to: " . $_POST["signature"];
if(!mail("tyler.psu.grim#gmail.com", $subject, $message, $headers)) {
echo 'something is wrong';
} else {
echo 'nothing is wrong';
}
}
And you might want to check the spam folder as well.
Are you sending from localhost or your own website?
Some webserver software such as xampp do not allow/execute? this mail function by default.

Sending e-mail form using PHP and AJAX

I have contact form on my site. It sends message to email. I try to do it without page reload using AJAX, but it seems that AJAX doesn't work: messages are sent but the page still redirecting to call-form.php. What is incorrect in my code? (jQuery is included)
HTML
<form name="freeCall" action="<?php bloginfo(template_url); ?>/mail/call-form.php" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
</form>
PHP - call-form.php
<?
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
}
?>
JS
$(function () {
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
});
Ok, first when you make an AJAX call, you must have a way to know if your PHP returns you something (useful for debugging).
Then, when submitting a form with AJAX, the tag action="" is not needed.
Finally, to prevent a form from being sent when making an AJAX call, add e.preventDefault() with the event called e here, like in my example.
I have improved your code to be more realistic about the latest standards.
HTML :
<form name="freeCall" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
JS :
$(function () {
$("#free-call-form").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
dataType: "json", // Add datatype
data: form_data
}).done(function (data) {
console.log(data);
alert("It's OK!");
}).fail(function (data) {
console.log(data);
});
});
});
And PHP :
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}
With echo json_encode, you know what is the return of your AJAX call. It is better
You're not preventing the default submit action -
$("#free-call-form").submit(function (event) { // capture the event
event.preventDefault(); // prevent the event's default action
Returning false or preventing the default behavior of the event should work for you.
Example with old .submit(), that now is an alias of .on('eventName'); and using return false to avoid form submission.;
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
return false;
});
Example using .on('eventName') and using e.preventDefault() to avoid form submission.
$("#free-call-form").on('submit', function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
From Jquery .submit() Documentation: This method is a shortcut for
.on( "submit", handler ) in the first variation, > and .trigger(
"submit" ) in the third.
Also, you would consider not using EVER the user input directly, it would not cause problems in this exact context (or maybe yes) but with your actual approach they can change the mail markup or adding some weirds things there, even scripts, you would consider escape, validate or limit it.
Also as zLen pointed out in the comments:
the action in the form markup is not necessary because you are not using it, you can remove it:
action="<?php bloginfo(template_url); ?>/mail/call-form.php"
What is happening is your form is being submitted, it's not actually the AJAX call which is doing it. To fix it, add
return false;
at the end of the submit function so that the browser doesn't submit the form and the AJAX call happens properly.

Issued loading PHP data to HTML file using JavaScript

I am writing a Shoutbox. The HTML file has 2 buttons: refresh - refreshes all the messages and submit - submits message and refreshes page messages.
Everything works perfectly but one issue. When I click submit, the page doesn't refresh with latest message. But everything works fine afterwards.
HMTL file:
<head>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script src="script.js"></script>
</head>
<body>
<div id="wrap">
<div id="input">
<form>
<input type="text" name="name" id="name" placeholder="Enter a name">
<input type="text" name="message" id="message" placeholder="Enter a message">
<input type="button" id="refresh" value="Refresh">
<input type="button" id="submit" value="Submit">
</form>
</div>
<div id="messages">
<ul id="messageList"></ul>
</div>
</div>
</body>
</html>
JavaScript File
$(document).ready(function() {
$('#refresh').on('click', function(){
$("#messageList").load( "messages.php");
event.preventDefault();
});
});
$(document).ready(function() {
$('#submit').on('click', function(){
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
$.post( "newmessage.php", dataString );
event.preventDefault();
$("#messageList").load( "messages.php");
event.preventDefault();
});
});
messages.php:
<?php
//error_reporting(0);
include 'database.php';
//Create Select Query
$query = "SELECT * FROM shoutbox ORDER BY time DESC";
$shouts = mysqli_query($con, $query);
while($row = $shouts->fetch_object()) {
$time = $row->time;
$name = $row->name;
$message = $row->message;
echo "<li>".$time." - <b>".$name.": </b>".$message."</li>";
}
$con->close();
?>
newmessage.php:
<?php
//error_reporting(0);
include 'database.php';
if(isset($_POST['name']) && isset($_POST['message']))
{
$name = '"'.$_POST['name'].'"';
$message = '"'.$_POST['message'].'"';
$datum = new DateTime();
$timeStamp = $datum->format('Y-m-d H:i:s');
$insert_row = $con->query("INSERT INTO shoutbox(name, message) VALUES($name, $message)");
}
if($insert_row) {
} else {
die('Error : ('. $con->errno .') '. $con->error);
}
$con->close();
?>
From this answer:
I'd recommend strongly that you take the time to understand the nature of asynchronous calls within JavaScript
Please follow the link, there's more info there.
To your code to work:
$(document).ready(function() {
$('#submit').on('click', function(event){ // << event was missing
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
event.preventDefault();
$.post("newmessage.php", dataString, function(){
// this function is a callback, called on AJAX success
$("#messageList").load( "messages.php");
});
});
});
This should do the job. Make sure if you are using event.preventDefault(), you pass the event variable to the function. This can also test if the message was posted successfully
$('#submit').on('click', function(event){
event.preventDefault();
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
var posting=$.post( "newmessage.php", dataString );
posting.done(function(data){
$("#messageList").load( "messages.php");
});
posting.fail(function(){
alert("Something is not right with your message. Please Try Again")
})
});

send form via AJAX in jQuery then save in MySQL but doesn't work

as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem

Categories

Resources