简体   繁体   中英

Multiple form submits from same page with ajax

I have a page which loads a bunch of questions from my database.

The questions all have 2 forms with it.

Like:

<div class="col-xs-6">
    <form method="post" action="" id="knowId-XXXXX-y">
        <input type="hidden" name="userKnewStatus" value="YES">
        <input type="hidden" name="knowId" id="knowId" value="#ID">
        <input type="hidden" name="knewStatus" id="knewStatus" value="1">
        <button class="btn btn-success dyk-btn" type="submit">
            Ja <i class="fa fa-smile-o fa-fw"></i>
        </button>
    </form>
</div>

<div class="col-xs-6">
    <form method="post" action="" id="knowId-XXXXX-n">
        <input type="hidden" name="userKnewStatus" value="YES">
        <input type="hidden" name="knowId"  id="knowId" value="#ID">
        <input type="hidden" name="knewStatus" id="knewStatus" value="0">
        <button class="btn btn-danger dyk-btn" type="submit">
            Nej <i class="fa fa-meh-o fa-fw"></i>
        </button>
    </form> 
</div>

To submit the form i have the following code in Jquery/ajax.

<script type='text/javascript'>
    /* attach a submit handler to the form */
    $("form").submit(function(event) {

        /* stop form from submitting normally */
        event.preventDefault();

        /* get some values from elements on the page: */
        var $form = $( this ), 
            url = $form.attr( 'action' );

        /* Send the data using post */
        var posting = $.post( url, { knowId: $('#knowId').val(), knewStatus: $('#knewStatus').val() } );

        /* Alerts the results */
        posting.done(function( data ) {
        alert('success');
        });
    });
</script>

The forms are getting submitted but due to the duplicate in ID for the form the first values is always sent to the row.

How do i assign the jquery to pick the id from within the form itself?

I'm not fancy in jquery at all but i tried to insert "this" but then i just receive error.

Change your ID properties to Classes first of all where you have elements with the same ID, as someone has said already, an ID should be unique on your page. Then you can get that class from the form you've clicked on by doing:

$form.find('.knowId').val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM