Load success message into a DIV - javascript

I have this rating script, when people click on any of the stars It allow people to clic again to update but I want people just to clic one time and load a message to DIV like "thanks for your vote" and clear our the stars.
current función https://co.angelesinfieles.com/profileview/rating/
<script>
// rating script
$(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var therate = $(this).attr('id');
for (var i = therate; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var therate = $(this).attr('id');
var dataRate = 'act=rate&post_id=<?php echo $id; ?>&ip=<?php echo $_COOKIE["PHPSESSID"]; ?>&rate='+therate; //
$('.rate-btn').removeClass('rate-btn-active');
for (var i = therate; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-active');
};
$.ajax({
type : "POST",
url : "<? echo $domain ?>profileview/rating/ajax.php",
data: dataRate,
success:function(){}
});
});
});
</script>
<div class="rate-ex1-cnt">
<div id="1" class="rate-btn-1 rate-btn"></div>
<div id="2" class="rate-btn-2 rate-btn"></div>
<div id="3" class="rate-btn-3 rate-btn"></div>
<div id="4" class="rate-btn-4 rate-btn"></div>
<div id="5" class="rate-btn-5 rate-btn"></div>
</div>

$.ajax({
type : "POST",
url : "<? echo $domain ?>profileview/rating/ajax.php",
data: dataRate,
success:function(data){
alert (data); // data is your return value
}
});

Related

How To Retain or keep hidden div element after page reloaded?

I have a hidden div on my page, I want to know what kind of way I can do to keep showing the div when the page is reloaded, with the following example:
This my html :
<div class="card-body">
<div class="overlay" id="kt_datatable_nodata">
<div class="overlay-wrapper rounded bg-light text-center">
<p class="font-weight-bold text-center">Pilih data untuk dibandingkan</p>
<a href='#right-modal' class='btn' data-toggle='modal'>Change Data</a>
</div>
</div>
<!--begin::Table-->
<div id="kt_datatable_fetch_display"></div>
<!--End::Table-->
</div>
This My javascript :
$('#kt_datatable').on('click','tr button', function() {
var id = $(this).data('id');
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/right-side/right-value.php',
data: {
'rowid': id
},
success: function(data) {
$('#kt_datatable_nodata').addClass('hidden');
$('#kt_datatable_fetch_display').html(data);
}
});
})
this right-value.php :
<?php
session_start();
include 'db_connect.php';
if (isset($_POST['rowid'])) {
$id = $_POST['rowid'];
$query = mysqli_query($config, "SELECT* FROM data_penilaian where id = '$id'");
$no = 1;
while ($row = mysqli_fetch_array($query)) {
?>
<form class="leftForms" method="POST">
<input type="hidden" name="id" value="<?= $row['id']; ?>">
<input type="text" name="position" value="<?= $row['position']; ?>">
</form>
<?php
}
} ?>
here what I want to do is what kind of way I can do to keep the kt_datatable_fetch_display on or after the page is reloaded. Thanks for any help.
I dont know if I understand quite what you want to do, but the only way I'm thinking you could achieve this it's to make your button to add a query param that must be your id.
Exaple:
// This goint to redirect to the new URL
$('#kt_datatable').on('click','tr button', function() {
var id = $(this).data('id');
var yourSiteURL = "http://localhost";
window.location.href = `yourSiteURL/${id}`;
});
/*
When DOM loads read query params and make your ajax req
So, no matter page reloads, always goint to make the ajax req and fill your div
*/
$(document).ready(function(){
var searchParams = new URLSearchParams(window.location.href);
var id = searchParams.get("id");
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/right-side/right-value.php',
data: {
'rowid': id
},
success: function(data) {
$('#kt_datatable_nodata').addClass('hidden');
$('#kt_datatable_fetch_display').html(data);
}
});
})

Function is not defined when call Js function in PHP Laravel

