How to pass extraparameter using jQuery.submit()?

Viewed 45

How to pass extraparameter using jQuery.submit() ?.

if you see this: https://api.jquery.com/submit/

you will see submit function accept eventdata argument, but how to make eventlistener grab this data?

Note: I dont want the handler to be put inside the submit function like: .submit( [eventData ], handler )

This is not working:

<form id="form1">
<button type="submit" id="button1">Click here to test</button>
  <input type="text" value="123">
</form>

<script>
$(function() {

  $('#button1').on('click', function(e) {
    $('form#form1').submit({"url": "url"});
  });
  
 $("form#form1").on("submit", function(event,data){
   console.log(event);
   console.log(data); //this is not exist. why?
   return false;
 });


});
</script>
1 Answers

.submit() didn't pass [eventData] to the submit event, It pass [eventData] to the handler in .submit( [eventData], handler)

Instead, you should use .trigger( event, [ extraParameters ] ). It triggers the event dynamically and adds extraParameters to it. Also, change the button to type="button" to prevent form submit again after .trigger (this time it won't extraParameters in it)

$(function() {
    $('#button1').on('click', function(e) {
        $('form#form1').trigger("submit", {"url": "url"});
    });

    $("form#form1").on("submit", function(event,data){
        console.log(event);
        console.log(data); //this is not exist. why?
        return false;
    });
});
<form id="form1">
    <button type="button" id="button1">Click here to test</button>
    <input type="text" value="123">
</form>

Related