I am trying to build website for team project. Basically, this web-site takes some datas from here. I used HTML, PHP, jQuery and Ajax in order to provide some functionalities for my website. I created an object with PHP and I printing functionalities by using for loop. poll_id is the critical part in there because when I vote two photos, I use specific ID in order to determine which poll will be voted. Here is the little snapshot from my website. Let's come to the problem. If I use SESSION in order to pass values to "Ajax.php" which includes post functions to our API, it directly votes last poll element of the database whichever I clicked.
So, question is >>> How can I pull specific ID from jQuery to Ajax by clicking button.
Here the some code to clarify my question.
From Ajax.php
<?php
session_start();
$user_id = $_SESSION['user_id'];
//$polls_id = $_SESSION['polls_id'];
if($_GET) {
if(isset($_GET['insert'])) {
vote_poll1($user_id, $polls_id);
}
elseif(isset($_GET['select'])) {
vote_poll2($user_id, $polls_id);
}
}
function vote_poll1($user_id, $polls_id){
$postdata = http_build_query(
array(
'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);
FROM First.php
public function getButtons() {
//$_SESSION['polls_id'] = $this->polls_id;
//echo $_SESSION['polls_id'];
echo $this->polls_id;
echo '<script src="https://code.jquery.com/jquery-2.0.0.js"></script>';
echo '<form action="ajax.php" id=' . $this->polls_id . '>';
echo "\t";
echo '<input type="submit" class="button" name="insert" value="Click here to vote" />';
echo "\t\t\t\t\t\t ";
echo '<input type="submit" class="button" name="select" value="Click here to vote" />';
echo "</form>";
echo "<script>";
echo "$(document).ready(function(){";
echo "$('.button').click(function(){";
echo "var clickBtnValue = $(this).val();";
echo "var idValue = $(this).attr('id')";
echo "var ajaxurl = 'ajax.php'";
//echo "var id = " . $this->polls_id;
echo "data = {'action': clickBtnValue, 'id': idValue};";
echo "$.post(ajaxurl, data, function (response) {";
echo 'alert("Action performed successfully");';
echo "});";
echo "});";
echo "});";
echo "</script>";
}
}
How can I take id from my jQuery script code to my Ajax.php in order to send appropriate data to our API?