radio button update from javascript to mysql - javascript

I am working on a widget in the zend framework and i cannot get the radio button value to update the database. Could someone help. Maybe someone sees something i dont.
thanks in advance.
Here is a sample of the radio html:
<div class="vote_block">
<form class="data_form">
<ul class="input_radio_group">
<li>
<input id="mediaRating1" class="radioBtnClass" type="radio" title="Poor" value=".1" name="rating">
<label class="label_radio">Poor</label>
<div class="clear"></div>
</li>
</ul>
<button id="rateVoteButton" class="button"><span><?php echo $this->translator('send_button'); ?></span></button>
</form>
I only posted one radio button so you can get an idea of what i have.
Here is the Javascript on the page:
<script type="text/javascript">
$(document).ready(function() {
$('#rateVoteButton').click(function() {
var rating = Array();
$(this).parents('.rating_block').find('li input').each(function() {
if ($(this).attr('checked') == true) {
rating.push($(this).attr('value'));
});
if (rating.length > 0) {
var data = $.toJSON({
'set_id': '<?php echo $this->set->set_id; ?>',
'rating': '<?php # echo $this->rating; ?>'
});
}
}
});
});
Now the widget page that acts like the controller:
protected function _prepareShow()
{
$setId = $this->_request->getParam('set_id');
$rating = $this->_request->getParam('rating');
$conn = XXX_Db_Connection::factory()->getSlaveConnection();
$setDao = XXX_Model_Dao_Factory::getInstance()->setModule('media')->getSetDao();
$setDao->setDbConnection($conn);
$data = Zend_Json::encode(array('set_id' => $setId, 'rating' => $rating));
$this->_view->assign('rating', $rating);
$this->_view->assign('data', $data);
}
protected function _prepareResult()
{
$setId = $this->_request->getParam('set_id');
$rating = $this->_request->getParam('rating');
$conn = XXX_Db_Connection::factory()->getMasterConnection();
$setDao = XXX_Model_Dao_Factory::getInstance()->setModule('media')->getSetDao();
$setDao->setDbConnection($conn);
$setDao->increaseRating($rating);
$data = Zend_Json::encode(array('set_id' => $setId, 'rating' => $rating));
$this->_view->assign('rating', $rating);
$this->_view->assign('data', $data);
}
Last but not least here is the sql statement:
public function increaseRating($rating)
{
$sql = sprintf("UPDATE " . $this->_prefix . "media_set
SET rating = rating + '%s'
WHERE set_id = '%s'",
mysql_real_escape_string($rating->rating),
mysql_real_escape_string($rating->set_id));
mysql_query($sql);
return mysql_affected_rows();
}
When a radio is selected and you hit the button i do get a ?rating=.1 after the link in the address bar but no update in database.
Any suggestions will help. Thanks again.

Related

