Why cant ajax find php file when submitting form? - javascript

I have a form, making an ajax post request but it wont find the php file.Ive tried anything and read through so many posts here and tried everything suggested but nothing helps.
I tried to use an absolute path as that was suggested somewhere. Doesnt work.
relative path doesnt work either
I tried to put the submit button outside of my form in my html file (was suggested in another post) - doesnt work either.
Anyone knows why?
EDIT: Im getting a 404
file structure:
myApp/app/js/contact.js
myApp/app/mail/contact.php
myApp/app/index.html
html:
<section id="contact">
<form>
name:
<input id="name" type="text" name="name"> email:
<input id="email" type="text" name="email"> message:
<input id="message" type="text" name="message">
<button id="submit">send</button>
</form>
</section>
app/js/contact.js:
$('#submit').click(function (event) {
event.preventDefault() ;
var name = $("#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
console.log("name", name, email);
$.ajax({
url: "/app/mail/contact.php",
type: "POST",
data: {
name: name,
email: email,
message: message
}
})
});
mail/contact.php:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Contact Form';
$to = 'myemail#yahoo.com';
$subject = 'Message from my page ';
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
}
}
?>

This isn't going to solve your issue, but this is a better ux
give your <form> a class or ID and execute your form submission on a form submit
so it would be
$('.formClassName').submit(function(event){
});
This will allow the form submission to fire off the AJAX event on the submit button click, as well as if the user hits the enter button.

In your html file, put your scripts before </body> tag
<section id="contact">
<form>
name:
<input id="name" type="text" name="name"> email:
<input id="email" type="text" name="email"> message:
<input id="message" type="text" name="message">
<button id="submit">send</button>
</form>
</section>
<script type="text/javascript" src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/app/js/contact.js"></script>
</body>

Instead of using
url: "/app/mail/contact.php",
use:
url: "mail/contact.php",

Related

Submit a HTML form without redirection and showing a success message

I decided to switch from a WordPress website to a self-made with HTML, CSS and JS, aiming to improve performance. So far, relying on tutorials, I've managed to deal with almost every issue, but I just can't get the contact form work the way it worked in WP. So far it redirects me to another page that shows the success message, which is just ugly.
Basically, I want the submit button to do 3 things: 1. Not to redirect me to another page. 2. Reset the form. 3. Display a success message.
Read many similar questions here, but as I am completely unfamiliar with AJAX, finally decided to post this question. Here's my code:
Index.html:
<div>
<form method="post" action="form.php" name="myForm">
<input name="name" placeholder="Nombre" required>
<input name="email" type="email" placeholder="Correo Electrónico" required>
<textarea rows="10" name="message" placeholder="Mensaje" required></textarea>
<input id="submit" name="submit" type="submit" value="Enviar Mensaje" class="boton-rojo">
</form>
</div>
and in form.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="De: $name \n Mensaje: $message";
$recipient = "contacto#mydomainname.cl";
$subject = "Mensaje desde el sitio web";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Tu consulta fue recibida";
?>
Any help would be much appreciated.
Thanks.
Put an ID to your form
<form id='myForm'>
....
</form>
Use jQuery (For easy code)
....
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</body>
Use $.ajax
$('#myForm').submit(function(e) {
e.preventDefault(); // prevent from submitting form directly
$.ajax({
url: 'form.php',
method: 'post',
data: $("#myForm").serializeArray() // convert all form data to array (key:value)
})
.done(function(response){
alert(response); // show the response
$("#myForm").reset(); // reset the form
})
.fail(function(error){
alert(error); // show the error.
});
})

Form on submit not doing anything

This is the code I'm using to send a form to a php page and then sending an email. Somehow it's not working and I don't get why. The page just reloads (why?) and I cannot see any request being sent. (I'm using MAMP on macOS if this is a useful information).
What's wrong here?
Thank you for helping me out.
PS: also, the page reloads when I click submit. Why and how can I prevent that?
HTML
<div id="form_container">
<form id="contact_form" enctype="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="col">
<input name="name" type="text" class="form-control" placeholder="Name" id="inputName">
</div>
<div class="col">
<input name="surname" type="text" class="form-control" placeholder="Surname" id="inputSurname">
</div>
</div>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Email">
</div>
<br/>
<div class="form-group">
<input name="subject" type="text" class="form-control" id="inputSubject" placeholder="Subject">
</div>
<div class="form-group">
<textarea name="message" class="form-control" id="textArea" rows="4" placeholder="Write your message here"></textarea>
</div>
<div id="btn_container">
<button id="btn_send" name="submit" type="submit" class="btn btn-dark">SEND</button>
<div id="success_send" class="alert alert-success" role="alert">
SUCCESS
</div>
<div id="error_send" class="alert alert-danger" role="alert">
ERROR
</div>
</div>
</form>
</div>
JS
$( document ).ready(function() {
$('#contact_form').submit(function(event) {
$.ajax({
type: 'POST',
url: '../php/email.php',
data: $('#contact_form').serialize(),
success: function() {
$('#success_send').show();
},
error: function(){
$('#error_send').show();
}
});
});
});
PHP
<?php
if($_POST){
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "xxxxxx#xxxx.xxx";
$subject = "Portfolio Mail - ".$subject;
$body = "Name: ".$name."\t".$surname."\nEmail: ".$email."\nMessage: ".$message;
$headers = "From: " . $email;
//send email
mail($to, $subject, $body, $headers);
?>
The page just reloads (why?)
Because you are submitting a form.
The data is sent to the URL specified in the action (default: the current page), and the result is loaded as a new page.
and I cannot see any request being sent.
The submit event handler runs before the form submission happens, this queues up the HTTP request. The browser then immediately leaves the page which kills the JS environment that request belongs to, so it is cancelled.
You should:
Make sure that a non-JS submission of the form Does The Right Thing. See Unobtrusive JavaScript
Stop the default form submission behaviour if the JS runs successfully:
Such
$('#contact_form').submit(function(event) {
event.preventDefault();
$.ajax({
You should add event.preventDefault(); at the start of the submit handler to prevent the default submit action.
As a bonus, you should add a form action attribute since it's technically required:
<form id="contact_form" action="../php/email.php" enctype="multipart/form-data">
Edit: Required in HTML4, optional in HTML5

"Undefined" response when submitting contact form without page refresh

I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.

having trouble in showing php success message with ajax

Here is my below code I'm just trying to send a message form with php script but the message is submitted well. but when it comes to showing success message I'm having trouble page submits the data but shows no code.
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#send").click(function(event){
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(data) {
$('#msg').html(data);
}
});
});
});
</script>
Below is php and html code:
<?php
include 'db.php';
$name=$_POST["name"];
$email=$_POST["email"];
$message=$_POST["message"];
$query = mysqli_query($con, "INSERT INTO test(name, email, message) VALUES ('$name', '$email', '$message')");
if($query){
echo "Your message has been sent successfully!";
}
else{
echo "Your message has been not sent successfully!";
}
mysqli_close($con);
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" class="form-control" id="name" name="name">
<input type="text" class="form-control" id="email" name="email">
<textarea class="form-control" rows="5" id="message" name="message"></textarea>
<button id="send" type="submit" class="btn btn-primary">Send</button>
</form>
<div id="msg" class="alert alert-success hidden"><strong></strong></div>
It is because your form will be submitted as the button has the type submit. By changing the type to button the ajax should be working.
Change type="submit" to type="button"
I hope this will help!

HTML: Get value from text fields and email them

