1

I have created a program to send email with attachment. First I create it without ajax. Then it worked properly. But when I used jquery ajax for it not work. When I click apply button nothing happen. My code is below.

<form action="sendemail.php" enctype="multipart/form-data" method="post">
                <h1 class="cta-title">Its a Call To Action</h1>
                <div class="cta-desc">
                    <input type="text" value='<?= $row['catogary'];?>' readonly style="width: 75%"><br><br>
                    <input type="text" value='<?= $row['company_name'];?>' readonly style="width:    75%"><br><br>
                    <input type="text" value='<?= $row['location'];?>' readonly style="width: 75%"><br><br>
                    <input type="text" value='<?= $row['qulification'];?>' readonly style="width: 75%"><br><br>
                    <input type="text" value='<?= $row['catogary'];?>' readonly style="width: 75%"><br><br>
                    <input type="text" value='<?= $row['indate'];?>' readonly style="width: 37.5%">&nbsp;
                    <input type="text" value='<?= $row['expdate'];?>' readonly style="width: 37.5%"><br>
                    <input type="text" id="email" name="email" value='<?= $row['email'];?>'><br>
                    <input type="file" name="uploaded_file" id="uploaded_file" class="text-center center-block well well-sm">
                    <input type="button" id="btn" name="btn" class="btn btn-primary" value="Apply">
                </div>
                    <script>
                        $('#btn').click(function () {
                            $.ajax({
                                method:"POST",
                                url:"sendemail.php",
                                data:{email:$('#email').val()},
                                success:function (data) {
                                    alert(data);
                                    return false;
                                }
                            });
                        });
                    </script>
                </form>

sendmail.php

    <?php
    $email2=$_POST['email'];
    require_once('PHPMailer/PHPMailerAutoload.php');
    $mail = new PHPMailer;
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "getinternshipuwu@gmail.com";
$mail->Password = "uwucst14xxxx";
$mail->SetFrom("getinternshipuwu@gmail.com");
$mail->FromName = "Internship Management";

$mail->addAddress($email2);
/
$mail->addReplyTo("getinternshipuwu@gmail.com", "Reply");

$mail->isHTML(true);

$mail->Subject = 'CV for internship Vacancy';
$mail->Body =  "Attached";
if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {

    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],$_FILES['uploaded_file']['name']);
}

if(!$mail->send())
{
    echo "Mailer Error: " . $mail->ErrorInfo;

}
else
{
    echo 'Successfully Applied for vacancy';
}
?>
Mahendra Gunawardena
  • 1,956
  • 5
  • 26
  • 45
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Apr 25 '17 at 20:35
  • yes i was running this.nothing happen.but before using ajax this was run well.yes.jquery library was used and no error report. – Danith Kumarasinghe Apr 25 '17 at 20:36
  • Change Apply button type to submit – Rotimi Apr 25 '17 at 20:40
  • You should use `FormData` object to upload files via ajax. Currently `$_FILES['uploaded_file']` is empty. Check: http://stackoverflow.com/a/21045034/4471134 – Alexey Chuhrov Apr 25 '17 at 21:18

2 Answers2

0

Here is my implementation. I change some attributes. But note the important that i change for my purposes the ssl to tls and to 587.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

</head>

<body>


    <form onsubmit="return submitForm();" enctype="multipart/form-data" method="post" name="fileinfo"  id="fileinfo" >
                <h1 class="cta-title">Its a Call To Action</h1>
                <div class="cta-desc">
                    <input type="text" value='a' readonly style="width: 75%"><br><br>
                    <input type="text" value='b' readonly style="width:    75%"><br><br>
                    <input type="text" value='c' readonly style="width: 75%"><br><br>
                    <input type="text" value='d' readonly style="width: 75%"><br><br>
                    <input type="text" value='e' readonly style="width: 75%"><br><br>
                    <input type="text" value='f' readonly style="width: 37.5%">&nbsp;
                    <input type="text" value='g' readonly style="width: 37.5%"><br>
                    <input type="text" id="email" name="email" value='iordanhs92@hotmail.com'><br>
                    <input type="file" name="files" id="files" class="text-center center-block well well-sm">
                    <input type="submit" id="btn" name="btn" class="btn btn-primary" value="Apply">
                </div>
                    <script>
                       function submitForm() {

                        console.log("submit event");

                        var fd = new FormData(document.getElementById("fileinfo"));
                        fd.append("label", "WEBUPLOAD");

                        $.ajax({
                          url: "mailattach.php",
                          type: "POST",
                          data: fd,
                          processData: false,  // tell jQuery not to process the data
                          contentType: false   // tell jQuery not to set contentType
                        }).done(function( data ) {
                                console.log("PHP Output:");
                                console.log( data );
                            });
                            return false;
                        }
                    </script>
                </form>


</body>
</html>

So,in php too,i changed the upload_file to files. The php code in mailattach is the same as that you provided

  • provide error messages. Also if you are running under non-https connections. change ssl to tls and the port to 587 . Test it with gmail , but you must logged in the gmail account and change the permission for sending emails under "unsecured" connection – Jordan Georgiadis Apr 26 '17 at 14:35
0

