I'm trying to create a system where people can vote on answers to a question.
The answers are fetched from a database then displayed in a foreach.
For the voting system I need to pass certain variables into JS to the do some AJAX magic with, however i'm falling at the first hurdle of just passing the variables to JS.
At the moment the code looks like such:
<?php
if ($answers->num_rows() == 0) {
echo '<p>Be the first to answer this question!</p>';
} else {
foreach ($answers->result() as $row)
{
echo '<div class="answers-to-question">';
echo '<form>'; //form for the purpose of voting
echo '<input type="hidden" name="a_id" value="'.$row->a_id.'">'; //pass this to voting script
echo '<input type="hidden" name="u_id" value="'.$row->username.'">'; //pass this to voting script
echo '<pre>'.$row->answer.'</pre>';
echo '<p class="green">answered '.$row->timestamp.' by <i class="green">'.$row->username.'</i></p>';
echo '<input type="button" name="upvote" value="upvote" onClick="upvote(this.form.u_id);">';
echo '</form>';
echo '</div>';
}
}
?>
So I have a button which on click should pass the variables in a JS function
Button
echo '<input type="button" name="upvote" value="upvote" onClick="upvote(this.form.u_id);">';
Javascript
$(document).ready(function(){
function upvote(username){
console.log(username);
}
});
This isn't working and i'm getting the error:
Uncaught TypeError: object is not a function onClick
If it helps, i'm using the Codeigniter and JQuery frameworks
Any help greatly appreciated
Do it all with jQuery instead of using inline JavaScript -
$(document).ready(function(){
function upvote(username){
console.log(username);
}
$('input[name="upvote"]').click(function() {
var username = $(this).parent('form').find('[name="u_id"]').val();
upvote(username);
});
});
Here is an UPDATE sending two variables to the function.
Just for adding some information, the code had two problems:
You were calling your function the same that your button, so that was why the message said that it wasn't a function, it was an element.
The function was declared inside de .ready() statement, so the function didn't exist. You must declare it before the ready() statement.