user3412305
user3412305

Reputation: 261

ajax response returning the same value

I am trying to implement voting system and have a while loop in which I am displaying voting results from the database. Just to get started, I tried echoing the id as a value for vote up button and then get the id of the button to display back via ajax request. The request is going through but it gives me the same id no matter which button I click on. I have 4 rows in the table and when I see the source page I see the value of each button correctly which is 1-4 but when I click on the button it only returns the last id which is 4(I am ordering DESC). Can someone help?

 <div class="response"></div>    

 while($row = $result->fetch_assoc())
    {
     echo"<button value='".$row['id']."' class='btn btn-default test' href='javascript:void(0);' onclick='voteup();'>."$row['voteup']".</button>";
    }

js

function voteup()
{
var dataString = 'test='+ test;
        $.ajax({
        type: "GET",
        url: "test.php?tar=vrate",
        data: dataString,
        cache: false,
        success: function(response)
        {  
            $(".response").fadeIn('slow').html(response);

        }
        });
 }

test.php

if(isset($_POST["tar"]) && !empty($_POST["tar"]) || isset($_GET["tar"]) && !empty($_GET["tar"])) 
{
if(isset($_GET["tar"]) == "vrate")      
{ 
$cos = $_GET['test'];
echo $cos;
}
}

Upvotes: 0

Views: 1147

Answers (1)

000
000

Reputation: 27227

This code could use some help, so here are some pointers and an answer:

Keep a cleaner separation of php and html by using the alternative while syntax.

Buttons don't have an href. And I removed the onclick so it will be attached in jquery.

<div class="response"></div>    

<?php while($row = $result->fetch_assoc()): ?>
  <button value='<?=$row['id']?>' class='btn btn-default test'>
    <?=$row['voteup']?>
  </button>
<?php endwhile; ?>

js

$(function() {
  $('.test').on('click', function() { // attach the click to the button
    var test_val = $(this).val(); // Grab the value from the button
    $.ajax({
        type: "GET",
        url: "test.php", // Move ?tar=vrate to the data array.
        data: {tar: 'vrate', test: test_val},
        cache: false,
        success: function(response)
        {  
            $(".response").fadeIn('slow').html(response);

        }
    });
  });
});

test.php

Since you are doing a GET request, $_POST should not have anything there. Only one of $_GET and $_POST can ever be set at one time. You can't do both types of requests at once.

The empty test is not necessary, since you're just checking for a certain value anyway.

if(isset($_GET["tar"]) && $_GET["tar"] == "vrate") 
{ 
  $cos = $_GET['test'];
  echo $cos;
}

Upvotes: 1

Related Questions