How to make bootstrap Voting snippet functional, change value in MySQL - javascript

I am trying to add a voting/poll panel in sidebar of my HTML/PHP/MySQL website.
Scenario
I have list of plans for separate places in MySQL Database Table, when some one search for the place they will also see list of plans decided for that place. They can vote for what plan to be executed next in that place.
What I have worked so far?
I am able to fetch plans for specific places when viewers search for any place.
Code used:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Vote next plan
</h3>
</div>
<div id="voting">
<form>
<div class="panel-body">
<ul class="list-group">
<?php
while ($planvote = mysql_fetch_array($planresultv)) {
echo '<li class="list-group-item">';
echo '<div class="radio">';
echo '<label>';
echo '<input type="radio" name="optionsRadios">';
echo $planvote['plan_name'];
echo '</label>';
echo '</div>';
echo '</li>';
}
?>
</ul>
</div>
<div class="panel-footer">
<button type="button" class="btn btn-primary btn-sm">
Vote</button>
View Result
</div>
</form>
</div>
Screenshot
Now, I have a database table with columns
|sn|plan_name|poll|
|1 |Path way |0 |
How can I add/change value of poll in some on selects radio button on the voting form and clicks vote.
P.S. You can answer ideas or help me with code if you want to.

You could add a value to you radio button:
echo '<input type="radio" name="optionsRadios">';
After you did this, you could make an ajax call where you update the results by getting the value of the radiobutton. Make sure to add an id to your button:
<button id='vote_button' type="button" class="btn btn-primary btn-sm">
Ajax call:
$("#vote_button").click(function(){
if($("input[type='radio'][name='optionsRadios']:checked").length > 0){
var chosenvalue = $("input[type='radio'][name='optionsRadios']:checked").val();
var dataString = 'paramX=' + chosenvalue;
$.ajax({
type: "POST",
url: "yourfile.php",
data: dataString,
cache: false,
success: function (html) {
}
});
}
});
In your ajax call you can update the voting system by using some PHP code and an SQL like where $val = the passed value to your ajax:
UPDATE your_table SET poll = poll + 1 WHERE sn = $val
But you will probably have to add way more coding than this, else people can just spam the voting system..

Solution
JS/Ajax Script
<script src="js/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$("#vote_button").click(function(){
if($("input[type='radio'][name='optionsRadios']:checked").length > 0){
var chosenvalue = $("input[type='radio'][name='optionsRadios']:checked").val();
var dataString = 'paramX=' + chosenvalue;
$.ajax({
type: "POST",
url: "yourfile.php",
data: dataString,
cache: false,
success: function (html) {
console.log(html);
$('.notice').html(html);
},
error: function(err) {
console.log(err);
}
});
}
});
HTML/ PHP
<div id="voting">
<form>
<div class="panel-body">
<ul class="list-group">
<?php
while ($planvote = mysql_fetch_array($planresultv)) {
echo '<li class="list-group-item">';
echo '<div class="radio">';
echo '<label>';
echo '<input type="radio" name="optionsRadios" value="'.$planvote['sn'].'">';
echo $planvote['vdc_PlName'];
echo '</label>';
echo '</div>';
echo '</li>';
}
?>
</ul>
</div>
<div class="panel-footer">
<button id="vote_button" type="button" class="btn btn-primary btn-sm">
Vote</button>
View Result
</div>
</form>
Finally it update the value of poll in database table.

Related

How to get the ID of a dynamically generated button using jQuery?

