insert data in database dynamically - javascript

$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)

Related

Problem by Passing variable between PHP, JS and HTML

In my code I send $id to Java Script section and it returns the same value inside <p id="retid"></p> and I can't get the value as integer inside $text variable.
`while ($row = $result->fetch_assoc())
{
$id = $row["id"];
$regname = $row["reg-name"];
echo '<button class="btnicon btndel" type="button" name="answer" onclick="showDiv('.$id.')"><i class="fa fa-trash"></i> '.$regname.'</button>';
}
} else {
//header("Location: login.php?Msg=wrongPass"); }
}
?>
</div>
<div id="DelMessageDiv" style="display:none;" class="answer_list" >
<form action="_modify.php" method="get">
<div id="alerts">
<?php
$text = '<p id="retid"></p>';
echo $text.'-+-'.strip_tags($text,'<p>').'
Are you sure for delete?
<input name="id" type="hidden" value="'.strip_tags($text).'" />
<button class="btnicon btndel" type="submit" name="operation" value="0+regDelete">Yes Delete</button>
';
?>
</div>
</form>
</div>
</div>
<?php include '_footer.php'; ?>
<script src="js/extention/choices.js"></script>
<script>
const choices = new Choices('[data-trigger]',
{
searchEnabled: false
});
function showDiv(x) {
document.getElementById('DelMessageDiv').style.display = "block";
document.getElementById('retid').innerHTML = x;
}
</script>`
Thanks for all helps.

show and hide element in jquery with ajax

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
});

How to pass the id from url in php function without refreshing the page?

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();
}
});
})
})

How to submit a form using AJAX?

I am trying to submit a form using ajax. However, it is not showing the message that the code is wrong. I push errors the same way on the entire website so that part works.
This is my code:
<script type="text/javascript" src="jquery.js"></script>
<div id="showerrors"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#showerrors').load('errors2.php')
}, 1000);
});
</script>
<form id="formoid" method="post" action="data/newpass.php">
<div class="row2">
<input type="email" class="form-control2" placeholder="email adres" aria-describedby="basic-addon1" name="email" required>
</div>
<div class="row2">
<input type="text" class="form-control2 pull-left" placeholder="Enter code" aria-describedby="basic-addon1" name="captcha" style="width: 70%;" required>
<div class="capbg1">
<input type="text" class="disable1b pull-right" value="<?php echo $capcode3;?>" name="captcha" style="width: 29%;" disabled>
</div>
</div>
<div class="row2"></div>
<div class="row2">
<button type="submit" class="w3-black pull-left" name="req_new_pw">Request new password</button>
</div>
</form>
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : { email: $('#email').val(), captcha: $('#captcha').val() },
});
});
</script>
// newpass.php - action in the form
<?php
error_reporting(E_ALL);
session_start();
ob_start();
$db = mysqli_connect(***);
if (isset($_POST['req_new_pw']))
{
$captcha = mysqli_real_escape_string($db, $_POST['captcha']);
$email = mysqli_real_escape_string($db, $_POST['email']);
if(isset($_SESSION['capcode3']))
{
if($_SESSION['capcode3'] != $captcha)
{
array_push($errors, "- Code is incorrect.");
}
}
}
?>
//errors.php
<?php if (count($errors) > 0) : ?>
<div class="isa_error">
<i class="fa fa-times-circle"></i>
<b>Oops..</b><br>
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
//errors2.php - display errors above form
<?php
include('errors.php');
if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</div>
</h3>
</div>
<?php endif ?>
When i submit the form, nothing happens.
What am i doing wrong?
You don't send $_POST['req_new_pw'] and you are asking if it's set.
You can use serialize() to send all form element by post:
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : $('#formoid').serialize(),
});
});
</script>
Make sure you are setting $_SESSION['capcode3'] either.
This works like a charm:
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
});

How to show check box text if it is not next to check box using jQuery

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>

Categories