-3

In my PHP code I have the following and these variables grab the data from a html form.

$name = @trim(stripslashes($_POST['name'])); 
$clientemail = @trim(stripslashes($_POST['email'])); 
$subject = @trim(stripslashes($_POST['subject'])); 
$message = @trim(stripslashes($_POST['message']));

however, if I remove the @ then all I see instead of a success message is "undefined" but if I keep the @ then I do get an email but it is a blank email....

Full Code:

<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL);
   header('Content-type: application/json');

        // WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
        // WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:  
        $status = array(
                        'type'          =>'Error',
                        'message'       =>'Couldn\'t send the Email at this Time. Something went wrong',
                        'attachement'   =>'Couldn\'t attach the uploaded File to the Email.'
        );

//Added to deal with Files
require_once('/PHPMailer/class.phpmailer.php');\

    //      require_once('/PHPMailer/class.smtp.php');
    //Get the uploaded file information
    $name_of_uploaded_file =
        basename($_FILES['uploaded_file']['name']);

    //get the file extension of the file
    $type_of_uploaded_file =
        substr($name_of_uploaded_file,
        strrpos($name_of_uploaded_file, '.') + 1);

    $size_of_uploaded_file =
        $_FILES["uploaded_file"]["size"]/1024;//size in KBs

    //Settings
    $max_allowed_file_size = 10240; // size in KB
    $allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png");

    //Validations
    if($size_of_uploaded_file > $max_allowed_file_size )
    {
      $errors .= "\n Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
    }

    //------ Validate the file extension -----
    $allowed_ext = false;
    for($i=0; $i<sizeof($allowed_extensions); $i++)
    {
      if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
      {
        $allowed_ext = true;
      }
    }

    if(!$allowed_ext)
    {
      $errors .= "\n The uploaded file is not supported file type. ".
      " Only the following file types are supported: ".implode(',',$allowed_extensions);
    }

    //copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
    $upload_folder = "/temp/";
    $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
    $tmp_path = $_FILES["uploaded_file"]["tmp_name"];

    if(is_uploaded_file($tmp_path))
    {
      if(!copy($tmp_path,$path_of_uploaded_file))
      {
        $errors .= '\n error while copying the uploaded file';
      }
    }
//--end

$name = @trim(stripslashes($_POST['name'])); 
$clientemail = @trim(stripslashes($_POST['email'])); 
$subject = @trim(stripslashes($_POST['subject'])); 
$message = @trim(stripslashes($_POST['message']));

$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" .   'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$email = new PHPMailer();   
$email->From      = $clientemail;
$email->FromName  = $name;
$email->Subject   = $subject;
$email->Body      = $body;  
$email->AddAddress( 'root@localhost.com' ); //Send to this email

// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP   BUILT IT MAIL FUNCTION    
$email->isMail();

// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT 
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...   
if($email->AddAttachment( $path_of_uploaded_file , $name_of_uploaded_file )){
        $status['attachment']   = 'Uploaded File was successfully attached to the Email.';  
    }

// NOW, TRY TO SEND THE EMAIL ANYWAY:
    try{
        $success    = $email->send();
        $status['type']     = 'success';
        $status['message']  = 'Thank you for contact us. As early as possible  we will contact you.';   
    }catch(Exception $e){
        $status['type']     ='Error';
        $status['message']  ='Couldn\'t send the Email at this Time. Something went wrong';     
    }   

    // SIMPLY, RETURN THE JSON DATA...
die (json_encode($status));

HTML:

            <form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
                <div class="col-sm-5 col-sm-offset-1">
                    <div class="form-group">
                        <label>Name *</label>
                        <input type="text" name="name" class="form-control" required="required">
                    </div>
                    <div class="form-group">
                        <label>Email *</label>
                        <input type="email" name="email" class="form-control" required="required">
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="number" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Company Name</label>
                        <input type="text" class="form-control">
                    </div>                        
                </div>
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>Subject *</label>
                        <input type="text" name="subject" class="form-control" required="required">
                    </div>
                    <div class="form-group">
                        <label>Message *</label>
                        <textarea name="message" id="message" required="required" class="form-control" rows="8" style="height:125px"></textarea>
                        <label for='uploaded_file' style="margin-top:10px">Select A Photo To Upload:</label>
                        <input type="file" name="uploaded_file">
                    </div>                        
                    <div class="form-group">
                        <button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
                    </div>
                </div>
            </form> 

Here is the AJAX that displays a message to the user when they click submit:

// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: $(this).attr('action'),

        beforeSend: function(){
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
        }
    }).done(function(data){
        form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
    });
});
Badrush
  • 1,247
  • 1
  • 17
  • 35
  • 3
    you posted this already http://stackoverflow.com/questions/37445450/php-email-is-sent-without-form-data – Funk Forty Niner May 26 '16 at 00:35
  • 2
    the `@` suppresses errors. – Pedro Lobito May 26 '16 at 00:36
  • @PedroLobito I understand that...but that just leads to an empty email... so I should address the errors causing it but I can't figure out what is causing it. – Badrush May 26 '16 at 00:38
  • 1
    You're doing `$email = new PHPMailer();` twice.... – Darren May 26 '16 at 00:41
  • Take a look at the error_log, it will point you on right direction to fix the problem. – Pedro Lobito May 26 '16 at 00:56
  • 1
    Are you using AJAX to call the `sendemail.php` script? It's unusual to return JSON with normal form submission, it should return HTML. – Barmar May 26 '16 at 01:08
  • @barmar here is the JS/AJAX code that displays a message to the user when they click submit... see my edit – Badrush May 26 '16 at 01:17
  • @PedroLobito that was a mistake I made editing the code, thanks I fixed that part. – Badrush May 26 '16 at 01:19
  • 1
    You're not sending any of the form fields in your AJAX call. Add `data: $(this).serialize()` – Barmar May 26 '16 at 01:20
  • @barmar To what part of the JS? – Badrush May 26 '16 at 01:21
  • 1
    To the `$.ajax` options, of course. Don't you know how to use the function you're calling? – Barmar May 26 '16 at 01:22
  • I didn't write that JS function. I looked up what serialize does but it is over my head. https://api.jquery.com/serialize/ – Badrush May 26 '16 at 01:23
  • @Barmar I added `$(this).serialize()` to the ajax options and I got this error upon submitting. ... `Parse error: syntax error, unexpected '$name_of_uploaded_file' (T_VARIABLE), expecting identifier (T_STRING) in F:\CL2\sendemail.php on line 19` – Badrush May 26 '16 at 01:26
  • 1
    That has nothing to do with the AJAX call, it means you have a syntax error in your PHP script. Maybe because of the backslash at the end of the `require_once` line before the `$name_of_uploaded_file` assignment? – Barmar May 26 '16 at 01:34
  • @Barmar Now it sends the email but I get a bunch of errors related to the file attachment even though no file was chosen. `Notice: Undefined index: uploaded_file in F:\CL2\sendemail.php on line 20 Notice: Undefined index: uploaded_file in F:\CL2\sendemail.php on line 28 Notice: Undefined variable: errors in F:\CL2\sendemail.php on line 53 Notice: Undefined index: uploaded_file in F:\CL2\sendemail.php on line 59 {"type":"success","message":"Thank you for contact us. As early as possible we will contact you.","attachement":"Couldn't attach the uploaded File to the Email."}` – Badrush May 26 '16 at 01:54
  • @Barmar if you post your answer I will mark it as the solution. My previous comment was solved with a simple if statement to make sure there are files attached. Now I just have to figure out why my files aren't being attached when I choose to use an attachment. – Badrush May 26 '16 at 03:18
  • This one shouldn't have been asked in the first place. The other one should have been edited. But I guess it's too late for that now. – Cerbrus May 27 '16 at 09:49

1 Answers1

1

You need to put the form data in the AJAX request.

$.ajax({
    url: $(this).attr('action'),
    data: $(this).serialize(),
    beforeSend: function(){
        form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
    }
})

However, serialize() doesn't work with type="file" inputs. That's why you get an Undefined Index for $_FILES['uploaded_file']. You need to use FormData:

$.ajax({
    url: $(this).attr('action'),
    data: new FormData(this),
    processData: false,
    contentType: false,
    beforeSend: function(){
        form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
    }
})

You also have a syntax error on this line:

require_once('/PHPMailer/class.phpmailer.php');\

Get rid of the slash at the end.

See PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" for information about all those warnings you're getting.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • So the `serialize(),` line allows the form to work but causes and error in the Jquery file which breaks the JS code. However if I use `serialize();` the JS is good but the PHP breaks and gives `undefined` output – Badrush May 27 '16 at 21:19
  • What about if you use `FormData`? – Barmar May 27 '16 at 21:20
  • Could it have something to do with this in the
    `enctype="multipart/form-data"` ??
    – Badrush May 27 '16 at 21:23
  • ohh you probably meant `data: new FormData(this),` yes I did try that as well and the same issue. I get an `undefined` message, I believe when it tries to run `beforeSend: function(){ form.prepend( form_status.html('

    Email is sending...

    ').fadeIn() ); }`
    – Badrush May 27 '16 at 21:31
  • I don't think the `beforeSend` should have any effect on that, but what happens if you remove that? – Barmar May 27 '16 at 21:35
  • No error but I receive an email without the form data – Badrush May 27 '16 at 21:36
  • What does it show in the Network tab as the request data for the AJAX call? – Barmar May 27 '16 at 21:39
  • So if I use your solution posted above. I get a blank email. In chrome the network tab just shows the `sendemail.php?[object%20FormData]` pop up and in preview it says `["Thank you for contacting us. We will reply as soon as possible."]` which is my success message in the PHP code but like I said, the email doesn't have the form data. (I am using the `beforeSend`) still. – Badrush May 27 '16 at 21:45
  • When you look in the Request Headers, does it show the form data being sent? – Barmar May 27 '16 at 21:46
  • Is it this? `Request URL:http://localhost:82/contact-us.html Request Method:GET Status Code:304 Not Modified Remote Address:[::1]:82` – Badrush May 27 '16 at 21:51
  • I think it's time you read a tutorial on using the Chrome debugger. I can't walk you through this whole process. – Barmar May 27 '16 at 21:54
  • `Accept:*/* Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8 Connection:keep-alive DNT:1 Host:localhost:82 Referer:http://localhost:82/contact-us.html User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36 X-Requested-With:XMLHttpRequest` – Badrush May 27 '16 at 21:57
  • I'm asking about the post data, not the headers. Is it posting the data from the form? – Barmar May 27 '16 at 22:00
  • When I click to submit the form this is everything that appears once I click. http://imgur.com/oWrVf7T – Badrush May 27 '16 at 22:04
  • I think you left out the `processData: false` option to `$.ajax`. – Barmar May 27 '16 at 22:06
  • It was included... `$.ajax({ url: $(this).attr('action'), data: new FormData(this), processData: false, contentType: false, beforeSend: function(){ form.prepend( form_status.html('

    Email is sending...

    ').fadeIn() ); } }).done(function(data){ form_status.html('

    ' + data.message + '

    ').delay(3000).fadeOut(); });`
    – Badrush May 27 '16 at 22:07
  • Sorry, I'm not sure why it's not working. I just copied this solution from other questions, they say it should work. – Barmar May 27 '16 at 22:09
  • Thanks for spending time helping me. – Badrush May 27 '16 at 22:13