I need some help. I have a page where I display database records as a bootstrap button pill in a display div. I also have an Ajax Submit input that saves new records to the database and dynamically creates a button pill for the new record using the db record id for the button id. The jQuery below allows me to click on the new dynamically created button but it always displays ID = 1 and not the ID shown in view source.
Can someone please explain what I am doing wrong here?
Code of Button Pills created from PHP:
<div class="row">
<div class="col-md-8 col-sm-10 mx-auto mb-3">
<div class="decision-box">
<div class="decision-icon bg-orange-grad"><img src="../assets/img/logos/Sparck-Logo-Icon-Lg-White.png" alt="Sparck-Logo-Icon-Lg" width="40" height="40" /></div>
<div class="decision-text">
<form id="accolorform">
<input type="hidden" name="action" value="colorsave">
<input type="hidden" name="interesttype" value="Favorite Color">
<input type="hidden" name="userid" value="<?php echo $_SESSION['userid']; ?>">
Favorite Color:
<input type="text" class="form-control-inline col-auto no-border no-shadow" id="ac_color" name="interest" placeholder="Type something" autocomplete="off" style="min-width: 200px;">
<span class="float-right" style="margin-right: 15px;">
<button type="submit" class="btn btn-light" id="colorbtn">Add</button>
</span>
</form>
</div>
</div>
<div id="color_pills">
<?php if(!empty($resultlist) && isset($resultlist)){
foreach($resultlist as $r){
if($r['interesttype'] = "Favorite Color"){ ?>
<button id="btn<?php echo $r['id']; ?>" class="btnpill" title="Are you sure you want to delete <?php echo $r['interest']; ?>?"><?php echo $r['interest']; ?> <i id="<?php echo $r['id']; ?>" class="fal fa-minus-circle delete"></i></button>
<?php }
}
}?>
</div>
</div>
</div>
Code of jQuery aJax that creates dynamic button
$("#accolorform").validate({
rules: {
ac_color: {
required: true
}
},
messages: {
ac_color: {
required: 'Please select a Color'
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $(form).serialize(),
success: function(id){
//alert("Color Added");
var name = $("#ac_color").val();
var newpill = '<button id="btn'+id+'" class="btnpill" title="Are you sure you want to delete '+name+'?">'+name+' <i id="'+id+'" class="fal fa-minus-circle delete"></i></button>';
$("#color_pills").append(newpill);
$("#accolorform")[0].reset();
},
error: function(){
alert("Error");
}
});
}
});
Code of Ajax Delete where I am trying to grab dynamic button id:
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
var title = $('#btn'+id).attr('title');
var string = 'source=interests&id='+ id ;
if (confirm(title)) {
$.ajax({
type: "POST",
url: "ajaxdelete.php",
data: string,
cache: false,
success: function(){
$('#btn'+id).remove();
}
});
}
return false;
});
The above code looks like it should work and view source shows a button tag that is formatted like the ones created by PHP that work perfectly.
I appreciate any help!

Submit form after getting PHP file via AJAX and placing in form

The programming is being done in Phonegap. I am trying to submit a form with JQuery. I am getting data from two separate PHP files and loading them into different ID's in the form. I am not having an issue getting the data, but the form is not posting. Upon some debugging, it appears to be it is because of the second php file which includes checkboxes.
The HTML code is below:
<div id = "result"></div>
<form method="post" name = "inviteform" id = "inviteform">
<p>
<select name="groupstrip" id = "groupstrip" class="formdrop" /><br />
</p>
<input type='hidden' name='user_name1' id='user_name1' value=''>
<p><input type = "button" id="grpsubmit" name= "grpsubmit" class="formsubmit" value = "Invite"></p>
<nav id="primary_nav">
<ul>
<div id = "friendsinv"></div>
</ul>
</nav>
</form>
The Javascript is below:
var invgrpurl = "http://www.website.com/app/invgrps.php?userid=" + items;
var invfrndurl = "http://www.website.com/app/invfrnds.php?userid=" + items;
$.ajax({
url: invgrpurl,
dataType: "text",
type: "GET",
success: function (data){
//manually insert the page
$("#groupstrip").html(data);
}
});
$.ajax({
url: invfrndurl,
dataType: "text",
type: "GET",
success: function (data){
//manually insert the page
$("#friendsinv").html(data);
}
});
$("#grpsubmit").click(function(event){
event.preventDefault();
$.post( 'http://www.website.com/app/invitemany.php', $("#inviteform").serialize(), function(data){
$("#result").html(data);
$('#inviteform')[0].reset();
});
});
The main data from the PHP file that is causing the issue is:
<li><div class="row">
<div class="col-lg-6">
<div class="input-group">
<span class="input-group-addon">
<?php
echo '<input type= "hidden" name = "id[]" id = "id[]" value="' . $rowid . '"></input>';
echo '<input type="checkbox" aria-label="..." name = "friends[]" id="friends[]" value="' . $y2aac . '">';
echo '</span>';
echo '<input readonly="readonly" type="text" class="form-control" aria-label="' . $fullname . '" placeholder="' . $fullname . '">';
?>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div>
</li>
Any help on getting this to submit would be greatly appreciated

Ajax not working properly when I tried to call it on same page again

