Jquery add class to all previous siblings - javascript

I am working on a simple rating system in WordPress.
<div id="r1" class="rate_widget"
data-post-id="<?php echo $post_id ?>"
data-user-id="<?php echo $user_id; ?>"
data-nonce="<?php echo $nonce ?>"
>
<div data-rating="1" class="ratings_stars"></div>
<div data-rating="2" class="ratings_stars"></div>
<div data-rating="3" class="ratings_stars"></div>
<div data-rating="4" class="ratings_stars"></div>
<div data-rating="5" class="ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
I have three classes
1-rating_stars = simply to show star.png
2- ratings_vote = when user hover over stars it turns into yellow
3- ratings_done = After receiving a response star turn into blue.
I want to add or remove classes based on the number I receive by Ajax.
Here is the code:
$('.ratings_stars').hover(
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
}
);
// This actually records the vote
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('data-rating'),
widget_id : $(star).parent().attr('id'),
post_id:$(star).parent().attr('data-post-id') ,
user_id:$(star).parent().attr('data-user-id') ,
nonce: $(star).parent().attr('data-nonce'),
action: 'rating_system'
};
console.log(clicked_data);
$.ajax({
type: 'POST',
data: clicked_data,
url : myAjax.ajaxurl,
success: function(INFO) {
$("div[data-rating = '" + INFO + "']").prevAll().addBack().addClass('ratings_vote');
$('.rate_widget').find('[data-rating="' + INFO + '"]').prevAll().andSelf().addClass('ratings_vote');
$('.rate_widget').find('[data-rating="' + INFO + '"]').nextAll().removeClass('ratings_vote');
}
});
});
I have tried these last lines but it doesn't work. But id I run same code in console it works perfectly. INFO is a number from 1 to 5.
$("div[data-rating = '" + INFO + "']").prevAll().addBack().addClass('ratings_vote');
$('.rate_widget').find('[data-rating="' + INFO + '"]').prevAll().andSelf().addClass('ratings_vote');
Is there any way to work around?

Related

php html div set POST variable in click

