Danny Cooper
Danny Cooper

Reputation: 355

Download on Form Submit & Validation w/ AJAX and jQuery

I have created a one input form for an email address that works fine and validates with AJAX and jQuery. All I need is the "Submit" button to also start a download of a specific file once the form is validated. This file will not change, it will be the same for every user as long as the email is valid.

What do I need to add to my jQuery validation file in order to get this working? Thank you!

Here's my form code:

<form name="contact" method="post">

    <div id="multitudes-download-form">

        <div style="float:left;">
            <label for="email">Your Email:</label>
            <input type="text" name="email" id="email" value=""/>
        </div>

        <div>
        <input type="submit" name="submit" class="button" id="submit_btn" value="Download Now" />

        <span class="error" id="email_val_error">Please provide a valid email address.</span><div id="loadingdiv" style="float:right;"><img src="../ajax-loader.gif"/></div>
        </div>
    </div>

</form>

Here is my validation:

$(function() {
  $('.error').hide();
  $('input.text-input').css({backgroundColor:"#FFFFFF"});
  $('input.text-input').focus(function(){
    $(this).css({backgroundColor:"#FFDDAA"});
  });
  $('input.text-input').blur(function(){
    $(this).css({backgroundColor:"#FFFFFF"});
  });

  $(".button").click(function() {
        // validate and process form
        // first hide any error messages
    $('.error').hide();

        var email = $("input#email").val();
        var atpos=email.indexOf("@");
        var dotpos=email.lastIndexOf(".");
        if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length || email== "") {
        $("span#email_val_error").fadeIn();
        $("input#email").focus();
        return false;
    }

        var dataString = 'email=' + email;
        //alert (dataString);return false;

        $.ajax({
      type: "POST",
      url: "process.php",
      data: dataString,
      success: function() {
        $('#multitudes-download-form').html("<h6>Thank you!</h6>")
        .hide()
        .fadeIn(500, function() {
        });
      }
     });
    return false;
    });
});

$(function() {
    $('#loadingdiv')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).fadeIn();
    })
    .ajaxStop(function() {
        $(this).hide();
    });
});

Upvotes: 0

Views: 1166

Answers (1)

mymotherland
mymotherland

Reputation: 8228

You can trigger anchor tag using click function on ajax success event to download the file. Give download link for anchor tag and make it as display:none as inline style

Upvotes: 1

Related Questions