I have a PHP page which has two sections (top and bottom). The top section has a table where I have options to Edit the data.
Once the Edit button is pressed, the content is loaded at the bottom of page and the user can change the data.
Here is part of my PHP page:
<div id="product_entry_<?php echo $id?>" class="product_entry_<?php echo $id?>">
<tr>
<td><font size=2px><?php echo $date?></font></td>
<td><font size=2px><?php echo $ProductName?></font></td>
<td><font size=2px><?php echo $Category.' / '.$SubCategory?></font></td>
<td><font size=2px><?php echo $MRP.' / '.$Price?></font></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="DirectPromoteSubmit(<?php echo $id?>)">Promote</button></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="RePromoteSubmit(<?php echo $id?>)">Edit</button></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="DelPromoteSubmit(<?php echo $id?>)">X</button></td>
</tr>
</div>
<!-- page where data is loaded -->
<div class="box box-warning" id="RePromoteReplace">
....some html content here...
</div>
Here is my Javascript:
function RePromoteSubmit(id){
//alert('got into Edit Promotions');
var dataString = "id="+ id;
alert(dataString);
if(dataString=='')
{
alert('Some Problem Occurred, Please try Again');
}
else
{
//alert('into post');
$.ajax({
type: "POST",
url: "SellerPanel/post_repromote.php",
data: dataString,
cache: false,
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").replaceWith(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
});
}return false;
}
Here is my PHP page which loads the bottom section - post_repromote.php:
<?php
include("../dbconnection.php");
include("session.php");
if(!isset($_SESSION))
{
session_start();
}
$id=$_POST['id'];
$query1=mysqli_query($con,"select promotiondata from sellerpromotions where id=$id");
while($row=mysqli_fetch_array($query1))
{
.....some code here.....
}
?>
<div class="box box-warning">
<div class="box-header">
<h3 class="box-title">Fill Product Details</h3>
</div><!-- /.box-header -->
<div class="box-body">
<!-- <form role="form " name="PromoteForm"> -->
<div>
<!-- text input -->
<table class="table">
....some data here from query..
</table>
<div class="box-header with-border">
<h3 class="box-title">Upload your Product Image</h3>
</div><!-- /.box-header -->
<div class="box-body no-padding">
<div id='preview'>
<?php if ($uploadid){ ?>
<img src=<?php echo "SellerPanel/uploads/".$imagename?> id="<?php echo $uploadid?>" alt="User Image" class='preview' style='width:340px;height:200px;border-color:black'/>
<?php }
?>
</div>
<?php
include ("index_photo.php");
?>
<!-- <span class="users-list-date">Yesterday</span> -->
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary" onClick="PromoteSubmit()">Promote</button>
</div>
</div>
</div><!-- /.box-body -->
</div><!-- /.box -->
<?php }
?>
The problem I'am facing:
I'am able to load the data when I press the Edit button first.
When I press it again, I'm not able to load the new data unless I refresh the page and click the Edit button again.
I tried to read the id in JS and printed it, I found that id is being passed correctly.
Any help would be very much appreciated.
Thanks in advance!
JS after using solution:
function RePromoteSubmit(id){
//alert('got into Edit Promotions');
var dataString = "id="+ id;
alert(dataString);
function getRandomInt() {
return Math.floor(Math.random() * Math.pow(10,6));
}
//var url = "SellerPanel/post_repromote.php?"+getRandomInt();
//alert ("url is: "+ url);
if(dataString=='')
{
alert('Some Problem Occurred, Please try Again');
}
else
{
//alert('into post');
$.ajax({
type: "POST",
url: "SellerPanel/post_repromote.php?rnd="+getRandomInt();
data: dataString,
cache: false,
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").replaceWith(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
});
}return false;
}
Try changing your callback to use .html() instead of replaceWith(): (in your original code)
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").html(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
I also recommend changing your selector to a class instead of an ID, you can do this by just adding an extra class in your HTML:
<div class="box box-warning promoReplace" id="RePromoteReplace">
and then updating the selector in your success callback:
$(".promoReplace").html(html);
Sidenote: For debugging, its usually easier to use console.log() instead of alert() (when using ajax, you usually would have the console open anyway)
Your AJAX response is getting cached by the browser due to some server setting or page header. Easiest way to disable this is to append some randomly generated parameter to your url every time you send a request.
The function getRandomInt will generate a 6 digit random number. If you want to have more/less digits, change the second argument passed to Math.pow.
function getRandomInt() {
return Math.floor(Math.random() * Math.pow(10,6));
}
//then, inside your ajax function, use:
url: "SellerPanel/post_repromote.php?rnd="+getRandomInt(),

using jquery in php post method