I am using bootstrap to create input fields. When someone clicks the "Submit" button I want the values (if they are valid) to be emailed to myself. I am having trouble even making sure they are valid. Below is my code
<form action="tryjs_submitpage.htm" onsubmit="return myFunction()">
<fieldset class="form-group">
<label for="name">Name*:</label>
<input type="text" class="form-control" id="usr" placeholder="Name">
</fieldset>
<fieldset class="form-group">
<label for="email">Email Address*:</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
</fieldset>
<fieldset class="form-group">
<label for="company">Company:</label>
<input type="text" class="form-control" id="company" placeholder="Company Name">
</fieldset>
<fieldset class="form-group">
<label for="message">Message*:</label>
<textarea class="form-control" rows="5" id="message" placeholder="Message"></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function myFunction() {
var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
submitOK = "true";
if (name.length == 0) {
alert("You must enter your name");
submitOK = "false";
}
if (email == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (message.length == 0) {
alert("You must enter a message");
submitOK = "false";
}
if (submitOK == "false") {
return false;
}
}
</script>
I modified the script from here, but when I click submit it says tryjs_submitpage.htm doesn't exist. Obviously this is an issue, but I can't seem to find tryjs_submitpage.htm anywhere to get it to work. Further I wanted to know if there was a way to trigger an email send with the appropriate information to my personal email. Thanks for the help!
You can't send an email directly with javascript for security reasons.
Suppose there is a feature in JavaScript to send email. Some malicious coder can write a script to send email to some address immediately when you visit their page. This will reveal your email address to some third party without your knowledge. They will start filling your mail box with lots of spam messages! However, there are alternatives as explained below. link
You can however open the user's mail client, to do so:
<form action="" onsubmit="sendMail(); return false">
...
...
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function sendMail() {
var link = "mailto:me#abc.com"
+ "?cc=myCCaddress#example.com"
+ "&subject=" + escape("This is my subject")
+ "&body=" + escape(document.getElementById('myText').value)
;
window.location.href = link;
}
</script>
You can't send a mail directly from the browser, however you can use third party technologies like http://www.emailjs.com/ or create a .php file using php native mail function to send mail.
Below is the HTML, JS(Jquery AJAX) and PHP file that handles mail sending.
In this case the PHP script handles email verification, but you can also use HTML require or JS regex to check at the client side before sending a POST request to the server
HTML
<form method="POST" action="" id="contactform">
<p>
<label for="name">Your Name</label>
<input type="text" name="name" class="input" >
</p>
<p>
<label for="email">Your Email</label>
<input type="text" name="email" class="input">
</p>
<p>
<label for="message">Your Message</label>
<textarea name="message" cols="88" rows="6" class="textarea" ></textarea>
</p>
<input type="submit" name="submit" value="Send your message" class="button transition">
</form>
JS (JQuery)
var $contactform = $('#contactform'),
$success = 'Your message has been sent. Thank you!',
$url = 'link to the hosted php script';
$contactform.submit(function(e) {
$.ajax({
type: 'POST',
url: $url,
data: $(this).serialize(),
dataType: "json",
xhrFields: {
withCredentials: true
}
})
.done(function(msg) {
console.log(msg)
if (msg.success == true) {
response = '<div class="success">' + $success + '</div>';
}
else {
response = '<div class="error">' + msg.errors + '</div>';
}
// Hide any previous response text.
$('.error, .success').remove();
// Show response message.
$contactform.prepend(response);
})
.fail(function(msg) {
console.log(msg)
});
e.preventDefault();
});
PHP
<?php
// Array to hold validation errors and response data.
$errors = array();
$data = array();
// Validate the variables
// if any of these variables don't exist, add an error to our $errors array
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$nospace_name = trim($_POST['name']);
$nospace_email = trim($_POST['email']);
$nospace_message = trim($_POST['message']);
// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: *');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'POST') {
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Max-Age: 604800');
//if you need special headers
header('Access-Control-Allow-Headers: x-requested-with');
}
if (empty($nospace_name))
$errors['name'] = "Name field is required.";
if (empty($nospace_email))
$errors['email'] = "Email field is required.";
if (empty($nospace_message))
$errors['message'] = "I would love to see your message.";
if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
$errors['bad_email'] = "Please enter a valid email address";
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// if there are no errors process our form, then return a message
// prepare message to be sent
$to = "admin#example.com";
$subject = "Website Contact Form: ".$name;
$headers = "From: noreply#example.com\n"; // email address the generated message will be from. Recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: ".$email;
// build the message
$message = "Name: ".$name."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Message: ".$msg;
// send it
$mailSent = mail($to, $subject, $message, $headers);
// check if mail was sent successfully
if (!$mailSent) {
$errors['unknown_error'] = "Something went wrong...Please try again later";
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
}
}
// return all our data to an AJAX call
echo json_encode($data);
?>
My advice is don't do the form validation yourself, just let the browser do it. You will need to change the input type on your email input to email, and you will need to add the required attribute to every one you want to be required.
This way instead of using JavaScript you can just use standards-compliant HTML.
Then, since you can't send email directly from the browser, you need a third-party service to send the email, like for example Formspree. Alternatively you could write a server-side script for sending email, but it's much easier to just use a service.
Here is the final code:
<form action="https://formspree.io/your.email.here#example.com">
<fieldset class="form-group">
<label for="usr">Name*:</label>
<input type="text" class="form-control" id="usr" placeholder="Name" name="message" required="required">
</fieldset>
<fieldset class="form-group">
<label for="exampleInputEmail1">Email Address*:</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="email" required="required">
</fieldset>
<fieldset class="form-group">
<label for="message">Message*:</label>
<textarea class="form-control" rows="5" id="message" placeholder="Message" name="message" required="required"></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
If you want to use Formspree and also have your visitors enter their company name, you can hack it by giving the company name field a name of "subject", which Formspree will forward to your email alongside the rest of the fields.
You have a little mistake in your code,
parameter document.getElementById is element id :
change code :
var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
TO this :
var name = document.getElementById("usr").value;
var email = document.getElementById("exampleInputEmail1").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;

Categories