hello i want to set a $_POST value in php when someone click a div element , here's part of my code :
<?php
$looperone = 1;
$judulcountquery = "SELECT nomorsoal FROM soal";
$judulcountrun = mysqli_query($konek,$judulcountquery);
if ( $judulcountrun == FALSE ) {
die(mysqli_error());
} else {
}
$judulcount = mysqli_num_rows($judulcountrun);
$amountofrows = $judulcount;
while($looperone == 1) {
$judulherequery = "SELECT * FROM soal WHERE nomorsoal = $amountofrows";
$judulsatuqueryconnect = mysqli_query($konek,$judulherequery);
$judulsatufetch = mysqli_fetch_assoc($judulsatuqueryconnect);
if($judulsatufetch != NULL) {
$judulsatu = $judulsatufetch['judul'];
} else {
break;
}
$judulnya = $judulsatufetch['judul'];
echo "<div class=\"head-main-recenttest-result\" style=\"text- decoration:none;\">". "".$amountofrows.".".$judulnya." </div>";
$looperone++;
$amountofrows--;
}
?>
example of output from echo :
<div class="head-main-recenttest-result" style="text-decoration:none;">
Latihan 1
</div>
as you see that only will redirect people to the link without giving post data , anyone know the method ? also im new so i can't ask well
By the looks of your code, you are not sending any post variable to the bacasoal.php. If you just want to submit then this will suffice.
<form method="post" action="bacasoal.php">
<div class="head-main-recenttest-result" style="text-decoration:none;">
<input type="submit" name="button" value="Latihan 1">
</div>
</form>
Note: Your <a> tag was replaced by a an submit input
And if you want to do it via AJAX when click on the <a> then
HTML
<div class="head-main-recenttest-result" style="text-decoration:none;">
Latihan 1
</div>
AJAX
$('a').click(function(){
$.ajax({
url: "bacasoal.php",
type: "post",
success:(unction(){
alert("success");
},
error:function(){
alert("error");
}
})
});
In the first approach the page will be redirected to bacasoal.php.
In second one the page will stay(unless you make it to).

CSS and JQuery doesn't work after Ajax call

My excuses: First off all, I would like to explain that I've been searching for an answer a long time. I found so many similar questions, but none with a solution for my scenario.
The Problem: After an Ajax call, where I dinamicaly add HTML code, the code added looses its styles and action responses (on click, for example).
HTML : The HTML that is loaded with page loading. It renders the collection of the user's images correctly. I mean... the style is ok and the JS functions bind to the classes 'visualizaImagem' and 'deletaImagem' works fine.
<div class="row">
<div class="col-sm-12" id='imagens'>
<?php
if(isset($imagens)){
if(count($imagens) > 0){
foreach($imagens as $imagem){
echo "
<div class='file-box' data-path='" . $imagem['path'] . "' id='" . $imagem['nome'] . "'>
<div class='file'>
<a class='visualizaImagem' data-path='". $imagem['path'] ."'>
<div class='icon'>
<img src='../" . $imagem['path'] . "' style='height:100%'>
<a class='deletaImagem' data-path='". $imagem['path'] ."' data-divid='" . $imagem['nome'] . "'>
<i class='fa fa-trash' style='position:absolute;top:10px;left:10px;font-size:18px;'></i>
</a>
</div>
<div class='file-name'> " . $imagem['nome'] . "</div>
</a>
</div>
</div>";
}
}
}
?>
</div>
</div>
JS : When I click to the upload button (that is not part of this code), the image data is passed through "data: dados", read by "salvaImagem" in the specific controller and than appended to the page. The image is actually appended, but with no css style and no response to the functions that should have been bind to the same classes presented above.
jQuery.ajax({
type: "POST",
url: "salvaImagem",
data: dados,
dataType: "json"}).done(function(response)
{
if(response.sucesso){
toastr['success'](response.msg);
var img = "" +
"<div class='file-box' id='" + response.nome + "' data-path='" + response.path + "'>" +
" <div class='file'>" +
" <a class='visualizaImagem' data-path='"+response.path+"'>" +
" <div class='icon'>" +
" <img src='../"+response.path+"' style='height:100%'>" +
" <a class='deletaImagem' data-path='"+response.path+"' data-divid='"+response.nome+"'>" +
" <i class='fa fa-trash' style='position:absolute;top:10px;left:10px;font-size:18px;'>" +
" </a>" +
" </div>" +
" <div class='file-name'> "+response.nome+"</div>" +
" </a>" +
" </div>" +
"</div>";
$('#imagens').append(img);
}
else{
toastr['error'](response.msg);
}
});
I think I should give a little bit more about the code. Here is an example of how I bind functions to those classes. Actually as I wrote the function inside the bind, I was expecting that would't be necessary to rebind.
$('.deletaImagem').on('click', function (){
var path = $(this).data('path');
var div_id = $(this).data('divid');
jQuery.ajax({
type: "POST",
url: "deletaImagem",
data: {'path':path},
dataType: "json"}).done(function(response)
{
if(response.sucesso){
toastr['success'](response.msg);
$('#'+div_id).remove();
}
else{
toastr['error'](response.msg);
}
});
return false;
});
Trying to use some of the tips friends gave me here, I tried the following, but no success either.
jQuery.ajax({
type: "POST",
url: "salvaImagem",
data: dados,
dataType: "json"}).done(function(response)
{
if(response.sucesso){
toastr['success'](response.msg);
var img = <HTML original code here>
$(img).appendTo('#imagens').find('.deletaImagem').on('click', deletaImagem);
$('.visualizaImagem').on('click', visualizaImagem);
}
else{
toastr['error'](response.msg);
}
});
function deletaImagem(){
var path = $(this).data('path');
var div_id = $(this).data('divid');
jQuery.ajax({
type: "POST",
url: "deletaImagem",
data: {'path':path},
dataType: "json"}).done(function(response)
{
if(response.sucesso){
$('#'+div_id).remove();
toastr['success'](response.msg);
}
else{
toastr['error'](response.msg);
}
});
return false;
}
Since I assume you are binding events (click etc... ) on document.ready, any new items added later will not have those events.
After adding the the new items, just add the events again.
$('#something').append("<div class='somethingWithClicklistener'>a</div>"); // It won't have the event, you have to add it
$('.somethingWithClicklistener').click(function(){ etc..
Though that approach might double the event handlers on pre-existing classes but you get the point
As for styles it shouldn't happen unless you use jquery animation etc...
if you get an ajax response as html, you have to write your javascript code relatively to your root element in witch you input your html (received from ajax).
1.
<div class="some-root-div">
// the place where you put your html from response
</div>
And you should append the html like this: $('#imagens').append($(img));
3.
(function($){
"use strict";
$('.some-root-div', '.deletaImagem').on('click', function(){
// your logic on `.deletaImagem` link click
})
})(jQuery);
Your problem is that event handlers are not being attached to the new elements. It is pretty simple to do so while you attach the element to the DOM.
Change this
$('#imagens').append(img);
to
$(img).appendTo('#imagens').find('.deletaImagem').on('click', function (){
var path = $(this).data('path');
var div_id = $(this).data('divid');
jQuery.ajax({
type: "POST",
url: "deletaImagem",
data: {'path':path},
dataType: "json"}).done(function(response)
{
if(response.sucesso){
toastr['success'](response.msg);
$('#'+div_id).remove();
}
else{
toastr['error'](response.msg);
}
});
return false;
});
I've been here. My solution and understanding is that AJAX comes at the end/during javascript, javascript coming way after CSS. I ended up setting the styles that need to be the most dynamic in javascript with a function that takes an element as a parameter. works like a charm!
function styleElement(elem){
elem.style.visibility = "hidden";
}

Refreshing div with ajax causes checkbox to loose value

I have a small box that is part of a PHP-site that lists all members who attended a certain event. In the box there is also a checkbox that communicates with a database to store values of who attended. I want the box to update dynamically when someone checks the checkbox. The code I have is working good, and whenever the DIV is refreshed I get an updated list of members and correct count, but loose both the checkbox value and the label!
I am sure there is a simple solution I've missed, but after trying for hours I need someone to point me in the right direction. Whenever I press F5 to refresh, the label and correct checkbox value reappears.
Javascript:
function check_my_attendance() {
var user_attending = Number(<?php echo in_array($_SESSION['username'],$attending_users) ?>);
if (user_attending > 0) { $("label[for='attending_checkbox']").text("You attended!"); }
else { $("label[for='attending_checkbox']").text("You did not attend."); }
$('#attending_checkbox').prop('checked',user_attending);
}
function set_attendance(cb) {
if($(cb).is(":checked")) {
$("label[for='attending_checkbox']").html('Setting..');
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=1",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance();
}
}); }
else {
$("label[for='attending_checkbox']").html('Removing..');
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=0",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance();
}
}); }
}
$(document).ready(function(){
check_my_attendance();
});
</script>
PHP/Html:
<div id="containerAttend">
<?php $query_attendance="SELECT link_attending.attended_memberid,link_attending.attended_gigid,members.username FROM link_attending
LEFT JOIN members ON (members.id = link_attending.attended_memberid) WHERE attended_gigid=".$ut;
$result_attendance = mysqli_query($mysqli,$query_attendance);
$attending_users = array();
for( $i = 0; $i < mysqli_num_rows ($result_attendance); $i++)
{mysqli_data_seek($result_attendance,$i); $usr=mysqli_fetch_array($result_attendance); $attending_users[] = $usr["username"];}
$chkattendance = array_filter($attending_users);
if (empty($chkattendance)) {$attendance_int = 0;} else {$attendance_int = count($attending_users);}
?>
<div id="list_attended">
<div class="col-md-3 col-md-offset-5">
<div class="panel panel-default">
<div class="panel-heading">
<b><?php echo $attendance_int; ?> users attended:</b>
</div>
<div class="panel-body">
<?php
if ($attendance_int > 0) {foreach($attending_users as $usr_att) {echo "<a href='profile.php?user=$usr_att'>$usr_att</a>"." - ";} echo "<br>";}
if (login_check($mysqli) == true)
{echo "<form><input id='attending_checkbox' type='checkbox' onclick='set_attendance(this)' />
<label for='attending_checkbox'></label></form>";}
else
{echo "<br>Log in to set attendance!";}
?>
</div></div></div></div>
Thanks for any help!
Based on the comments, this is where I believe you can make changes and everything might just work fine for you
function check_my_attendance(result) {
var user_attending = Number(<?php echo in_array($_SESSION['username'],$attending_users) ?>);
if(typeof result != 'undefined') {
user_attending = result;
}
if (user_attending > 0) {
$("body label[for='attending_checkbox']").text("You attended!");
} else {
$("body label[for='attending_checkbox']").text("You did not attend.");
}
$('body #attending_checkbox').prop('checked',true);
}
In function set_attendance(), you can pass the result value to your check_my_attendance() function like this:
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=1",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance(result);
}
});
You can do console.log(result) and check what you are getting as result in in the after the AJAX Callback. If it is an empty string, you can add this line at the end of setattendance.php - echo 1; or echo 0;
I also created this fiddle as a small example for setting this checked property and label text. Even though I am not using any AJAX in it, I just wanted to let you know why we are using the body tag before #attending_checkbox in $('#attending_checkbox'). The basic reason behind showing it to you is that whenever a new DOM element is loaded or an old DOM element is replaced the old javascript doesn't work. So, you need to set the parent name and then the DOM id first, so that the JavaScript is able to locate the new element. - https://jsfiddle.net/prateekkathal/3kbtp2am/
Thanks,