source : https://www.thenerdyblog.com/simple-ajax-form-email-attachment-using-php/

<?php

$email = $_POST['email_address'];
        
    //Recepient Email Address
    $to_email       = $email;

    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        $output = json_encode(array( //create JSON data
            'type'=>'error',
            'text' => 'Sorry Request must be Ajax POST'
        ));
        die($output); //exit script outputting json data
    }

    //Sanitize input data using PHP filter_var().
    $first_name      = filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
    $email_address   = filter_var($_POST["email_address"], FILTER_SANITIZE_EMAIL);
    $subject         = "Your Email Subject Goes Here...";
   
     
    //Textbox Validation 
    if(strlen($first_name)<4){ // If length is less than 4 it will output JSON error.
        $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
        die($output);
    }
    
 

    $message = '<html><body>';
    $message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
    $message .= "<tr style='background: #eee;'><td><strong>First Name:</strong> </td><td>" . strip_tags($_POST['first_name']) . "</td></tr>";
    $message .= "<tr><td><strong>Email Address :</strong> </td><td>" . strip_tags($_POST['email_address']) . "</td></tr>";
    $message .= "</table>";
    $message .= "</body></html>";


    $file_attached = false;
    if(isset($_FILES['file_attach'])) //check uploaded file
    {
        //get file details we need
        $file_tmp_name    = $_FILES['file_attach']['tmp_name'];
        $file_name        = $_FILES['file_attach']['name'];
        $file_size        = $_FILES['file_attach']['size'];
        $file_type        = $_FILES['file_attach']['type'];
        $file_error       = $_FILES['file_attach']['error'];


 
        //exit script and output error if we encounter any
        if($file_error>0)
        {
            $mymsg = array(
            1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
            2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
            3=>"The uploaded file was only partially uploaded",
            4=>"No file was uploaded",
            6=>"Missing a temporary folder" );
             
            $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
            die($output);
        }
         
        //read from the uploaded file & base64_encode content for the mail
        $handle = fopen($file_tmp_name, "r");
        $content = fread($handle, $file_size);
        fclose($handle);
        $encoded_content = chunk_split(base64_encode($content));
        //now we know we have the file for attachment, set $file_attached to true
        $file_attached = true;



        
    }


     
    if($file_attached) //continue if we have the file
    {
       
    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (RFC)
    $eol = "\r\n";

    // main header (multipart mandatory)
    $headers = "From:Fromname <info@fromemail.com>" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;

    // message
    $body .= "--" . $separator . $eol;
    $body .= "Content-type:text/html; charset=utf-8\n";
    $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $body .= $message . $eol;

    // attachment
    $body .= "--" . $separator . $eol;
    $body  .= "Content-Type:".$file_type." ";
    $body .= "Content-Type: application/octet-stream; name=\"" . $file_name . "\"" . $eol;
    $body .= "Content-Transfer-Encoding: base64" . $eol;
    $body .= "Content-Disposition: attachment; filename=\"".$file_name."\"". $eol;
    $body .= $encoded_content . $eol;
    $body .= "--" . $separator . "--";
        
    }
    else
    {
        
        $eol = "\r\n";
        
        $headers = "From: Fromname <info@fromemail.com>" . $eol;
        $headers .= "Reply-To: ". strip_tags($email_address) . "\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        $body .= $message . $eol;

    }


    $send_mail = mail($to_email, $subject, $body, $headers);
 
    if(!$send_mail)
    {
        //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
        $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$first_name .' Thank you for your order, will get back to you shortly'));
        die($output);
    }

?>
<!DOCTYPE html>
<html lang="en">

<body>
  <form id="contact-form" method="post" enctype="multipart/form-data">
    <div class="form-group">
      <label for="fname">First Name:</label>
      <input type="text" class="form-control" id="fname">
    </div>
    <div class="form-group">
      <label for="email">Email Address:</label>
      <input type="email" class="form-control" id="email_address">
    </div>
    <div class="form-group">
      <label for="attachment">File attachment:</label>
      <input type="file" name="file_attach" class="input-field" />
    </div>

    <button type="button" id="submit" class="btn btn-default btn-dark">Submit</button>
  </form>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {

      $("#submit").click(function(e) {

        var proceed = true;

        if (proceed) //everything looks good! proceed...
        {

          //data to be sent to server        
          var m_data = new FormData();
          m_data.append('first_name', $('#fname').val());
          m_data.append('email_address', $('#email_address').val());
          m_data.append('file_attach', $('input[name=file_attach]')[0].files[0]);

          //instead of $.post() we are using $.ajax()
          //that's because $.ajax() has more options and flexibly.

          $.ajax({
            url: 'process.php',
            data: m_data,
            processData: false,
            contentType: false,
            type: 'POST',
            dataType: 'json',
            success: function(response) {
              //load json data from server and output message    
              if (response.type == 'error') { //load json data from server and output message    
                output = '<div class="error">' + response.text + '</div>';
              } else {
                output = '<div class="success">' + response.text + '</div>';
              }
              $("#response").hide().html(output).slideDown();
            }
          });


        }

      });
    });
  </script>

</body>

</html>
Nitsh
  • 79
  • 3