I create survey poll in wordpress plugin to display questions i use ajax to display it
this is my html code
<div id="my_poll">
<button class="start" id="start"><b><?php _e('Start poll questions'); ?></b></button>
<div id="poll" class="container mt-sm-5 my-1">
<form>
<?php
if ($ques->have_posts()) {
while ($ques->have_posts()) {
$ques->the_post();
global $post;
$ID = $post->ID;
$option = get_post_meta($ID, "op1", true);
$nonce = wp_create_nonce("my_user_vote_nonce");
$link = admin_url('admin-ajax.php?action=my_user_vote&post_id=' . $ID . '&nonce=' . $nonce);
$ques_id = 'Q-' . $ID;
?>
<div id="<?php echo $ques_id ?>" class="questions">
<div class="question ml-sm-5 pl-sm-5 pt-2">
<h3><b><?php _e('Poll Survey'); ?></b></h3>
<div class="py-2 h5"><b class="msg"><?php the_title() ?></b></div>
<div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3" id="options">
<label class="options"><?php _e($option['op1']['op1']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op1']['op1']) ?>"> <span class="checkmark"></span> </label>
<label class="options"><?php _e($option['op2']['op2']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op2']['op2']) ?>"> <span class="checkmark"></span> </label>
<label class="options"><?php _e($option['op3']['op3']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op3']['op3']) ?>"> <span class="checkmark"></span> </label>
</div>
<div class="d-flex align-items-center pt-3">
<div class="ml-auto mr-sm-5">
<button class="btn btn-success">
<?php
echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $ID . '" href="' . $link . '">submit</a>';
?>
</button>
</div>
</div>
</div>
</div>
<?php
}
}
?>
</form>
</div>
</div>
and this is my ajax to show and hide elements
jQuery(document).ready(function() {
jQuery("#poll").hide();
var count = 0;
jQuery(".start").click(function(e) {
jQuery("#poll").show();
jQuery(".start").hide();
});
jQuery(".user_vote").click(function(e) {
e.preventDefault();
option = jQuery('input[name="framework"]:checked').val();
post_id = jQuery(this).attr("data-post_id");
nonce = jQuery(this).attr("data-nonce");
var idArr = [];
jQuery(".questions").each(function() {
idArr.push(jQuery(this).attr("id"));
});
jQuery.ajax({
type: "post",
dataType: "json",
url: myAjax.ajaxurl,
data: {
action: "my_user_vote",
post_id: post_id,
nonce: nonce,
option: option,
},
success: function(response) {
if (response.type == "success") {
count++;
if (count < idArr.length) {
jQuery(".questions").hide();
jQuery("#" + idArr[count]).show();
} else {
jQuery("#my_poll").hide();
alert('Thank you for your time.')
}
} else {
alert("Your vote could not be added");
}
},
});
});
});
in this jquery ajax whene i click start button i display all questoins divs.
but i want display the first question div.
Does anyone have any solutions?
Change the on click event function like below;
jQuery(".start").click(function(e) {
jQuery(".start").hide();
jQuery("#poll:first").show(); // id selector!
});
Better way, wirte "poll" word into the class attribute, dont use same id more than one time. If you change the id and class of the elements, your code must be like this;
jQuery(".start").click(function(e) {
jQuery(".start").hide();
jQuery(".poll:first").show(); // class selector
});
Also, you can use $ character instead of Jquery;
jQuery("div") EQUAL $("div")
Another way to find first element;
$(".start").click(function(e) {
$(".start").hide();
$(".poll").eq(0).show(); // class selector
});
Related
I have a div which contains a button(Book it).When I press the button I want to add to the current url the id of the item I clicked on.Then get that id to pop up a box with clicked item data without refreshing the page, because I need to pop up in the current page.
Here it gets the treatments Id
<div class="treatments">
<ul>
<?php
global $treatments;
foreach($treatments as $treatment){
echo ' <li>'.$treatment['name'].'</li>';
};
?>
</ul>
<div class="line"></div>
</div>
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" id="hidden_input" name="id_item" value="'.$item['id'].'">
<a class="bookBtn" id="btn"><button>BOOK IT</button></a> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
</div>
Pop up box
<div class="bookDetails">
<div class="details">
<?php
global $iController;
$itemm;
if(isset($_GET['id_item'])){
$itemm = $iController->getItemById($_GET['id_item']);
}
echo'
<h1>Book your treatment</h1>
<p>Treatment Name : '.$itemm['name'].'</p>
<p>Treatment Time :'.$itemm['time'].' </p>
<p>Treatment Price : '.$itemm['price'].'</p>
';
?>
<form action="" method="POST">
<label for="date">Choose your date:</label>
<input type="date" for="date" name="date"><br>
<input type="submit" value="Cancel" id="cancel">
<input type="submit" value="Book Now">
</form>
Jquery code
$(".bookBtn").click(function(){
$(".bookDetails").show();
})
getItemById function
public function getItemById($id){
$sql="SELECT * FROM treatments_item WHERE id=$id";
echo $id;
$items = mysqli_query($this->connection,$sql);
$returnArray = array();
if($items){
while($row = mysqli_fetch_assoc($items)){
array_push($returnArray, $row);
}
return $returnArray[0];
}else{
echo'It doesn't work';
}
}
You can use ajax or mix php and javascript like this:
<script>
$(document).ready(function() {
<?php session_start(); ?>//Remove session_start
if (!<?php $_GET(['id'])?'true':'false'; ?>) {
alert something
} else {
something ..
}
});
</script>
hope this was helpful. :)
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" class="id_item" value="'.$item['id'].'">
<div class="bookBtn"><button>BOOK IT</button></div> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
Note: Never use id same name in one Page i.e., id="hidden_input" // In for loop same name will be generated. It will create bug down the line. Same goes for Input name, instead use class.
$(document).ready(function(){
$('body').on('click','.bookBtn',function(){
var treatmentID = $(this).siblings('.id_item').val();
// $(this) --> it will read the data of the property you have clicked
// .siblings --> adjacent class with name ('.id_item')
$.ajax({
url: 'treatments.php',
type: "get", //send it through get method
data: {
treatmentID: treatmentID
},
success: function(response) {
//operation to show the data in div
//e.g., $('#divId').html(data.name);
$(".bookDetails").show();
}
});
})
})
I am executing an ajax script which loads a view into a div. The view populates some dropdowns from the database. When this view is loaded into the div, chosen-select doesnt work.
If I try to call
$('.chosen-select').chosen('destroy');
$('.chosen-select').chosen();
inside success block of ajax call, it says:
Uncaught TypeError: $(...).chosen is not a function
If we call these functions outside ajax call function block, it has no effect.
Below is my js
function addnewrow()
{
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>" + "mycontroller/myfunction",
success: function(res){
if(res) {
var list = document.querySelectorAll(".newrow");
var last = list[list.length - 1];
last.innerHTML=res;
//$('.chosen-select').trigger('chosen:updated');
var newDiv = document.createElement('div');
newDiv.setAttribute("class", "newrow");
newDiv.setAttribute("id", "newrow");
newDiv.innerHTML = "";
last.insertAdjacentElement("afterend", newDiv);
}
},
error: function(res, status, error) {
alert('Please Refresh the page and Try Again.');
}
});
}
Below is my controller function which prepares the page with dropsowns and pass the result to js
public function myfunction()
{
$data["data1"]=$this->main_model->getdata1();
$data["data2"]=$this->main_model->getdata2();
$data["data3"]=$this->main_model->getdata3();
$this->load->view('myviews/datapage',$data);
}
Below is the target code for reference which needs to be passed to js and then is placed inside newrow
<div class="row">
<br>
<div class="col-sm-2">
</div>
<div class="col-sm-2">
<label>DATALIST 1</label>
<?php
if(isset($data1) && !empty($data1))
{
echo '<select class="chosen-select form-control" id="datalist1" name="datalist1[]" data-placeholder="Choose an data item">
<option value=""> </option>';
foreach($data1 as $s)
{
echo '<option value="'.$s->sno.'">'.$s->dataname.'</option>';
}
echo '</select>';
}
?>
</div>
<div class="col-sm-2" id="itemdetails">
<!--
ON SELECTING AN ITEM IN DATALIST1, FETCH SOME DATA FROM DATABASE ABOUT THAT ITEM AND SHOW IT HERE
-->
</div>
<div class="col-sm-1"></div>
<div class="col-sm-2">
<label>DATALIST 2</label>
<?php
if(isset($data2) && !empty($data2))
{
echo '<select class="chosen-select form-control" id="datalist2" name="datalist2[]" data-placeholder="Choose a Data">
<option value=""> </option>';
foreach($data2 as $s)
{
echo '<option value="'.$s->sno.'">'.$s->dataname.'</option>';
}
echo '</select>';
}
?>
</div>
<div class="col-sm-2">
<label>DATALIST 3</label>
<?php
if(isset($data2) && !empty($data2))
{
echo '<select class="chosen-select form-control" id="datalist3" name="datalist3[]" data-placeholder="Choose a Data">
<option value=""> </option>';
foreach($data2 as $s)
{
echo '<option value="'.$s->sno.'">'.$s->dataname.'</option>';
}
echo '</select>';
}
?>
</div>
<div class="col col-sm-1">
<br>
<div class="btn btn-primary btn-block mt-4" name="removerows" onclick="removethisrow(this);"><i class="fa fa-minus" aria-hidden="true"></i></div>
</div>
</div>
UPDATE
I tried using 3.3.1 version of JQuery, 1.8.7 version of chosen, 4.0.6-rc.0 version of select2 in place of chosen and I face the same issues everywhere.
Try adding setTimeOut() to the chosen initialisation as follows.
function addnewrow()
{
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>" + "mycontroller/myfunction",
success: function(res){
if(res) {
var list = document.querySelectorAll(".newrow");
var last = list[list.length - 1];
last.innerHTML=res;
setTimeOut(function() {
$('.chosen-select').trigger('chosen:updated');
}, 1000);
var newDiv = document.createElement('div');
newDiv.setAttribute("class", "newrow");
newDiv.setAttribute("id", "newrow");
newDiv.innerHTML = "";
last.insertAdjacentElement("afterend", newDiv);
}
},
error: function(res, status, error) {
alert('Please Refresh the page and Try Again.');
}
});
}
$query = "select * from comments t1 inner join users t2 on t1.user_id = t2.UserId where usercomplain_id='$id'";
$run =mysqli_query($mysqli,$query);
while($row=mysqli_fetch_array($run))
{
$commentid = $row['comment_id'];
$comment = $row['comment'];
$username = $row['UserName'];
$userid1 = $row['UserId'];
$date = $row['CDate'];
$ageDate = time_elapsed_string($date);
?>
<div class="jumbotron" style="border:3px solid #2FAB9B; background-color:#68C8C6;">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<?php echo $ageDate; ?>
</div>
</div>
<br>
<label>Comment by <?php echo $username; ?></span></label><br>
<a class="reply" data-role="<?php echo $commentid; ?>">Reply</a>
<br>
<br>
<div style="width:63%; display:none;" class="replyForm" data-role="<?php echo $commentid; ?>">
<form method="post">
<textarea cols="100" rows="4"></textarea><br>
<br>
<input type="submit" name="reply" class="btn btn-primary" style="float:right" value="reply">
</form>
</div>
</div>
<script>
$(document).ready(function(){
$(".reply").click(function(){
var current = $(this).attr("data-role");
$('.replyForm[data-role="'+$(this).attr("data-role")+'"]').fadeIn();
});
});
</script>
<?php
if(isset($_POST['reply']))
{
echo "<script>alert('$commentid')</script>";
}
?>
<?php } ?>
it is a simple comment system with each comment there is a reply link on click on reply link a textbox is shown . I want to enter comment reply to database table therefore I want to get the record of the specific comment. How to do that with PHP.
this code should do what you want, completely dinamically
<div class="jumbotron comment-container" data-pk="<?php echo $commentid; ?>">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<em class="text-muted"><?php echo $ageDate; ?></em>
</div>
<div class="col-md-12">
<label>Comment by <?php echo $username; ?></label><br/>
<button class="btn btn-primary reply">Reply</button>
</div>
</div>
</div>
And here is the JS part. In order to reduce the code printed in the while loop, the reply form is cloned each time and appended where needed.
var reply_form = $('<div class="row replyForm-container"><div class="col-md-12">'+
'<form method="post" class="reply-form">'+
'<textarea class="form-control" rows="4">Prefilled content</textarea><br>'+
'<br>'+
'<button type="submit" name="reply" class="btn btn-primary" style="float:right" >Reply</button>'+
'</form>'+
'</div></div>');
$(".reply").click(function(){
$(this).hide();
var $container = $(this).closest('.comment-container');
var pk = $container.data('pk');
var rf_clone = reply_form.clone();
rf_clone.find('form').attr('data-pk', pk).data('pk', pk);
$container.append( rf_clone.hide().fadeIn(1000) );
});
// working with dynamical elements, we need to use delegation here
$(document).on('submit', '.reply-form', function(e){
e.preventDefault();
var reply_container = $(this).closest('.replyForm-container');
var pk = $(this).data('pk');
var reply = $(this).find('textarea').val();
console.log('Insert reply "'+reply+'" for comment ID: '+pk);
$.ajax({
type: "POST",
url: 'my_php_handler.php',
async: false,
dataType: "json",
data: {action: 'add-reply', commend_id: pk, reply_text: reply},
success: function (response) {
if( response ) {
reply_container.fadeOut('slow', function(){
var btn = reply_container.closest('.comment-container').find('button.reply');
$(this).remove(); //will remove the element after fadeOut completes
btn.show();
})
}
}
});
});
Check working Fiddle (ajax disabled)
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!
I am trying to achieve checked value text should visible like shown in the image:
Without refresh or any click can anyone help me out?
This is my php dynamic from :
<div class="products-row">
<?php $tq=$conn->query("select * from os_tiffen where tiffen_status=1 order by id_tiffen ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input multiple="multiple" type="checkbox" id="<?php echo $tiffen['tiffen_image']; ?>" name="tifeen" hidden>
<label for="<?php echo $tiffen['tiffen_image'];?>"><img src="img/tiffen/<?php echo $tiffen['tiffen_image']; ?>" class="img img-responsive" /></label>
<h3 class="FoodName"><?php echo $tiffen['tiffen_name'];?></h3>
</div>
</div>
<?php } ?>
</div>
This is my script to show the text:
<script type="text/javascript" language="JavaScript">
$( document ).ready(function() {
var FoodMenu = $('input[type=checkbox]:checked').map(function(){
return $(this).next('.FoodName').text();
}).get().join("<br>");
$("#selectedfood").html(FoodMenu);
});
</script>
Out put id: <a id="selectedfood"></a></li>
You could try to get all checked options’ text on checkbox change event and append selected values to “selectedfood”. The following sample code is for your reference.
<script>
$(function () {
$(".foodmenuform [type='checkbox']").change(function () {
var FoodMenu = "";
var ischecked = $(".foodmenuform [type='checkbox']:checked").each(function () {
FoodMenu += $(this).siblings(".FoodName").text() + "<br/>";
})
$("#selectedfood").html(FoodMenu);
})
})
</script>
Its easier thank i thought:
var checkedFood = $('input[type=checkbox]:checked').map(function(){
//console.log($('input[type=checkbox]:checked').serialize());
return $(this).val();
}).get().join("<br>");
$("#selectedfood").html(checkedFood);
Form:
<div class="products-row">
<?php $tq=$conn->query("select * from os_tiffen where tiffen_status=1 order by id_tiffen ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input type="checkbox" id="<?php echo $tiffen['id_tiffen'];?>" class="Foodmenu" value="<?php echo $tiffen['tiffen_name'];?>" name="tifeen[]" hidden>
<label for="<?php echo $tiffen['id_tiffen'];?>"><img src="img/tiffen/<?php echo $tiffen['tiffen_image']; ?>" class="img img-responsive" /></label>
<h3><?php echo $tiffen['tiffen_name'];?></h3>
</div>
</div>
<?php } ?>
</div>