Updating database values using ajax request

I have a form and it has radio buttons that a user must click to increement a value in the database but I click the radio button and nothing happens in the database heres my form code:
<form id="myform" name="myform" method="post">
<div class="radio show-options">
<li><label id="l_security"><input type="radio" id="r_security" name="weekend" value="security" />Security</label> (<label id="c_security">0</label>)</li>
</div>
<div class="radio show-options">
<li><label id="l_manager"><input type="radio" id="r_manager" name="weekend" value="manager" />Manager</label> (<label id="c_manager">0</label>)</li>
</div>
<div class="radio show-options">
<li><label id="l_cleaner"><input type="radio" id="r_cleaner" name="weekend" value="cleaner" />Cleaner</label> (<label id="c_cleaner">0</label>)</li>
</div>
</form>
here the script for the form
<script type="text/javascript">
var lastClicked = '';
function getTotals() {
// function to get click counts as JSON from helper page
// expects get_count.php to be in same directory level
$.ajax({
type: "GET",
url: "get_count.php",
dataType: "json",
error: function(xhr, status, msg) {
alert("Failed to get click counts: " + msg);
}
})
.done(function(data) {
// loop through JSON variables, assign to count labels
$.each(data, function(key, value) {
var tmp = "#c_" + key;
$(tmp).text(value);
});
});
}
function processClick(obj) {
// function to increment click count via ajax
// expects increment_count.php to be in same directory level
if(lastClicked != obj.val()) { // don't count clicks on currently active radio button
lastClicked = obj.val(); // set currently clicked radio button to this one
var qs = "weekend=" + obj.val(); // set query string value
$.ajax({
type: "GET",
url: "increment_count.php",
data: qs,
error: function(xhr, status, msg) {
alert("Failed to process click count: " + msg);
}
})
.done(function() {
getTotals(); // update totals on successful processing
});
}
}
$(document).ready(function() {
getTotals(); // get click totals on initial page load
$(document).ready(function() {
// add click incrementing event handler to all radio buttons on page
$('input:radio').click(function() {
processClick($(this));
});
});
});
</script>
here is get_count.php
<?php
require('db_connect.php');
// get new count totals, pass as JSON
$rs = mysql_query("SELECT * FROM employee") or die('Cannot get updated click counts');
if(mysql_num_rows($rs) > 0) {
$out = "{ ";
while($row = mysql_fetch_array($rs)) {
$out .= "\"$row[name]\" : $row[leave], ";
}
$out = substr($out, 0, strlen($out) - 2);
$out .= " }";
header("Content-type: application/json");
echo $out;
}
and here is increment_count.php
<?php
require('db_connect.php');
// if this is a postback ...
if(isset($_GET['weekend'])) {
// create array of acceptable values
$ok = array('security', 'manager', 'cleaner');
// if we have an acceptable value for position_name ...
if(in_array($_GET['weekend'], $ok)) {
// update the counter for that position
$q = mysql_query("UPDATE employee SET leave = leave + 3 WHERE name = '".$_GET['weekend'] . "'") or die ("Error updating count for " . $_GET['weekend']);
}
}
the leave value in the employee table is not increased