I'm working on a Laravel project. In my blade view, I have a Javascript function like this:
<script type="text/javascript">
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
Then, I call this function in the body tag and pass two php parameters to it:
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>
But when I run this, I got a error: "Uncaught ReferenceError: autoFill is not defined".
Here is my full code in blade view if you want:
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">
Activiti Form
</div>
#if(isset($formDataResult) && isset($dropdownValue))
<div class="links">
<form action="{{ url('handle-form') }}" method="POST">
<!--Loop form data and call components to render form-->
#foreach($formDataResult as $formDataValue)
<div class="links">
#if($formDataValue['type'] == 'select')
#if(array_key_exists('description',$formDataValue))
<?php
$dropDown = $formDataValue['name']
?>
#component('components/InputSelect',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name'],
'enumData' => $dropdownValue
])
#endcomponent
#else
<?php
$emptyDropDown = $formDataValue['name'];
?>
#component('components/EmptyInputSelect',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name']
])
#endcomponent
#endif
#elseif($formDataValue['type'] == 'text')
#component('components/InputText',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name'],
'type'=>$formDataValue['type']
])
#endcomponent
#endif
<br>
</div>
#endforeach
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>
<!--Hidden input to store task id-->
#component('components/HiddenInput',[
'id' => $taskId
])
#endcomponent
<div>
<input type="reset" value="Reset Form">
<button type="submit">Complete Task</button>
</div>
</form>
</div>
<!--If don't have form data, show error alert-->
#else
<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<strong>Notice!</strong> There are no tasks at this moment!
</div>
#endif
</div>
</div>
</body>
<script type="text/javascript">
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
How I can fix this?
Thank you very much!
You are trying to call the function before you define it. Put the <script type="text/javascript">...</script> defining the function before your <script> autoFill('$dropDown', '$emptyDropDown'); </script> which tries to call it.
You can read js value to using PHP. But you can print js value to HTML screen.
You have a <span> or <div> tag with class or id attribute then you can place your value inside that.
Here is your js functionality
<script>
// whatever value you need in your js from PHP. you need to below code.
let dropdown = <?php echo $dropDown; ?>
let emptyDropdown = <?php echo $emptyDropDown; ?>
// now pass your js variables here.
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
let $this = $(this);
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>

product filtering for brand as checkbox and price slider using php,mysql and ajax

if u select on brand that will be checked and also check the price that also filtered but when i selected another brand that will not be selected please suggest me..
i think it will not select multiple array brands.i will used php,jquery and mysqli.
<div class="widget-header">
<h4 class="widget-title">Brand</h4>
</div>
<div class="accordion-group" id="brandname">
<?php
$all_brand=$con->query("SELECT distinct brand FROM `mc_products_tbl` WHERE cat_id = '$_GET[cat_id]' GROUP BY brand");?>
<?php foreach ($all_brand as $key => $new_brand) :
if(isset($_GET['brand'])) :
if(in_array(data_clean($new_brand['brand']),$_GET['brand'])) :
$check='checked="checked"';
else : $check="";
endif;
endif;
?>
<input type="checkbox" value="<?=data_clean($new_brand['brand']);?>" <?=#$check?> name="brand[]" class="sort_rang brand" onchange="filterProducts()"><?=ucfirst($new_brand['brand']); ?>
<?php endforeach; ?>
</div>
<div class="widget-header">
<h4 class="widget-title">Price Range</h4>
</div>
<div class="filter-panel">
<p><input type="hidden" id="price_range" onchange="filterProducts()" value="50,50000"/>
</p>
</div>
function filterProducts() {
var cat_id = $("#cat_id").val();
var subcat_id = $("#subcat_id").val();
var brand = check_box_values('brand');
var price_range = $("#price_range").val();
alert(cat_id);
alert(subcat_id);
alert(brand);
alert(price_range);
var dataString='price_range='+price_range+'&cat_id='+cat_id+'&subcat_id='+subcat_id+'&brand='+brand;
alert(dataString);
$.ajax({
type: "POST",
url: "left_listing_ajax_filter.php",
data: dataString,
cache: false,
// beforeSend: function () {
//$('.container').css("opacity", ".5");
//},
success: function (data) {
if (data != "") {
$('#results').html(data);
//$('.container').css("opacity", "");
}
}
});
function check_box_values(check_box_class){
var values = new Array();
$("."+check_box_class+":checked").each(function() {
values.push($(this).val());
});
return values;
}
$('.sort_rang').change(function(){
$("#search_form").submit();
return false;
});
}
please suggest me....if you select second time that will not move to left_listing_ajax_filter file..please suggest me...i am trying to resolve this problem please help me..