Button from a ajax post page doesnt work when clicked [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 1 year ago.
I have a commenting project that has a button id #see_more_comments inside my .user__comments__container div that is being outputted from a getcomments-afunc.php file via jquery post when the comment is more than 4. The file code of ajax.php is:
<?php
session_start();
include_once '../dbh-inc.php';
if (isset($_SESSION['userid'])) {
$jobsid = mysqli_real_escape_string($conn, $_POST['jid']);
$output = "";
$sql = "SELECT * FROM comments AS c INNER JOIN users AS u ON c.usersId = u.usersId WHERE c.jobsId = '$jobsid' ORDER BY c.cid DESC LIMIT 4;" ;
$result = mysqli_query($conn, $sql);
$commentcount = 3;
if (mysqli_num_rows($result) > $commentcount) {
while ($row = mysqli_fetch_assoc($result)) {
$usersid = $row['usersId'];
$commenterprofilepic = $row['usersProfilePic'];
$username = $row['usersName'];
$usersusername = $row['usersUsername'];
$commentDesc = $row['commentDesc'];
$commentDate = $row['commentDate'];
$output .= '<div class="user__comments">
<img src="profilepic/'.$commenterprofilepic.'" alt="'.$username.'\'s profile picture" class="profile__thumbnail" onclick="location.href=\'profile?uid='.$usersid.'\'">
<div class="comment__bubble">
<div class="comment__box">
<p class="username" onclick="location.href=\''.$usersusername.'\'">'.$username.'</p>
<p class="comment">'.nl2br($commentDesc).'</p>
</div>
<p class="date">'.$commentDate.'</p>
</div>
</div>';
}
$output .= '<div class="see__more__comments" id="see_more_comments">See more comments..</div>';
}
echo $output;
}
else {
header("../../dashboard.php");
exit();
}
Now, when it is outputted to my index.php via a jquery post call, it is registered and can be seen at the elements tab of my browser or DOM.
It is outputted via this jquery code:
setInterval(() => {
$.post('includes/ajax-func/getcomments-afunc.php', {
jid : pageId
}, function (response) {
$('.user__comments__container').html(response);
});
}, 10000
);
However, when I am clicking so that it will add 4 more comments to my .user__comments__container index.php. It doesnt work, I tried making a console.log for it but it hasnt outputted anything, this is the code for clicking the button:
$('#see_more_comments').click(function() {
commentCount = commentCount + 4;
$('.user__comments__container').load('includes/ajax-load/seemorecomments-aload.php' , {
jobsId : pageId,
newCommentCount : commentCount
});
console.log(commentCount);
});
And this is the seemorecomments-aload.php content:
<?php
session_start();
include_once '../dbh-inc.php';
$jobsid = $_POST['jobsId'];
$newcommentcount = $_POST['newCommentCount'];
$sql = "SELECT * FROM comments AS c INNER JOIN users AS u ON c.usersId = u.usersId WHERE c.jobsId = '" . $jobsid . "' ORDER BY c.cid DESC LIMIT $newcommentcount;" ;
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$usersid = $row['usersId'];
$commenterprofilepic = $row['usersProfilePic'];
$username = $row['usersName'];
$usersusername = $row['usersUsername'];
$commentDesc = $row['commentDesc'];
$commentDate = $row['commentDate'];
echo '<div class="user__comments">
<img src="profilepic/'.$commenterprofilepic.'" alt="'.$username.'\'s profile picture" class="profile__thumbnail" onclick="location.href=\''.$usersusername.'\'">
<div class="comment__bubble">
<div class="comment__box">
<div class="username" onclick="location.href=\''.$usersusername.'\'">'.$username.'</div>
<div class="comment">'.$commentDesc.'</div>
</div>
<div class="date">'.$commentDate.'</div>
</div>
</div>';
}
Before all of this, I have all getcomments-afunc.php content without the $output, $output is replaced by echo, inside my index.php .user__comments__container and it worked just fine..
However, when I decided to add jquery to it so that I wont need to reload the wholepage, my purpose of letting the .user__coments__container reload itself worked but the button doesnt work anymore.
Any help? thank you!! :(
Change the line
$('#see_more_comments').click(function() {
To
$(document).on("click","#see_more_comments",function() {
Thanks Mr. Majid Ali and Mr. Swati,
It worked!! by using $(document).on("click","#see_more_comments",function() {
May I know why $('#name').click doesnt work sometimes??

How to autopopulate a drodown based on the selection in another dropdown in php?

I have read a few similar questions but didn't find the solution.
I am trying to fetch a dropdown based on the selection of another dropdown. The first dropdown is school names, which upon selection should fetch the users under that particular school.
There are two tables in the database. The first one has school name column named schoolname and another table called person has a column named school which is the foreign key and has first name and last name too which should be fetched upon selection.
I am refering to this tutorial (https://makitweb.com/how-to-autopopulate-dropdown-with-ajax-pdo-and-php/)
I tried the below code:
queries.php
class Queries {
public static function getSchool() {
$dbUser = "xxx";
$dbPass = "xxxx";
$dbConn = "(DESCRIPTION = (ADDRESS = (PROTOCOL=TCP)(HOST=xxxx)(PORT=1521))(CONNECT_DATA=(SID=xxxx)))";
$conn = oci_connect($dbUser, $dbPass, $dbConn);
$sql = oci_parse($conn,"SELECT a.School, a.SchoolName FROM SchoolName a WHERE a.FormDisplay = 'Y' ORDER BY a.SchoolName");
return $sql;
}
}
form.php
<?php
require_once './functions/queries.php';
$getschool = new Queries();
?>
<div class="container">
<div class="panel panel-default">
<div class="panel-body">
<div id="addroles" class="hide" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="resultRoleContent"></div>
</div>
<form class="cmxform" action ='functions/processform.php' id="Form1" method="post">
<legend> Form</legend>
<label for="addname">Please Select School</label>
<select class="form-control" name="school" id="school">
<?php
$nameslist = $getschool->getSchool();
oci_execute($nameslist, OCI_DEFAULT);
while ($row = oci_fetch_array($nameslist, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo '<option value="' . $row['SCHOOLNAME'] . '">' . $row['SCHOOLNAME']. '</option>';
}
?>
</select>
<label for="addname">Please Select Name</label>
<select class="form-control" name="names" id="names">
<?php
?>
</select>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#school').change(function(){
var schoolname = $(this).val();
$('#names').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'getUsers.php',
type: 'post',
data: {request: 1, primaryschool: schoolpropername},
dataType: 'json',
success: function(response){
var len = response.length;
for( var i = 0; i<len; i++){
var id = response[i]['primaryschool'];
var firstname = response[i]['firstName'];
var lastname = response[i]['lastName'];
$("#names").append("<option value='"+id+"'>"+firstname+"</option>");
}
}
});
});
});
</script>
getUsers.php
<?php
$dbUser = "xxxx";
$dbPass = "xxxx";
$dbConn = "(DESCRIPTION = (ADDRESS = (PROTOCOL=TCP)(HOST=xxxx)(PORT=1521))(CONNECT_DATA=(SID=xxxx)))";
$conn = oci_connect($dbUser, $dbPass, $dbConn);
$request = 0;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
if($request == 1){
$schoolname = $_POST['school'];
$sql =oci_parse($conn,"SELECT * FROM person ");
oci_bind_by_name($sql, ':primaryschool', $schoolname);
$result = oci_execute($sql);
$response = array();
foreach($result as $row){
$response[] = array(
"firstname" => $row['firstname']
);
}
echo json_encode($response);
exit;
}
In the above code I am getting the following three errors:
PHP Notice: Undefined index: school in getusers.php
2.PHP Warning: oci_bind_by_name(): ORA-01036: illegal variable name/number in getusers.php
3.PHP Warning: oci_bind_by_name(): ORA-01036: illegal variable name/number in getusers.php
Undefined error occurred because school value is not getting in the $_POST array. Print the $_post array and check in which index you are getting school value.
You haven't mentioned column name in WHERE clause in your query to fetch the details of particular school. So you are getting that warning.
Your query should be like as below.
Assuming column name as schoolname in your table.
$sql =oci_parse($conn,"SELECT * FROM person WHERE schoolname = :primaryschool");
oci_bind_by_name($sql, ':primaryschool', $schoolname);

How to pass the radio button value to other program and insert value into database using php and jquery

I have a form with multiple radio buttons. What i want to store the radio button values in database like 1 for "Yes" and 0 for "No". I am using couple of script a.php, b.php for the same, a.php will get the radio button values and pass to b.php as parameter. Then b.php insert into the database. The problem here is database field for button value always updating with 0. I tried to implement with javascript and some other php logic. But no luck. Also I have created other small script to test the radio value is printing properly which is working fine. The problem is I am not aware how to get proper value in "recommend" in b.php
I really appreciate your help.
a.php is like below:
<div id="result">
<label for="sel1">Would You recomend</label>
<div class="pull-left">
<input name='recommend' type='radio' value=1>Yes
<input name='recommend' type='radio' value=0>No
<button class="btn btn-primary btn-sm" id="submit" type="submit" value="submit">submit</button>
b.php
<?php
require_once './config.php';
$pid = intval($_POST["pid"]);
$uid = intval($_POST["uid"]);
$score = intval($_POST["score"]);
$recommend = intval($_POST["recommend"]);
$aResponse['error'] = FALSE;
$aResponse['message'] = '';
$aResponse['updated_rating'] = '';
$return_message = "";
$success = FALSE;
$sql = "INSERT INTO `tbl_product_rating` (`product_id`, `user_id`, `ratings_score`, `recommend_score`) VALUES "
. "( :pid, :uid, :score, :recommend)";
$stmt = $DB->prepare($sql);
try {
$stmt->bindValue(":pid", $pid);
$stmt->bindValue(":uid", $uid);
$stmt->bindValue(":score", $score);
$stmt->bindValue(":recommend", $recommend);
//$stmt->execute(':pid' => $pid, ':uid' => $uid, ':score' => $score, ':recommend' => $recommend));
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
$aResponse['message'] = "Your rating has been added successfully";
} else {
$aResponse['error'] = TRUE;
$aResponse['message'] = "There was a problem updating your rating. Try again later";
}
} catch (Exception $ex) {
$aResponse['error'] = TRUE;
$aResponse['message'] = $ex->getMessage();
}
if ($aResponse['error'] === FALSE) {
// now fetch the latest ratings for the product.
$sql = "SELECT count(*) as count, AVG(ratings_score) as score FROM `tbl_products_ratings` WHERE 1 AND product_id = :pid";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":pid", $pid);
$stmt->execute();
$products = $stmt->fetchAll();
if ($products[0]["count"] > 0) {
// update ratings
$aResponse['updated_rating'] = "Average rating <strong>" . round($products[0]["score"], 2) . "</strong> based on <strong>" . $products[0]["count"] . "</strong> users";
} else {
$aResponse['updated_rating'] = '<strong>Ratings: </strong>No ratings for this product';
}
} catch (Exception $ex) {
#echo $ex->getMessage();
}
}
echo json_encode($aResponse);
?>
Jquery which I am using in a.php to send radio button value to b.php:
<script>
$document.ready(function(){
$('input[type="radio"]').click(function(){
var recommend = $(this).val();
$.ajax({
url:"b.php",
method:"POST",
data:{recommend:recommend},
// data:{recommend:$('#recommend').val($("[type='radio'] :checked").val())},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
jquery to fetch pid,uid,score..
<script>
$(document).on('click', '#submit', function() {
<?php
if (!isset($USER_ID)) {
?>
alert("You need to have a account to rate?");
return false;
<?php } else { ?>
var score = $("#score").val();
if (score.length > 0) {
$("#rating_zone").html('processing...');
$.post("update_ratings.php", {
pid: "<?php echo $_GET["pid"]; ?>",
uid: "<?php echo $USER_ID; ?>",
score: score
}, function(data) {
if (!data.error) {
// success message
$("#avg_ratings").html(data.updated_rating);
$("#rating_zone").html(data.message).show();
} else {
// failure message
$("#rating_zone").html(data.message).show();
}
}, 'json'
);
} else {
alert("select the ratings.");
}
<?php } ?>
});
</script>
I can insert the value 1 if "YES" for radio button with the mentioned jquery but it's inserting 0 for other fields like product_id..etc.I want just one entry to be inserted in db with proper value of radio button along with other fields.I have provided the full code for insert (b.php) with ajax which passing value to b.php from a.php. Kindly suggest.
I want output in mysql like below:
ratings_id product_id user_id ratings_score recommend_score
1 17637 1 4 0
2 17638 2 2 1
How it's happening now:
ratings_id product_id user_id ratings_score recommend_score
3 0 0 0 1
6 17639 2 4 0
In your ajax that fires once a user clicks on a radio-button you are not sending the other values needed for insert (pid, uid, score). I suppose they are included in the half-shown form.
Assuming you have those inputs in your form
<input name="pid" id="pid">
<input name="uid" id="uid">
<input name="score" id="score">
EDIT: since you've now shown more code I updated the code below (to match how you send pid & uid in the normal form-submit).
you can add them to the data object with something like this:
data:{
recommend:recommend,
pid: "<?php echo $_GET["pid"]; ?>",
uid: "<?php echo $USER_ID; ?>",
score: $('#score').val(),
},
Also change the double-ids of #newsletter as the others have suggested.
Change id to class attribute.
<script type="text/javascript">
$(document).ready(function() {
$("input[type=radio]").click(function () {
var recommend = $(this).val();
console.log(recommend);
$.ajax({
url:"b.php",
method:"POST",
data:{
recommend:recommend
},
success: function(data){
//your code here
},
error: function (error) {
console.log(error);
}
});
});
});
</script>
<input name="recommend" class='newsletter' type='radio' value=1>Yes
<input name="recommend" class='newsletter' type='radio' value=0>No
Sample HTML:
<input type="radio" name="color" id="rdoColor" value="green" />Green<br />
<input type="radio" name="color" id="rdoColor" value="Blue" />Blue<br />
Sample JQuery Code:
$(document).on("click", "input[id=rdoColor]", function(){
$.post(serverPath+"/colorHandler.php", {action: "saveColor", color: $(this).val()}, function(data){
var response = $.parseJSON(data);
// use this response as u need
});
});
Sample PHP (colorHandler.php):
$jsonStr = "";
define('DB_SERVER', 'DBserver:port');
define('DB_NAME', 'DBName');
define('DB_USER', 'dbUser');
define('DB_PASS', 'dbPass');
try {
$dbCon = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS);
$dbCon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO colorTable (colorName) VALUES (?)";
$stmt= $dbCon->prepare($sql);
$stmt->execute(array($_POST["color"]));
if( $dbCon->lastInsertId() ){
$jsonStr = '{
"status":"Success",
"Message":"Color Saved"
}';
echo $jsonStr;
}else{
$jsonStr = '{
"status":"Failure",
"Message":"Color was not Saved"
}';
echo $jsonStr;
}
}catch(PDOException $e){
$jsonStr = '{
"status":"Failure",
"Message":"Database server not found!"
}';
echo $jsonStr;
}

how to call function if fetched data from database is != "Detained"

I fetched the data from my database and echoed it. Once I go to a prisoner's profile and his status is not = detained, the button 'Add Visitor' should be automatically disabled.
Where should I put my disable() function for it to be called?
Here's my script
<script language = "javascript" type = 'text/javascript'>
function disable(){
if(document.getElementById('prisonerstatus').value == "Detained"){
document.getElementById("visitorbtn").disabled= false;}
else{
document.getElementById("visitorbtn").disabled= true;
}
};
</script>
PHP
<?php
include "connect.php";
$idd =$_GET['id'];
$result = $connect->query("SELECT * FROM prisoner
INNER JOIN offensedata ON prisoner.prisoner_id = offensedata.prisoner_id
INNER JOIN arrestdata on prisoner.prisoner_id = arrestdata.prisoner_id
INNER JOIN booking ON prisoner.prisoner_id = booking.prisoner_id
WHERE prisoner.prisoner_id = $idd") or die($connect->error);
$rows1 = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows1 as $row){
$status = $row['status'];
echo "<input type = 'hidden' value = '$status' id = 'prisonerstatus'/>";
echo "<div class='col-lg-3'>Status: $status </div>";
}
Here's my button
<input type = "button" class="call_modal" style="cursor:pointer;margin-top:1%;" value = "Add Visitor" id = 'visitorbtn'>
Please excuse my code. This is for my school project only, these codes are what have been taught to us. I will study on how to avoid SQL injections and apply it soon. Thank you in advance :)

Remove item from session onClick

I'm trying to remove an item from a sort of shopping cart. The items are saved to a session when they are "saved to the shopping cart".
But now I would like to be able to remove certain items from this "shopping cart". Because I got the script from here (stackoverflow) I'm not that familiar with the code. I saw some answers on google and here that described using unset to delete the entry from the session. But I wouldn't know where to start with this one. If additional information is needed please let me know. Thanks for having a look at my question...
Here is the HTML (nothing special):
<div class="txtHint"></div>
This is my script:
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('example.com/reload.php', {productName: productName}, function(data) {
$('.txtHint').html(data);
})
});
This is my reload.php file:
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Saved Items</h4>
<?php foreach ($_SESSION['products'] as $product): ?>
<div class="echo-product"><i style="color:#F60;padding-right:20px;" class="fa fa-anchor" aria-hidden="true"></i><?php echo htmlspecialchars($product); ?></div>
<?php endforeach;?>
Updated code: As suggested by Bert Maurau (I Hope).
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if(isset($_GET['delparam'])){
unset($_SESSION['products'][$productName]);
}
if(isset($_GET['addparam'])){
$_SESSION['products'][] = $productName;
}
?>
If I use this it doesn't add any new items...
You should be able to do:
unset($_SESSION['products'][$productName]);
This wil unset the array_key and its values that matches your productName.
Edit: Code for using the unset
HTML:
$('.delete-product').click(function() {
var productName = $(this).data('product');
$.post('example.com/reload.php?delparam', {productName: productName}, function(data) {
})
});
Reload.php (after $productName)
if(isset($_GET['delparam'])){
unset($_SESSION['products'][$productName]);
}
if(isset($_GET['addparam'])){
//code for adding product
}

Categories