2

I am trying to send an e-mail after an ajax call has been successfully completed. I do not have access to the file that I am making the AJAX call to.

I am preventing the first submit, making the ajax call and submitting the form again upon competition. When doing this, I can't seem to figure out why I have to press the submit button twice for the email to be sent.

Here is my code:

"use strict";
var submitted = '';

/* Send info to the portal */
jQuery(function($) {
    $('#quote').submit(function(e){
        var firstName   = $('#firstName').val(),
            lastName    = $('#lastName').val(),
            email       = $('#email').val(),
            phone       = $('#primaryPhone').val(),
            weight      = $('#weight').val(),
            origin      = $('#originPostalCode').val(),
            destination = $('#destinationPostalCode').val(),
            notes       = $('#whatsTransported').val()
        if( submitted != 1 )
        {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "https://somewhere.on/the/internet.php",
                crossDomain: true,
                dataType: "json",
                data: {"key": "my secret key","first": firstName, "last": lastName, "email": email, "phone": phone, "weight": weight, "origin_postal": origin, "dest_country": destination, "note": notes }
            })
            .done(function(data){
                if(data[1][0][0] == 2)
                {
                    $('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
                } else if(data[1][0][0] == 0) {
                    console.log("Made it.");
                    $('#quote #submit').submit();
                } else {
                    $('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
                }
            })
            .fail(function(data) { console.log(data); });
        }
        submitted = '1';
    });
});

Here is the form HTML

<form action="<?php echo bloginfo($show='template_url').'/includes/form-email.php'; ?>" class="span6 offset1" id="quote" method="post">
            <div class="row formRow">
                <div class="firstName span3">
                    <label for="firstName"><?php _e('First Name:','StreamlinedService'); ?></label>
                    <input type="text" name="firstName" id="firstName">
                </div>
                <div class="lastName span3">
                    <label for="lastName"><?php _e('Last Name:','StreamlinedService'); ?></label>
                    <input type="text" name="lastName" id="lastName">
                </div>
            </div>
            <div class="row formRow">
                <div class="email span3">
                    <label for="email"><?php _e('Email Address:','StreamlinedService'); ?></label>
                    <input type="text" name="email" id="email">
                </div>
                <div class="primaryPhone span3">
                    <label for="primaryPhone"><?php _e('Phone Number:','StreamlinedService'); ?></label>
                    <input type="text" name="primaryPhone" id="primaryPhone">
                </div>
            </div>
            <div class="row formRow">
                <div class="weight span2">
                    <label for="weight"><?php _e('Weight (lbs):','StreamlinedService'); ?></label>
                    <input type="text" name="weight" id="weight">
                </div>
            </div>
            <div class="row formRow">
                <div class="originPostalCode span3">
                    <label for="originPostalCode"><?php _e('Origin:','StreamlinedService'); ?></label>
                    <input type="text" name="originPostalCode" id="originPostalCode">
                </div>
                <div class="destinationPostalCode span3">
                    <label for="destinationPostalCode"><?php _e('Destination:','StreamlinedService'); ?></label>
                    <input type="text" name="destinationPostalCode" id="destinationPostalCode">
                </div>
            </div>
            <div class="row">
                <div class="whatsTransported span6">
                    <label for="whatsTransported"><?php _e('What can we help you transport?','StreamlinedService'); ?></label>
                    <textarea name="whatsTransported" id="whatsTransported" rows="5"></textarea>
                </div>
                <input type="hidden" name="formType" value="quote" />
                <input type="hidden" name="siteReferer" value="<?php echo $blog_id ?>">
                <input type="submit" id="submit" name="submit" value="<?php _e('Get Freight Quote','StreamlinedService') ?>" class="btn btn-primary btn-large span3 offset3" style="float:right;">
            </div>
        </form>

My question is two-fold: Is there a more efficient way to do this? If not, why isn't this working?

Greg Wiley
  • 323
  • 1
  • 2
  • 12

2 Answers2

0

You use the wrong approach to Jquery You miss the key : Write Less Do More, the heart of JQuery. Anyway try this:

"use strict";
/* Send info to the portal */
jQuery(function($) {
    $('#quote').submit(function(e){
         var tis = $(this);
         $.ajax({
                type: "POST",
                url: "https://somewhere.on/the/internet.php",
                cache: true,
                dataType: "json",
                data: tis.serialize(),
                success: function(data){
                   if(data[1][0][0] == 2){
                    $('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
                } else if(data[1][0][0] == 0) {
                    console.log("Made it.");
                    $('#quote #submit').submit();
                } else {
                    $('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
                }
                },
                error: function(data){console.log(data);}
            });
         e.stroPropagation();
         e.preventDefault();
    });
});

Last thin.. you CAN'T request a remote page that's not hosted on the same domain of the script.. For that ther's This answer

Community
  • 1
  • 1
ExoticSeagull
  • 1,547
  • 25
  • 46
  • And he can "write less" here: $('#quote #submit'), which is at best a less-efficient way of selecting $('#submit') – weir Feb 01 '13 at 18:48
  • Right there're a lot of things that's he can optimize in that code. I edit only a bounch of it. Feel free to edit my code :-) – ExoticSeagull Feb 01 '13 at 18:49
  • Much of that bulk was me trying to separate things out to make sure that I'm not missing something silly. I doubled up on id's to make sure that there were no other conflicts. Thanks for review. I just can't seem to see why the form isn't being submitted on `$('#quote #submit').submit();` – Greg Wiley Feb 01 '13 at 18:58
  • Also, my server is accepting a cross-domain request from my local machine. – Greg Wiley Feb 01 '13 at 19:00
  • @ClaudioLudovicoPanetta wouldn't this end in an infinite loop? The ajax call will continue to be submitted over and over, as there is no way to tell if the ajax request has already been run after the `submit()` upon `success:` – Greg Wiley Feb 01 '13 at 19:06
0

Just use the .submit directly on the form node (note the [0])

$('#quote #submit').submit();

becomes

$('#quote')[0].submit();

this bypasses the jQuery bound event and forces a postback.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • `Uncaught TypeError: Property 'submit' of object # is not a function` is the error that I receive. – Greg Wiley Feb 01 '13 at 19:13
  • That doesn't make any sense... all form elements should have a submit method... `document.createElement("form").submit` -> `function submit() { [native code] }` – Kevin B Feb 01 '13 at 19:37
  • I'm looking for the article, but I remember there being record of a bug that required you to perform the submit method on the button and not the form. – Greg Wiley Feb 01 '13 at 19:47
  • a jquery bug? or native javascript. the suggestion i'm making uses native DOM methods, nothing related to jQuery. I've never heard of having to submit from the button instead. – Kevin B Feb 01 '13 at 19:57
  • Interesting: Out of desperation I decided to try `$('#quote').unbind().submit();` and it worked. – Greg Wiley Feb 01 '13 at 20:04
  • That's definitely an option, has pretty much the same effect. – Kevin B Feb 01 '13 at 20:06
  • 1
    "Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures." This might have been part of the problem, but as you stated, we were using native DOM methods, so I'm not sure why it wasn't working. http://forum.jquery.com/topic/submiting-a-form-programmatically-not-working – Greg Wiley Feb 01 '13 at 20:12
  • `document.createElement("form").setAttribute("id","submit").submit -> failure` Yup that was the cause of the native .submit not working. :) – Kevin B Feb 01 '13 at 20:13