Loading contents with ajax and appending

What I am doing is loading contents from a php file in json format
products.php
<?php
$stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10");
$stmt->execute();
$products = $stmt->get_result();
$product_array = array();
while($product = $products->fetch_assoc()){
$product_array[] = $product;
}
echo json_encode($product_array);
?>
home.php
<style>
.product
{
width: 100px;
height:100px;
margin-bottom: 10px;
}
</style>
<div class="product_area">
<div class="product">
<h3>Product 1</h3>
<p>Price: $10</p>
</div>
<div class="product">
<h3>Product 2</h3>
<p>Price: $10</p>
</div>
<div class="product">
<h3>Product 3</h3>
<p>Price: $10</p>
</div>
<div class="product">
<h3>Product 4</h3>
<p>Price: $10</p>
</div>
</div>
I have already 4 products in a product_area now I want to fetch the other products as soon as the document is loaded so I used ajax
$(document).ready(function()
{
$.ajax(
{
url: 'product.php',
dataType: 'JSON',
success: function(data)
{
//This is where I am stucked. How do I append the new data beneath the current data in `product_area`.
for(i=0; i<=data.length; i++)
{
}
window.History.pushState({urlPath:'&view=products'},"",'&view=product');
}
});
});
Also I am trying to push the state in the url with this window.History.pushState({urlPath:'&view=products'},"",'&view=product') but it doesn't push it means it doesn't show the url appended.
How it should be
Before pushState url index.php?store=abc
After pushState url index.php?store=abc&view=products
Can some one help me with this?
Try to do this:
products.php
<?php
header('Content-Type: application/json');
$stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10");
$stmt->execute();
$products = $stmt->get_result();
$product_array = array();
while($product = $products->fetch_assoc()){
$product_array[] = $product;
}
echo json_encode($product_array);
?>
javascript - just clone the first div and then replicates
$(document).ready(function() {
$.ajax({
url: 'product.php',
dataType: 'JSON',
success: function(data) {
//This is where I am stucked. How do I append the new data beneath the current data in `product_area`.
data.forEach(function (product) {
var newProductBox = $('.product:first').clone();
newProductBox.find('h3').text(product.nameInYourColumnDb);
newProductBox.find('p').text('Price: $' + product.priceInYourColumnDb);
$('.product_area').append(newProductBox);
});
window.History.pushState({urlPath:'&view=products'},"",'&view=product');
}
});
});
About the "pushState" take a look at this examples:
https://developer.mozilla.org/en-US/docs/Web/API/History_API#Example_of_pushState()_method
Parse Json Data and Append It To product_area class
<script>
$(document).ready(function()
{
$.ajax(
{
url: 'product.php',
dataType: 'JSON',
success: function(data)
{
var json = $.parseJSON(data);
for(i=0; i<=json .length; i++)
{
$('.product_area').append('<div class="product"><h3>Product Name: '+json[i].product_name+'</h3><p> Price :'+json[i].product_price+'</p></div>');
}
window.History.pushState({urlPath:'&view=products'},"",'&view=product');
}
});
});
</script>

How to refresh a div on link or button click?

