1

I'm calling this script using Ajax. The 'write to database' part of the script runs fine, but for some reason the send_receipt() function does not run when the script is run.

The send e-mail function needs to be enclosed within a custom function because the script will ultimately send two e-mails - one receipt to the customer and one notification to the company. So all of the mail() variables and data will be repeated, but with different target e-mail addresses, with both functions to be called when the script is run.

Any help much appreciated.

Thanks!

Ajax:

    $.ajax({
        type: "POST",
        url: "selfnormal.php",
        data: "fname="+ fname +"& lname="+ lname +"& worktel="+ worktel +"& privtel="+ privtel +"& mobtel="+ mobtel +"& email="+ email +"& workaddress="+ workaddress +"& homeaddress="+ homeaddress +"& level="+ level +"& size="+ size +"& deliv="+ deliv +"& venue="+ venue +"& ioshdate="+ ioshdate +"& isdiscount="+ isdiscount +"& elcas="+ elcas +"& funding="+ funding +"& paytype="+ paytype +"& selfinvoicead="+ selfinvoicead +"& companyname="+ companyname +"& companyaddress="+ companyaddress +"& PO="+ PO +"& tcs="+ tcs +"& finalprice="+ finalprice +"& finalvat="+ finalvat +"& finalfee="+ finalfee +"& finaltotal="+ finaltotal +"& finalmonthly="+ finalmonthly +"& finaladmin="+ finaladmin,
        success: function(){
        alert ("success");
        }

PHP:

<?php
$firstname = htmlspecialchars(trim($_POST['fname']));
$lastname = htmlspecialchars(trim($_POST['lname']));
$worktel = htmlspecialchars(trim($_POST['worktel']));
$privtel = htmlspecialchars(trim($_POST['privtel']));
$mobtel = htmlspecialchars(trim($_POST['mobtel']));
$email = htmlspecialchars(trim($_POST['email']));
$workaddress = htmlspecialchars(trim($_POST['workaddress']));
$homeaddress = htmlspecialchars(trim($_POST['homeaddress']));
$level = htmlspecialchars(trim($_POST['level']));
$size = htmlspecialchars(trim($_POST['size']));
$deliv = htmlspecialchars(trim($_POST['deliv']));
$venue = htmlspecialchars(trim($_POST['venue']));
$ioshdate = htmlspecialchars(trim($_POST['ioshdate']));
$isdiscount = htmlspecialchars(trim($_POST['isdiscount']));
$elcas = htmlspecialchars(trim($_POST['elcas']));
$funding = htmlspecialchars(trim($_POST['funding']));
$paytype = htmlspecialchars(trim($_POST['paytype']));
$selfinvoicead = htmlspecialchars(trim($_POST['selfinvoicead']));
$companyname = htmlspecialchars(trim($_POST['companyname']));
$companyaddress = htmlspecialchars(trim($_POST['companyaddress']));
$po = htmlspecialchars(trim($_POST['PO']));
$tcs = htmlspecialchars(trim($_POST['tcs']));
$courseprice = htmlspecialchars(trim($_POST['finalprice']));
$vat = htmlspecialchars(trim($_POST['finalvat']));
$fee = htmlspecialchars(trim($_POST['finalfee']));
$admin = htmlspecialchars(trim($_POST['finaladmin']));
$total = htmlspecialchars(trim($_POST['finaltotal']));
$monthly = htmlspecialchars(trim($_POST['finalmonthly']));

$dbc = mysqli_connect('xxxx', 'xxxx', 'xxxx', 'xxxx')
or die ('Could not connect to MySQL server.');

$query = "INSERT INTO enrolments (fname, lname, worktel, privtel, mobtel, email, workaddress, homeaddress, level, size, deliv, venue, ioshdate, isdiscount, elcas, funding, paytype, selfinvoicead, companyname, companyaddress, po, tcs, price, VAT, BIFM_Fee, Total, Monthly, adminfee)" . 
"VALUES ('$firstname', '$lastname', '$worktel', '$privtel', '$mobtel', '$email', '$workaddress', '$homeaddress', '$level', '$size','$deliv','$venue', '$ioshdate','$isdiscount','$elcas', '$funding', '$paytype','$selfinvoicead','$companyname','$companyaddress','$po','$tcs', '$courseprice', '$vat', '$fee', '$total', '$monthly', '$admin')";

$result = mysqli_query($dbc, $query)
or die ('error querying database');
mysqli_close($dbc);

function send_receipt() {
$to = $email;
$subject = $firstname . ', thank you for enrolling on the ' . $level . ' ' . $size . ' (' . $deliv . ')';
$msg = "Hi $firstname," . PHP_EOL . 
    PHP_EOL .
    "Thanks for enrolling with us. Please find a summary of your enrolment below. We'll be in touch shortly to arrange payment, after which we will send you joining instructions and course details." . PHP_EOL .
    PHP_EOL . 
    "Please be aware that in accordance with UK Legislation, you are legally entitled to a 7 day 'cooling off' period during which you may cancel your course at no cost. After this period, you will be liable for full payment as detailed below." . PHP_EOL . 
    PHP_EOL . 
    "Level: $level" . PHP_EOL .
    "Scale: $size" . PHP_EOL .
    "Delivery Method: $deliv" . PHP_EOL .
    "Payment Method: $paytype" . PHP_EOL .
    "Course Price: £$courseprice" . PHP_EOL .
    "VAT: £$vat" . PHP_EOL .
    "ILM/BIFM fee: £$fee" . PHP_EOL .
    "Total: £$total" . PHP_EOL .
    PHP_EOL . 
    "We look forward to welcoming you onto the course in the near future." . PHP_EOL .
    PHP_EOL .
    "Kind regards" . PHP_EOL .
    PHP_EOL .
    "The Xenon Group staff";

    mail ($to, $subject, $msg, 'From: Xenon Group Enrolments');
}

send_receipt();
4
  • What are you getting in AJAX response ? Commented Oct 18, 2012 at 8:00
  • why not just bcc the company? Commented Oct 18, 2012 at 8:02
  • Ajax response is reading 'success' which I presume is for the writing to database part of the script. Commented Oct 18, 2012 at 8:06
  • 1
    I can't bcc the company as they will receive a different e-mail, with more information. Commented Oct 18, 2012 at 8:07

2 Answers 2

1

For a start in your PHP you are relying on vars outside of the function scope. This is not the way PHP works. If you wish to access a variable outside of the function you have to use global $var; to pull the variable into the function's scope... If you do not do this, the variables would be all undefined and so your mail() function wont know where to send what it is sending because $email will be empty.

function send_receipt(){

  global $email, $firstname, $lastname; /* and so on... */

}

However, It would be far better to tailor your function so that you are sending the arguments you want to use into it - this makes it more reusable:

function send_receipt( $email, $firstname, $lastname ){

  /* and so on ... */

}

Or even more portable (because you can send in flexible data):

function send_receipt( $email_to, $user_data ){

  /// place any default values here - just in case a value is missed
  $user_data += array(
    'firstname' => '',
    'lastname' => '',
  );

  /// create a shortcut to the data
  $ud = $user_data;

  $msg  = "Hi {$ud[firstname]}," . PHP_EOL .
          "Thanks for enrolling with us....";

  /* and so on ... */

}

Secondly, to avoid URL encoding problems it would be best to formulate your jQuery ajax call like so:

$.ajax({
    type: "POST",
    url: "selfnormal.php",
    data: {
      "fname": fname,
      "lname": lname,
      "worktel": worktel,
      /* and so on */
    },
    success: function(){
     alert ("success");
    }
 });

This is because jQuery will handle URL encoding the values correctly for you, rather than what you were doing before... which had no encoding and would break the second your data contained illegal URL characters.

In response to Chris' comment :)

The above wont change the way your PHP script recieves the data, it will just protect it whilst it is in transit through to your sever - and so that your PHP script can interpret the information correctly once it starts parsing it. If you don't URL encode for example the following would break your previous URL.

var firstname = 'Pebbl & Pebbl';
var lastname = 'Pebbl';
var url = 'firstname=' + firstname + '&lastname=' + lastname;

Using the above URL your PHP script would most likely receive:

echo $_POST['firstname'];

/// would output 'Pebbl ' rather than the correct 'Pebbl & Pebbl'

With regard to how you receive data on your PHP side the following would probably make it easier - although what you are doing is fine, it just isn't using the power of server side scripting ;)

/// define array of 'allowed param names' and 'var names to use in your script'
$allowed_fields = array(
  'fname' => 'firstname',
  'lname' => 'lastname',
  'email' => 'email',
  /* and so on ...*/
);

/// step each of the allowed fields
foreach( $allowed_fields as $field_name => $script_name ){

  /// check the post array to see if we have a value for that param name
  if ( !empty($_POST[$field_name]) ) {
    /// if we do, process by removing whitespace
    $value = trim( $_POST[$field_name] );
    /// and converting html to safe characters
    $value = htmlspecialchars( $value );
  }
  else {
    /// if no value default to empty
    $value = '';
  }

  /// use a variable variable to set the variable defined by $script_name 
  /// to $value i.e. if $script_name == 'email', then this would be the 
  /// same as writing $email = $value;
  $$script_name = $value;

}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks pebbl - haven't applied all of this yet so don't know if it fixes the problem, but regarding the Ajax URL query, by doing it in this format do I still use the 'htmlspecialchars(trim($_POST['fname']))' code to call the data into my PHP script or do I need something different?
OK, so I went with the second option and included all of the variables as arguments to the function and also changed the Ajax as recommended, but the problem is still the same - write to database works, but no e-mail. Any ideas?
@Chris where are you testing this? on your local server (localhost) or somewhere else?
what happens if you wrap your mail command with the following - echo "(mail( ... );)"; basically keep your mail command but force PHP to echo out what you are sending to it instead? If you can confirm that this command is being executed, and it is receiving all the variables you expect... then i would guess it's a mail configuration problem with which ever server you are using.
@ianace - this is on my local server. I know it is able to send e-mails, because if you take the mail command outside of the custom function, it works. Problem is I need to send two e-mails, so need each of them to sit within a function
|
0

Try modify your ajax to show error message response:

$.ajax({
    type: "POST",
    url: "selfnormal.php",
    data: "fname="+ fname +"& lname="+ lname +"& worktel="+ worktel +"& privtel="+ privtel +"& mobtel="+ mobtel +"& email="+ email +"& workaddress="+ workaddress +"& homeaddress="+ homeaddress +"& level="+ level +"& size="+ size +"& deliv="+ deliv +"& venue="+ venue +"& ioshdate="+ ioshdate +"& isdiscount="+ isdiscount +"& elcas="+ elcas +"& funding="+ funding +"& paytype="+ paytype +"& selfinvoicead="+ selfinvoicead +"& companyname="+ companyname +"& companyaddress="+ companyaddress +"& PO="+ PO +"& tcs="+ tcs +"& finalprice="+ finalprice +"& finalvat="+ finalvat +"& finalfee="+ finalfee +"& finaltotal="+ finaltotal +"& finalmonthly="+ finalmonthly +"& finaladmin="+ finaladmin,
    success: function(){
        alert ("success");
    },
    error: function (xhr, status, thrownError) {
       alert(xhr.responseText);
       alert(thrownError);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.