Aniruddh Bhagwat
Aniruddh Bhagwat

Reputation: 37

Multiple Forms on Same page AJAX

I'm having troubles on making this work. I need to have multiple forms on the same page... I've tried countless things, but nothing seem to work.

What I'm trying to do here is identify every form (in some way) in order to submit that one instead of the FIRST form on the page. Code below, works but submits always the same form, the first one!

Here's my current code

JS:

$(document).ready(function(){

    $('.submit').on("click", function() {

        var artworkId = $("#inquirebox").data("artworkid");

        $.post("send.php";, $("#artinquire"+artworkId).serialize(), function(response) {
            $('#success').html(response);
        });

        return false;

    });

});

HTML:

<div id="inquirebox" data-artworkid="<?php echo 456;?>">
    <form action="" method="post" id="artinquire<?php echo 456;?>" data-artworkid="<?php echo 456;?>">
        <label for="name">Name:</label><br />
        <input type="text" name="name" id="name" /><br />

        <label for="email">Email:</label><br />
        <input type="text" name="email" id="email" /><br />

        <label for="message">Message:</label><br />
        <textarea name="message" id="message"></textarea><br />

        <input type="hidden" name="id" value="<?php echo 456;?>">
        <input type="hidden" name="artist" value="<?php echo $title1; ?>">
        <input type="hidden" name="url" value="<?php echo $uri1; ?>">
        <input type="hidden" name="artwork" value="<?php echo $artwork1; ?>">

        <input type="button" value="send" class="submit" id="submit" data-artworkid="<?php echo 456;?>">
        <div id="success"></div>
    </form>
</div>

Upvotes: 1

Views: 7663

Answers (1)

adeneo
adeneo

Reputation: 318182

You're using the same ID on all the DIV wrappers around the forms.

ID's must be unique, so you could use a class instead, but you really don't need any identifiers at all, nor do you need data attributes, the .submit button is inside the form, so all you need is this.form, or more jQuery'ish $(this).closest('form') to get the parent form

$(document).ready(function(){

    $('.submit').on("click", function() {

        var form = $(this).closest('form');

        $.post("send.php", form.serialize(), function(response) {
            form.find('.success').html(response);
        });

        return false;

    });
});

You should however use a class on the #success element to find it based on the form.

Upvotes: 3

Related Questions