BL1nK
BL1nK

Reputation: 25

AJAX script working with only one of the buttons

What I'm trying to do: Make Upvote and Downvote buttons, using AJAX to send to a php script that processes it.

The Problem: The script only works with one set of buttons. Each item has it's own upvote/downvote button but the script only works with the first item but not the rest.

HTML(Each item has it's own div with these button/forms)

        <form id="upvote-form">
            <input name="idea_name" type="hidden" value="test">
            <input name="topic_name" type="hidden" value="test">
            <input name="vote" type="hidden" value="up">
            <input name="submit" id="upvote" type="submit" value="">
        </form>
        <form id="downvote-form">
            <input name="idea_name" type="hidden" value="test">
            <input name="topic_name" type="hidden" value="test">
            <input name="vote" type="hidden" value="down">
            <input name="submit" id="downvote" type="submit" value="">
        </form>

AJAX/Javascript(right now this is just a test script)

  $(function () {
    $( "#upvote-form" ).on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'scripts/vote.php',
        data: $('form').serialize(),
        success: function (data) {
          alert(data);
        }
      });
      e.preventDefault();
    });
  });
  $(function () {
    $( "#downvote-form" ).on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'scripts/vote.php',
        data: $('form').serialize(),
        success: function () {
          alert('form was submitted');
        }
      });
      e.preventDefault();
    });
  });

Upvotes: 1

Views: 339

Answers (2)

Barmar
Barmar

Reputation: 780851

Change:

data: $('form').serialize(),

to:

data: $(this).serialize();

You were combining both forms. Since they had duplicate names, the server only picked up the ones from the first form.

You also have duplicate IDs in each set of buttons. Change id="upvote-form" to class="upvote-form", and the same for downvote-form. And change your jQuery to bind to $('.upvote-form') and $('.downvote-form').

I don't know if you really need the IDs on the submit buttons. You should remove them if they're not used, or change them to classes and fix the code that binds them.

Upvotes: 1

wrshawn
wrshawn

Reputation: 439

You have duplicate IDs inside each of the divs. $('#upvote-form') will only select the first item with an id of 'upvote-form' since ids are supposed to be unique. change it to a class instead of an id and it will attach the event handler properly.

Upvotes: 3

Related Questions