I am working on a small social network project where I am using post comment functionality. What I am stuck with is as soon as the use deletes a comment, the comment count should decrease automatically. This can onyl be done using refresh functionality, but the current code does not seem to be working. It deletes the comment but does not display the decreased count. So whenever a comment is deleted, it should show up the decreased count. Here is my code so far.
<div style="border:2px solid red;" class="comment_ui" id="view<?php echo $id; ?>">
<div>
View all <?php echo $comment_count; ?> comments
</div>
<div class="comment_ui">
<div class="comment_text">
<div class="comment_actual_text">
<?php echo $FirstName.' '.$LastName;?>
<a id="<?php echo $c_id;?>" class = "delete_comment" style="position: relative; float:right; right: 20px; text-decoration: none;" href="#">x</a><p/>
<div id="sssss"><?php echo $comment; ?></div>
</div>
</div>
</div>
JQuery
<script type="text/javascript">
$(function(){
$(".delete_comment").click(function(){
var element = $(this);
var comment = element.attr("id");
var commentRow = $(this).closest('.comment_text');
var info = "comment="+comment;
$.ajax({
type: "POST",
url: "delete_comment.php",
data: info,
success: function(){
commentRow.fadeOut('slow', function() {$(this).remove();});
$('.comment_ui').load(url + ' .comment_ui');
}
});
return false;
});
});
</script>
Try Below code
<script type="text/javascript">
$(function(){
$(".delete_comment").click(function(){
var element = $(this);
var comment = element.attr("id");
var commentRow = $(this).closest('.comment_text');
var info = "comment="+comment;
$.ajax({
type: "POST",
url: "delete_comment.php",
data: info,
success: function(){
commentRow.fadeOut('slow', function() {$(this).remove();});
$.post( url + ' .comment_ui', function( data ) {
$( ".comment_ui" ).html( data );
})
},
error: function(){
alert("somthing is wrong")
},
});
});
});
</script>
You cant use .load() like that. The variable url isn't defined and you can't add a jquery selector to the url.
If you cant .load() the exact html you need you must .get() it instead, .find() the part you need in the response and insert it with .html()
EDIT: Added code suggestion
<div style="border:2px solid red;" class="comment_ui" id="view<?php echo $id; ?>">
<div>
<a href="#" class="view_comments" id="<?php echo $id; ?>">View all
<span id="totalCommentsCount"><?php echo $comment_count; ?></span> comments</a>
</div>
<div class="comment_ui">
<div class="comment_text">
<div class="comment_actual_text">
<?php echo $FirstName.' '.$LastName;?>
<a id="<?php echo $c_id;?>" class = "delete_comment" style="position: relative; float:right; right: 20px; text-decoration: none;" href="#">x</a><p/>
<div id="sssss"><?php echo $comment; ?></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$(".delete_comment").click(onDeleteComment);
});
function onDeleteComment() {
var commentElement = this;
var commentId = commentElement.id;
//Start the fade-out even before the delete is committed to create a fast user experience
var commentRow = $(commentElement).closest('.comment_text');
commentRow.fadeOut('slow', function() { commentRow.remove(); });
//Post the delete to the server
$.ajax({
type: "POST",
url: "delete_comment.php",
data: { comment: commentId },
success: function (deleteResponse) {
//USE ONE OF THE ALT. BELOW:
//Alt.1: delete_comment.php returns a json like { count: 12 } which describes number of comments left
$('#totalCount').text(deleteResponse.count);
//Alt.2: you don't care to reload number of comments from server and just decrease by one.
var totalCountSpan = $('#totalCount');
totalCountSpan.text(parseInt(totalCountSpan.text()) - 1);
//Alt.3: get number of comments left on server by reloading the "view" an extra time. Really not optimal!
var viewId = $('.comment_ui').attr('id');
$.get( "get_view.php?id=" + viewId, function( data ) {
var newCount = $(data).find('#totalCount').text();
$( "#totalCount" ).text( newCount );
});
},
error: function(){
//Possibly restore the comment here if this happens often?
alert("somthing is wrong")
},
});
}
</script>

Categories

Resources