Efe Özelçi Efe Özelçi - 2 years ago 77
Javascript Question

Why Clicking One Button Affects All Buttons in jQuery Ajax

I want to click one button that affects(post something to our API) its specific id. However, when I clicked it, whole buttons of the page send data to our API. Here is the little snapshot of my page. All rows has unique id as you can see, however when I clicked relative vote button in the row, it votes all rows.

My jQuery and Ajax code is here

jQuery in First.php

public function getButtons() {
$ids = $this->polls_id;
echo $this->polls_id;

echo "<html>";
echo "<head>";
echo '<meta charset="utf-8">';
echo '<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>';
echo '<script type="text/javascript"></script>';
echo '<script type="text/javascript">';
echo '$(function(){';
echo "$('body').on('click', 'button', function(event){";
echo "event.preventDefault();";
echo "var pollss_id = $('#" . $ids . "').text();";
echo "$.ajax({";
echo "method: 'POST',";
echo "url: 'ajax.php',";
echo "data: {'pollss_id' : pollss_id}";
echo "})";
echo "});";
echo "});";
echo "</script>";
echo "</head>";
echo "<body>";
echo '<div id='. $ids .'>' . $ids . '</div>';
echo '<button type="button">Vote</button>';
echo "</body>";
echo "</html>";


$user_id = $_SESSION['user_id'];

if($_POST) {
$polls_id = $_POST['pollss_id'];

function vote_poll1($user_id, $polls_id){
$postdata = http_build_query(
'user_id' => $user_id,
'poll_id' => $polls_id,
'vote_value' => '1'
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
$context = stream_context_create($opts);
$result = file_get_contents('http://sitename.herokuapp.com/api/v1/polls/'. $polls_id . '/castvote', false, $context);

echo vote_poll1($user_id, $polls_id);

PS: I create object and call functions(pictures, text fields, buttons) with for loop. What might be a problem for that?

Answer Source

The way you are doing it right now you are registering a click event on every button.

So the code

$('#" .  $ids . "').text();

will run on any button click.

What you could do is add that function one time and add the pollid as a data attribute to the button itself

<button data-poll-id="5" type="button">Vote</button>

then on your function yu can get the id with jQuery's data function

var poll_id = $(this).data("poll-id")

and make your ajax call as you have it now

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download