J. Doe
J. Doe

Reputation: 143

jQuery - Dynamically Load Form and Submit with AJAX

I'm trying to load a form into a dialog using .load(url) and then enabling AJAX submit on it. It does load the form into the dialog, but it seems it completely ignoring my jQuery code and just submits it normally with page refresh.

I use the AJAX code on multiple sites (not dynamic) and that works just as intended.

Here I will show you the code:

javascript.js; wrapped into a ready() to submit the dynamic form

$("#dbsearch").submit(function(event) {
    alert('click!');
    var data = $("#dbsearch").serialize();
    $.ajax({
        url: 'ajax.php',
        type: 'POST',
            data: data,
            success: function(response) {
                alert(response);
            }
    });

    event.preventDefault();
});

form.php; loaded into a modal

<form method="post" id="dbsearch">
    <div class="form-group col-xs-12 col-md-12">
        <label for="method" class="control-label">Search By</label>
        <select class="form-control" id="method" name="method">
            <option>Choose...</option>
            <option value="content-type">Search By Name</option>
            <option value="release-date">Search By Release Date</option>
        </select>
    </div>
    <div class="form-group col-xs-12 col-md-12">
        <label for="value" class="control-label">Value</label>
        <input type="text" value="" class="form-control" id="value" placeholder="Enter a term...">
    </div>
    <div class="form-group col-xs-12 col-md-12">
        <input type="submit" value="Search" class="btn btn-primary btn-block">
    </div>
</form>

What can be causing this? Is it because it's dynamically loaded into a dialog? If so, what would be the best way to resolve such issue?


Updated JS Code

$("#dbsearch").delegate("#dbsearch input[type=submit]", "click", function(event) {
    alert('click!');
    var data = $("#dbsearch").serialize();
    $.ajax({
        url: 'ajax.php',
        type: 'POST',
            data: data,
            success: function(response) {
                alert(response);
            }
    });

    event.preventDefault();
});

Upvotes: 1

Views: 1731

Answers (2)

Leonardo Roese
Leonardo Roese

Reputation: 94

You can load your code in your dialog container element by using "html" method, it will load your js functions on the browser.

$.get(url, function(result){
   $('mydialogdiv').html(result);
});

Upvotes: 0

Steve Mulvihill
Steve Mulvihill

Reputation: 717

This is happening because you are using a direct event handler instead of a delegated event handler. Event delegation allows us to attach an event listener to elements that exist now or in the future.

https://learn.jquery.com/events/event-delegation/

Example (not tested):

$("#dbsearch").delegate("#dbsearch input[type=submit]", "click", function(event) {
  // Your code here
  event.preventDefault();
});

Upvotes: 1

Related Questions