I have never coded using PHP before so I have no idea if my code is correct. I am trying to run my PHP file from my JavaScript/jQuery code using ajax. I don’t seem to understand what is wrong. No emails are being sent but I’m not being given any errors either. Please help! Also, the email being used in the PHP code is my actual email just didn’t want it in the question so I changed to example. Everything is pulling from an HTML form also. I gave each input the name according to what info it collects.
JavaScript
$.ajax({
type: "CONNECT",
url: "mail.php"
}).done(function(data){
alert("Message is sent");
});
PHP
<?php
$email = $_GET['email'];
$company_name = $_GET['companyname'];
$sender_name = $_GET['customername'];
$telephone_num = $_GET['telephonenum'];
$message = $_GET['message'];
$to = "[email protected]";
$subject = $company_name . " " . $sender_name;
$finished_message = "Name: " . $sender_name . "n
Company: " . $company_name . "n
Telephone Number: " . $telephone_num . "n
Email: " . $email . "n
Message:n" . $message . "";
$finished_message = wordwrap($finished_message,70);
$headers = "MIME-Version: 1.0" . "rn";
$headers .= "Content-type:text/html;charset=UTF-8" . "rn";
$headers .= "From: ". $sender_name . " <" . $email . ">";
mail($to,$subject,$finished_message,$headers);
?>
I’ve tried changing the type in the js file but then I throw errors.
2
Answers
You seem to be using ajax wrong. You don’t send the body with your request. I would suggest something like this:
Or using FormData:
And PHP part: you are getting your values from GET object. However, you schould send your email-forms using POST method. In ajax I already wrote
method: 'post'
. Change$_GET
to$_POST
and everything should work fine.And I strongly recommend validating your incoming data, at least if it exists or not.
Here is the solution of your problem of calling a file through ajax
Hope helpful for you!