Reputation: 3882
I'm not very well versed in JavaScript/jQuery, but I have managed to write a poll script that allows a user to vote on a poll and display results without refreshing the page. This is the jQuery code I've came up with:
$("#poll_yes").click(function(){
$("#poll_options").html(ajax_load);
$.post(
"query.php?module=vote",
{answer: "yes", pid: "<? display($_GET['username'], poll_id); ?>", to: "<?= $_GET['username'] ?>"},
function(responseText){
$("#poll_options").html(responseText);
},
"html"
);
});
$("#poll_no").click(function(){
$("#poll_options").html(ajax_load);
$.post(
"query.php?module=vote",
{answer: "no", pid: "<? display($_GET['username'], poll_id); ?>", to: "<?= $_GET['username'] ?>"},
function(responseText){
$("#poll_options").html(responseText);
},
"html"
);
});
This would get the id of the input element on the page and based on the id it would then send a query to query.php. query.php would then send a response back and that response would then be displayed on the page.
This script is working fine but I have run into another challenge. I need multiple polls displayed on one page. I'm using php to generate the polls from a SQL database and was wondering if it was possible to pull the values for "answer: no", "answer:yes", "pid: $id", "to: $username", etc.. from an field. If this is possible, would multiple forms be needed through out the page (for each poll)? or would one form suffice with multiple inputs?
Upvotes: 0
Views: 136
Reputation: 176956
yes you can get the value form the form fileds easily by using .val() function of jquery
$("#yourid").val();
Upvotes: 1
Reputation: 30456
You could have a form for each poll, and include the pid as an input with type="hidden". Then instead of using the click even on a yes or no button (by ID) you would attach a callback on all forms submit event. This would also let you collapse your two functions into a single callback.
<script>
$("form.Poll > input[type='button']").click(function(e) {
e.preventDefault();
var form= $(this).closest("form");
alert("QuestionId:"+$("input[name='QuestionId']", form).val()+" clicked on:"+$(this).val());
});
</script>
<form method='POST' action='update.php' class='Poll'>
<input type='hidden' name='QuestionId' value='1'/>
Do you like jQuery?
<input type='button' name='Answer' value='Yes'/>
<input type='button' name='Answer' value='No'/>
</form>
<form method='POST' action='update.php' class='Poll'>
<input type='hidden' name='QuestionId' value='2'/>
Do you like AJAX?
<input type='button' name='Answer' value='Yes'/>
<input type='button' name='Answer' value='No'/>
</form>
<form method='POST' action='login.php'>
This form will fire like a normal form if you click on submit but it will not pass though the submit script defined above
<input type='submit' name='Answer' value='Login'/>
</form>
This can be tested at http://jsfiddle.net/te9YL/
Upvotes: 1