AJAX Post for multiple form

Snowman

I have a list, each row is a form with a submit button. When I submit the form, data is sent through the post and must be update the div with the result. But there is a problem when sending the post, javascript does not send data correctly.

This is index file:

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function() {
    $(".notif-close").click(function(e) {
        e.preventDefault();
        var notif_id = $(".notif_id").val();
        var data = 'notif_id='+ notif_id;
        $.ajax({
            type: "POST",
            url: "post.php",
            data: data,
            beforeSend: function(send) {
                $("#notif_box").fadeOut(400, function() {
                    $('.loader').fadeIn(50);
                    }
                )},
            success: function(html){ // this happen after we get result
                $(".loader").fadeOut(50, function()
                { 
                    $("#notif_box").html(html).fadeIn(400);
                    $(".notif_id").val("");

                });
                return false;
            }
        });   
    });
});
</script>
</head>
<body>
    <form method='post' action='post.php'>
        <input type='hidden' id='notif_id' name='1' class='notif_id' value='1' />
        <button type="submit" id="notif-close" class="notif-close">notif-close1</button>
    </form>
    <form method='post' action='post.php'>
        <input type='hidden' id='notif_id' name='2' class='notif_id' value='2' />
        <button type="submit" id="notif-close" class="notif-close">notif-close2</button>
    </form>
    <div class='notificationsblock' id='notif_box'>Result</div>
    <span class='loader' style="display: none; position: absolute;">Please wait...</span>
</body>
</html>

And this is post.php:

 <?
 sleep(2);
 print_r($_POST);
 ?>

Help me. Please tell me what am I doing wrong?

gskema

Try changing

var notif_id = $(".notif_id").val();

to

var notif_id = $(this).parent().find(".notif_id").val();

You can also try changing

var data = { 'notif_id' : notif_id }

You also have same IDs: #notif_id, #notif_close, which can (and will) cause errors and conflicts. You must give unique IDs. Giving unique names to input elements and forms is also a better idea.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related