call javascript function in every div in html

Hi I have a javascript function and I want it to call when the c_id loops each. but I don't have an idea about it.
here is my function.
function getCLowestPrice(c_id){
$.ajax({
type: "POST",
url: 'http://sample.com/api/store_lowest_price/',
dataType: "xml",
cache: false,
data: {'id' : c_id},
success: function(resp){
// we have the response
console.log(resp);
$(resp).find("response").each(function() {
var c_name = $(this).find("c_name").text();
var c_currency = $(this).find("currency").text();
var c_min_price = $(this).find("price_min").text();
var formated_price = addCommas(parseFloat(c_min_price).toFixed(2));
$('.cinformation').html("<p>Lowest Price : " + c_currency + " " + formated_price + "</p>");
});
},
});
}
and I want it to call when the div loaded. but it loops all the clients and also their c_id.
<div>
Client : <?php echo get_post_meta($post->ID, 'wpcf-c', true); ?>
<div class="cinformation">
C ID = <?php echo get_post_meta($post->ID, 'wpcf-c-id', true); ?>
....
</div>
...
</div>
so it will be this when it loops.
<div>
Client : Hello
<div class="cinformation">
C ID = 1
....
</div>
...
</div>
....
<div>
Client : World
<div class="cinformation">
C ID = 2
....
</div>
...
</div>
....
....
...
but i don't have any idea on how can I add the getCLowestPrice(c_id) in the cinformation div.
I try to use the onload but it can't be used in div.
does anyone have an idea about my case?
thanks in advance ...
You need to put your C ID using data attribute like so:
<div>
Client : Hello
<div class="cinformation" data-c_id="1">
</div>
</div>
Then after the page loads just use jQuery to select all your divs and call your function:
$(".cinformation[data-c_id]").each(function(index, elem){
var cId = $(this).data("c_id");
getCLowestPrice(cId);
});
You can just try adding this
<script type="text/javascript">
getCLowestPrice (<?php echo get_post_meta($post->ID); ?>)
</script>
in your for loop in php

Categories