Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    May 2009
    Posts
    164
    Thanks
    75
    Thanked 1 Time in 1 Post

    Issue submitting form more than once

    Hi guys, have a slight problem. When you submit my form, everything works and an email gets sent to my address. However, if you then try to submit it again after that, everything appears to work but no email is sent any other time. The only way to get it sending an email again is if I clear the cache.

    Form is pretty basic, removed some elements to shorten it

    Code:
                <form id="my-form">
                    <div id="my-company-div">
                        <input id="my-company" type="text" value="" maxlength="100" placeholder="Company" name="my-company" style="background-color: rgb(255, 255, 255);">
                    </div>
                    <div id="my-name-div">
                        <input id="my-name" type="text" value="" maxlength="100" placeholder="Name" name="my-name" style="background-color: rgb(255, 255, 255);">
                    </div>
                    <div id="title-bottom">
                        <p id="my_text_submit">Open Account</p>
                        <input class="my-btn" type="submit" value="Send" name="my-btn">
                    </div>
                </form>
    I have a submit handler attached to the form
    Code:
    $("#my-form").submit(my_submit);
    And this basically calls up the following
    Code:
        function my_submit(e){
            e.stopPropagation();
    
            var $btn = $("input[name='my-btn']");
            $btn.prop('disabled',true).val('Please Wait...');
            $('#my-success').html("<h4 id='my-success'></h4>");
            var fields = [
                "my-company", "my-name"];
    
            var formData = {};
            for (var i = 0; i < fields.length; ++i) {
                var $field = $("[name='" + fields[i] + "']");
                if (!Modernizr.input.placeholder && $field.val() == $field.attr("placeholder")) {
                    formData[fields[i]] = "";
                }
                else {
                    formData[fields[i]] = $field.val();
                }
            }
    
            var onSubmitSuccess = function(data){
                if(200 == data.code){
                    $.ajax({
                        url: "",
                        type: "post",
                        dataType: "html",
                        data: formData,
                        success: function (data) {
                            $('#my-success').html("<h4 id='my-success'>Form Submitted!</h4>");
                            $("#my-form")[0].reset();
                        }
                    });
                }
                else {
                    // clear all input background colours
                    $("input[type='text']").css("background-color","#ffffff");
    
                    // go through errors
                    for (var i = 0; i < data.fields.length; i++){
                        // make background red
                        var $field = $("[name='" + data.fields[i] + "']").css("background-color","#ff8080");
                        if (!Modernizr.input.placeholder && $field.val() == "") {
                            $field.val($field.attr("placeholder"));
                        }
                    }
                }
                $btn.prop('disabled',false).val('Send Request');
            }
            var onSubmitError = function(jxhr, status) {
                alert("An internal error occurred while processing your request. Please try again, or call use directly.\n\nWe apologize for any inconvenience.")
                $btn.prop('disabled',false).val('Send Request');
            }
            $.ajax({
                url: 'my-submit.php',
                type: "POST",
                dataType: "json",
                data: formData,
                success: onSubmitSuccess,
                error: onSubmitError
            });
    
            return false;
        }
    Finally the php file is pretty straight forward
    Code:
    <?php
        $requiredFields = array(
            "my-company", "my-name"
        );
    
        $missingFields = array();
        foreach ($requiredFields as $fieldName) {
            if (empty($_POST[$fieldName])) {
                $missingFields[] = $fieldName;
            }
        }
    
        $response = array();
        if (count($missingFields) == 0) {
            // Validate the input.
            $validationErrors = array();
    
            if (count($validationErrors) == 0) {
    
                $fields = array(
                    'date' => time(),
                    'ipaddress' => $_SERVER['REMOTE_ADDR'],
                    'source' => $_SERVER['HTTP_REFERER'],
                    'device' => $_SERVER['HTTP_USER_AGENT'],
                    'company' => $_POST["my-company"],
                    'name' => $_POST["my-name"],
                );
    
                $tpl_email = <<<TXT
    ===== My Account: =====\n
    Enqury made: {date}
    IP Address: {ipaddress}
    Source: {source}
    Device: {device}
    ===== Contact Details =====
    Company: {company}
    Customer Name: {name}
    ====================================
    TXT;
    
                $message = $tpl_email;
                foreach ($fields as $key => $value) {
                    $message = str_replace('{' . $key . '}', $value, $message);
                }
    
                $to      = 'me@my.co.uk';
                $subject = 'My Account';
                $headers = 'From: info@my.com' . "\r\n" .
                    'Reply-To: info@my.com' . "\r\n" .
                    'X-Mailer: PHP/' . phpversion();
    
                if (mail($to, $subject, $message, $headers)) {
    
                    $response["code"] = 200;
                }
                else {
                    $response["code"] = 500;
                }
            }
            else {
                $response["code"] = 400;
                $response["fields"] = $validationErrors;
            }
        }
        else {
            $response["code"] = 400;
            $response["fields"] = $missingFields;
        }
        echo(json_encode($response));
    So thats pretty much the code. My question is why the email only gets sent the first time, and not the second or third time?

    Any advice appreciated.

    Nick

  • #2
    Regular Coder hdewantara's Avatar
    Join Date
    Aug 2009
    Location
    Jakarta, Indonesia.
    Posts
    361
    Thanks
    9
    Thanked 53 Times in 52 Posts
    Hi Nick.
    If you're using Firefox, any messages from your console log?

    Also, does the following have some purpose?
    Code:
            var onSubmitSuccess = function(data){
                if(200 == data.code){
                    $.ajax({
                        url: "",
                        type: "post",
                        dataType: "html",
                        data: formData,
                        success: function (data) {
                            $('#my-success').html("<h4 id='my-success'>Form Submitted!</h4>");
                            $("#my-form")[0].reset();
                        }
                    });
                }
                else {...
    Your form has already run $.ajax(), but then it runs this $.ajax() inside onSubmitSuccess() to nowhere? and why twice?

    Hendra

  • Users who have thanked hdewantara for this post:

    nick2price (07-05-2014)

  • #3
    Regular Coder
    Join Date
    May 2009
    Posts
    164
    Thanks
    75
    Thanked 1 Time in 1 Post
    Hi, no error in the console, infact it returns 200 each time as it should do. The reason I have two $.ajax() is actually because I am following a design I made before, but the one I made before actually went to another html page on success while this one doesnt. The way it works is that the first ajax passes the form data to my php file. This PHP file does some validation and then sends an email, and returns a code back to the ajax. This code is then used to determine the outcome. You are right though, in this situation because I dont need to go to another page, the second ajax is not required. So it makes more sense like this
    Code:
                if(200 == data.code){
                    $('#my-success').html("<h4 id='my-success'>Form Submitted!</h4>");
                    $("#my-form")[0].reset();
                    $("#my-company-id, #my-name-id, #my-email-id, #my-phone-id").css({
                        "background-image": "none"
                    });
                }
    It is still the same as before though, first time gets sent through fine, any time after this everything appears ok, but no email is sent. Have to clear the cache to make it work again. Even looking at the console for the second time around, everything appears correct. The post is
    my-company Testing
    my-email test@test.com
    my-name Tester
    my-phone 777777777

    And the response is
    {"code":200}

    So I am posting the correct thing, the response is correct, but no email being sent. Everything looks correct doesnt it?

    Cheers

    Nick

  • #4
    Regular Coder hdewantara's Avatar
    Join Date
    Aug 2009
    Location
    Jakarta, Indonesia.
    Posts
    361
    Thanks
    9
    Thanked 53 Times in 52 Posts
    Sorry Nick,
    Your javascript / jQuery seems to look fine to me, and your PHP script looks okay too. Perhaps this is something do with your mail server? I might go back testing this mail issue with plain, traditional form (no javascript) if I were you
    Last edited by hdewantara; 07-06-2014 at 05:26 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •