1

I have following form processing php script.

<?php
$G['hotel_email']="[email protected]";
$G['hotel_name']="xxx xxx";
$G['language']="en";
$T['lbl_form_sent_successfully']="H";


# Recipients: comma separated
$G['form_contact_mail_recipients'] = $G['hotel_email'];
$G['form_contact_mail_subject'] = $G['hotel_name'] . ' - Contact Weddings [' . $G['language'] . ']';


# CHECK IF FORM SENT. AJAX. RESPONSE IN JAVASCRIPT TO INTERACT IN THE FORM.
if (!empty($_POST)) {
    $js = '';

     # ALTERNATIVE CAPTCHA, IT MUST NOT BE FILLED
     if (!empty($_POST['title'])) { exit; }


     # FORM MAIL TO SENT
     unset($_POST['title']);
     unset($_POST['submit']);
     $message = date("l, F j, Y, g:i a")." [GMT] \n\nFORM DETAILS\n\n\n";
     foreach ($_POST as $field => $value) { 
        $message .= ucfirst(str_replace('_',' ',$field)).': '.$value."\n\n";
     }
     $message .= "\n\n\n";
     mail($G['form_contact_mail_recipients'], $G['form_contact_mail_subject'], $message, "From: ".$_POST['email']."\r\n");
     echo "success";
}
?>

The form is being submitted using following JavaScript

    $(function() {
      // Initialize form validation on the registration form.
      // It has the name attribute "registration"
      $("#ba-form-contact form").validate({
        // Specify validation rules
        rules: {
          // The key name on the left side is the name attribute
          // of an input field. Validation rules are defined
          // on the right side
          First_Name: "required",
          Surname: "required",
          email: {
            required: true,
            // Specify that email should be validated
            // by the built-in "email" rule
            email: true
          }
        },
        submitHandler: function() {
     jQuery.ajax({
     type: 'POST',
     url: '<?=$_SERVER['REQUEST_URI']?>',
     data: jQuery("#ba-form-contact form").serialize(),
     dataType: 'html'
     });
     return false;
     }
      });
    });
     </script>

The last echo statement does't work and I don't get any error msg.I do get email with all the info alright.I think nothing work after the mail function, I tried like var_dump, but nothing. What could be the error here?

16
  • $_POST is empty so its not going in if (!empty($_POST)) { condition Commented Oct 28, 2016 at 10:56
  • Also your code is vulnerable to header injection. Commented Oct 28, 2016 at 10:57
  • After mail write die; and check what's happening? And, if not printing success, then where it's going. Is it redirecting to other page? Find out, you yourself can do debugging. Commented Oct 28, 2016 at 10:59
  • @Ruchish then how come I am getting emails? the line before the echo sends the email Commented Oct 28, 2016 at 11:00
  • @ Nana Partykar I did debug and did a lot of research myself, tried var_dump, die() but nothing happens, I just get emails. The form is submitting to same page. the above code is followed by html form. Commented Oct 28, 2016 at 11:04

2 Answers 2

1

As per your ajax request, you are not using success method here in ajax request, you need to add success method as:

jQuery.ajax({
url: YourURL,
type: "POST",
data: jQuery("#ba-form-contact form").serialize(),
dataType: "html",  
success: function(response) {
    alert(response); //this will return the response
},
beforeSend: function()
{
    // loading if you need before ajax success
}
});  
return false;

Here success: function(response) { will return the success message.

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

5 Comments

Thanks, I am aware of this method to output success message. My question is why, in the php code mail function is working but echo statement is not?
note that, your echo success is also working its not showing because you are using ajax, for more detail, open your browser console you will get the idea or open your ajax request in a new tab , will help u @manu
the console show this "POST localhost:8888/site/test-form.php 200 OK 39ms" When I expand this and under the response tab I can see the whole body of the page with success message echoed! I don't know what is the eplanantion for this.
thanks, devpro, as you have pointed PHP echo is indeed working just I need to updated the DMO with ajax response using a script. I will accept your comment as the answer.
@manu what I am saying its working Php execute completely but when u need response in ajax than u must need to use success function
1

You do not know that it is the echo that does not work.

What you do know is that the script executes, and the jQuery function does not issue output. And that's where half the problem is.

jQuery.ajax({
    type: 'POST',
    url: '<?=$_SERVER['REQUEST_URI']?>',
    data: jQuery("#ba-form-contact form").serialize(),
    dataType: 'html'
 });

The above does not do anything with the output, so logically nothing happens.

Try this:

jQuery.post({
    '<?=$_SERVER['REQUEST_URI']?>',
    jQuery("#ba-form-contact form").serialize()
 }).done(function(retval) {
     // Debug (better use console.log actually)
     alert(JSON.stringify(retval));
     // Do what you want with retval.message (check retval.status also)
     alert(retval.message);
 });

and in the PHP, which must output nothing else, end with:

 header('Content-Type: application/json');
 die(json_encode(array(
     'status' => 'success',
     'message' => 'The mail was sent',
 )));

(I have changed from HTML to JSON output since this allows to send more structured data, with negligible additional complexity).

4 Comments

but i think, just using the success function in ajax will work here.. because datatype is html.. m i right??
Yes, you are. Yours solution allows the minimum possible change in the code (I'm upvoting it for that, too). Yet it is my experience that it's better to have the fewest possible output formats from a service, and it's advisable to have a slightly more flexible output format to avoid abusing the returned HTML. For example I've seen the output HTML parsed to access information fields, i.e. $(retval).find('#field1').text(). I am well aware that I'm going against YAGNI here, but I'm balancing it against the danger of creeping featurism :-).
but to be honest, i always use json for ajax, u are also right with another solution.. u also deserve for appreciation.
yes, I am aware of many ways to output success message upon form submission.But my question is only related to PHP code.

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.