Home > Back-end >  How to call a php file using ajax and is my php code correct?
How to call a php file using ajax and is my php code correct?

Time:01-24

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" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
$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.

CodePudding user response:

Here is the solution of your problem of calling a file through ajax

$.ajax({
        type: 'POST',
        url: '/mail.php',
        data: {
            // Parameters with values
        }
        
        success: function (res) {
            alert("Message is sent");
        },
        error: function (error) {
            alert("Message not sent" error);
        }
    });

Hope helpful for you!

CodePudding user response:

You seem to be using ajax wrong. You don't send the body with your request. I would suggest something like this:

$.ajax({
  method: "POST",
  url: "mail.php",
  data: {} // your form data
})
.done(function(msg) {
  alert("Data sent!");
});

Or using FormData:

$.ajax({
  method: "POST",
  url: "mail.php",
  data: new FormData() // your form data
})
.done(function(msg) {
  alert("Data sent!");
});

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.

  • Related