I am not very experienced in jquery and ajax but I need the following. After users have successfully logged in they can download pdf files from the page. The site has a collapse div from where they can choose which file to download. Everything is done in php and works ok. However, if the file is not found the collapse div is closed back. In other words the web page gets reloaded. So the user has to make a new selection newly which is inconvenient. So I would the following. If the file is not found then the div should stay collapsed and the previous value in the input field 's' on the form. I know this should be done via jquery or javascript. I have tried the following but it does not work.
//PHP
<?php
//if download is clicked
if (isset($_POST["download"])) {
$data = $_POST["s"];
//if file is found
if (fileexists($data){
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile($data);
}
//else the div should remain open
else{
echo "<script> if ($('#collapseOne').is(':hidden')) {
$('#collapseOne').show();
}</script>";
}
}
?>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form id='searchForm' method="post" action=''>
<p><label>Select Month</label></p>
<input id='s' name = 's' type='text' required><br><br>
<button type="submit" id='download' name='download' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download
</button>
<br> <br>
<button id='download1' name = 'download1' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download All
</button>
</form>
</div>
</div>
In short, you echo PHP into Javascript
<script>
$(document).ready(function(){
var hasDownload = "<?php echo $_POST['download']; ?>";
var oldInput = "<?php echo $_POST['s']; ?>";
if(hasDownload == false) {
$('#collapseOne').show();
$('input#s').val(oldInput);
}
})
</script>
When the server serves your file, those values will be present for your Javascript. Place you're jQuery at the bottom in another if statement & a doc ready block so that the dom is loaded first and echo your PHP variables into Javascript variables to perform your jQuery logic.
<?php
if (isset($_POST["download"]) && fileexists($_POST["s"]) {
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile($_POST["s"]);
}
?>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form id='searchForm' method="post" action=''>
<p><label>Select Month</label></p>
<input id='s' name = 's' type='text' required><br><br>
<button type="submit" id='download' name='download' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download
</button>
<br> <br>
<button id='download1' name = 'download1' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download All
</button>
</form>
</div>
</div>
<?php if(isset($_POST["download"]) == false && fileexists($_POST["s"] == false) : ?>
<script>
$(document).ready(function(){
var hasDownload = "<?php echo $_POST['download']; ?>";
var oldInput = "<?php echo $_POST['s']; ?>";
if(hasDownload == false) {
$('#collapseOne').show();
$('input#s').val(oldInput);
}
})
</script>
<?php endif; ?>
Try using this!
$.ajax({
url:"/path/to/your/script/",
type: "post",
data: //fetch the data which you want to pass
}).done(function(status){
//status is the data returned from the script called
});

inserting an ajax response into div

First time AJAX attempt.....
I am attempting to update a based on a selection made with a button.
I am currently just alerting the ID back, as that is all I can figure out what to do.
Is it possible to put the file my_page.php into the div with class "populated_info"?
Then when I press a different button, the page will function will run again, and populate the div with the new result. I have the my_page.php already built and running based on the ID, just can't get it to render in the correct place.
HTML:
<form name="gen_info">
<div class="body">
<div class="row">
<div class="col-md-2">
<table width="100%" class="border_yes">
<tr>
<td>
Last Name, First Name
</td>
</tr>
<?php
$result = mysqli_query($conn,"SELECT * FROM general_info");
while($row = mysqli_fetch_array($result))
{
$CURRENT_ID = $row['ID'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
?>
<tr>
<td>
<button type="button" class="btn btn-default custom" onclick="function1('<?php echo $CURRENT_ID;?>')"><?php echo $lastName.', '.$firstName; ?></button>
<!-- button that will run the function -->
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="col-md-10 populated_info"> <!-- WHERE I WOULD LIKE THE UPDATED INFORMATION -->
</div>
</div>
</div>
</form>
AJAX:
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
alert(resp); //how to get this to put the page back into the right spot?
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Your approach:
With regards to your button, I'd suggest separating the inline Javascript handler to keep your HTML and Javascript separate. I'll use a custom data attribute to store the ID here:
<button type="button" class="btn btn-default custom mybutton" data-id="<?php echo $CURRENT_ID;?>">
<?php echo $lastName . ', ' . $firstName; ?>
</button>
Then jQuery:
$('.mybutton').click(function() {
var ID = $(this).data('id');
function1(ID);
});
Your AJAX request:
You can shorten that whole function and use $.load() to get the data into your div:
function function1(ID) {
// Get the output of functions/my_page.php, passing ID as parameter, and
// replace the contents of .populated_info with it
$('.populated_info').load('functions/my_page.php', { ID: ID });
}
Doesn't look like you need a callback function here, but if you do you can put it in after the data parameter. A useful application of a callback here might be for your error handler. See here how to implement one.
An an aside, if you're just getting data, you should probably be using the GET HTTP method instead of POST.
if you successfully get the response from the server just replace alert(resp) with $('.populated_info').html(resp);
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
$('.populated_info').html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>

Categories