2

I've got a problem figuring out how to pass a variable to parameter of the ajaxForm() function. I am getting templatedir path from hidden form field after clicking on form button in jQuery (this works great) and I can pass it to other function but not to the ajaxForm() parameter:

    var templatedir;

    // Get variable of templatedir
    $('form#contact input[type="submit"]').on('click',function(){
        templatedir = $('input[name=templatedir]').fieldValue();   
    });

    // Validate Form
    function validateform(formData, jqForm, options) {         
        ...
        // IF I CALL TEMPLATEDIR HERE IT WORKS
    }   

    // Send to PHPMailer
    $("form#contact").ajaxForm({
        url: templatedir, // IT DOESNT WORK HERE
        type: 'post', 
        beforeSubmit: validateform,
        target: '#msg',
        clearForm: true
    });

I tried the solution from this answer (How do i pass variables between functions in javascript) as you can see but it doesn't work.

Community
  • 1
  • 1
poho
  • 29
  • 3

2 Answers2

0

Your variable templatedir is undefined.

You should call ajaxForm() in click event.

$('form#contact input[type="submit"]').on('click',function(event) {
    event.preventDefault();

    // Send to PHPMailer
    $("form#contact").ajaxForm({
        url: $('input[name=templatedir]').fieldValue(),
        type: 'post', 
        beforeSubmit: validateform,
        target: '#msg',
        clearForm: true
    });
});
Martin Hučko
  • 791
  • 5
  • 16
0

The points of interest are:

  • you cannot use the templatedir variable before you set it
  • change templatedir = $('input[name=templatedir]').fieldValue(); to

    templatedir = $('input[name=templatedir]').val();

  • remove url: templatedir, // IT DOESNT WORK HERE and set it in validateform: before form submission

My snippet:

var templatedir;

$(function () {
  $('form#contact input[type="submit"]').on('click', function(){
    templatedir = $('input[name=templatedir]').val();
  });
  function validateform(formData, jqForm, options) {
    // because you now are in the beforesubmit event
    // you can change the url.....
    options.url = templatedir;
  }

  $("form#contact").ajaxForm({
    type: 'post',
    beforeSubmit: validateform,
    target: '#msg',
    clearForm: true
  });
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://malsup.github.io/jquery.form.js"></script>

<form id="contact" action="www.google.com" method="post">
    templatedir: <input type="text" name="templatedir"/>
    <input type="submit" value="Submit Comment" />
</form>
<div id="msg"></div>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61