How to show a message status below the rate button in jquery? - javascript

I have a rate button on my page, created using PHP and jQuery.
When the button is clicked, a message is shown and hidden after a while "#num voted including you"
HTML:
div class="voting_wrapper" id="1001">
<div class="voting_btn">
<div class="up_button"> </div>
<span class="up_votes"></span>
</div>
</div>
jQuery:
$(document).ready(function() {
//####### on page load, retrive votes for each content
$.each( $('.voting_wrapper'), function(){
//retrive unique id from this voting_wrapper element
var unique_id = $(this).attr("id");
//prepare post content
post_data = {'unique_id':unique_id, 'vote':'fetch'};
//send our data to "vote_process.php" using jQuery $.post()
$.post('vote_process.php', post_data, function(response) {
//retrive votes from server, replace each vote count text
$('#'+unique_id+' .up_votes').text(response.vote_up +' user has voted');
},'json');
});
//####### on button click, get user vote and send it to vote_process.php using jQuery $.post().
$(".voting_wrapper .voting_btn").click(function (e) {
//get class name (down_button / up_button) of clicked element
var clicked_button = $(this).children().attr('class');
//get unique ID from voted parent element
var unique_id = $(this).parent().attr("id");
if(clicked_button==='up_button') { //user liked the content
//prepare post content
post_data = {'unique_id':unique_id, 'vote':'up'};
//send our data to "vote_process.php" using jQuery $.post()
$.post('vote_process.php', post_data, function(data) {
//replace vote up count text with new values
$('#'+unique_id+' .up_votes').text(data);
//thank user for liking the content
dataModified = data+' users has voting including you';
$('#message-status').hide().html(dataModified).fadeIn('slow').delay(5000).hide(1);
}).fail(function(err) {
//alert user about the HTTP server error
alert(err.statusText);
});
}
});
//end
});
It works fine, but placement of the message is incorrect. When I click the button, that message status shows up at the top of the page, while I need it to be shown below the rate button.
May I know how to add the code to achieve this? I think I could use append(); but I am struggling where and how to add the script. Can anyone help me?
Thanks in advance.

The reason why is that, is probably because the #message-status element is initially placed outside of the voting_wrapper element. You could move #message-status inside that wrapper, below the .voting_btn button using .insertAfter()
$('#message-status').hide().html(dataModified).insertAfter('#'+unique_id+' .voting_btn').fadeIn('slow').delay(5000).hide(1);
So that after AJAX call, your HTML becomes:
<div class="voting_wrapper" id="1001">
<div class="voting_btn">
<div class="up_button"> ddd</div>
<span class="up_votes">X</span>
</div>
<div id="message-status">X users has voting including you</div>
</div>
[EDIT]
If you need the message below the whole voting_wrapper, use this:
$('#message-status').hide().html(dataModified).insertAfter('#'+unique_id).fadeIn('slow').delay(5000).hide(1);

try replacing your code,
$('#message-status').hide().html(dataModified).fadeIn('slow').delay(5000).hide(1);
with this
$('#message-status').css({
'position': 'absolute',
'left': $(this).offset().left,
'top': $(this).offset().top + $(this).height() + 5
}).hide().html(dataModified).show("slow").delay(3000).hide("slow");

Related

Jquery concatination with upvotes in php

I have been created voting system using php and jquery.
Here is my index.php:
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//####### on page load, retrive votes for each content
$.each( $('.voting_wrapper'), function(){
//retrive unique id from this voting_wrapper element
var unique_id = $(this).attr("id");
//prepare post content
post_data = {'unique_id':unique_id, 'vote':'fetch'};
//send our data to "vote_process.php" using jQuery $.post()
$.post('vote_process.php', post_data, function(response) {
//retrive votes from server, replace each vote count text
$('#'+unique_id+' .up_votes').text(response.vote_up);
},'json');
});
//####### on button click, get user vote and send it to vote_process.php using jQuery $.post().
$(".voting_wrapper .voting_btn").click(function (e) {
//get class name (down_button / up_button) of clicked element
var clicked_button = $(this).children().attr('class');
//get unique ID from voted parent element
var unique_id = $(this).parent().attr("id");
if(clicked_button==='up_button') //user liked the content
{
//prepare post content
post_data = {'unique_id':unique_id, 'vote':'up'};
//send our data to "vote_process.php" using jQuery $.post()
$.post('vote_process.php', post_data, function(data) {
//replace vote up count text with new values
$('#'+unique_id+' .up_votes').text(data);
//thank user for liking the content
dataModified = data+' users has voting including you';
$('#message-status').hide().html(dataModified).fadeIn('slow').delay(5000).hide(1);
}).fail(function(err) {
//alert user about the HTTP server error
alert(err.statusText);
});
}
});
//end
});
</script>
<style type="text/css">
<!--
.content_wrapper{width:500px;margin-right:auto;margin-left:auto;}
h3{color: #979797;border-bottom: 1px dotted #DDD;font-family: "Trebuchet MS";}
/*voting style */
.voting_wrapper {display:inline-block;margin-left: 20px;}
.voting_wrapper .up_button {background: url(images/index.png) no-repeat;float: left;width: 50px;cursor:pointer;}
.voting_wrapper .up_button:hover{background: url(images/index.png) no-repeat;}
.voting_btn{float:left;margin-right:5px;}
.voting_btn span{font-size: 11px;float: left;margin-left: 3px;}
-->
</style>
</head>
<body>
<div class="content_wrapper">
<h3><img src="9780143332497.jpg" alt=""><br />
<!-- voting markup -->
<div class="voting_wrapper" id="1001">
<div class="voting_btn">
<div class="up_button"> </div><span class="up_votes"></span>
</div>
</div>
<!-- voting markup end -->
</h3>
<span id="message-status"></span>
</div>
When i click the rate button it will shows count number as stable, and also i set to shows up vote count number fade in and fadeout.
Now i need like this http://s1.postimg.org/mv060km8v/Untitled_1.png
I tried to add my "user has voted" text in my jquery script, but it seems to be nothing happen.
May i know, where can i add exact code to get my needs?
Can anyone help me? thanks in advance.
In your index.php
//retrive votes from server, replace each vote count text
$('#'+unique_id+' .up_votes').text(response.vote_up + ' user has voted');
you add the count alone in your jquery try to add your text along with it.
What exactly u want to hide the button?
to include user has voted u need to add
$('#'+unique_id+' .up_votes').text(data + ' User has Voted');

Saving <div> styles with its content inside a contenteditable div

The title of this question might be unclear, but thats why I'm trying to explain it right here. I've got a contenteditable div which acts like a textarea for the articles of my blog (adminpanel). Getting the db data to display properly in the contenteditable div is no problem. But when I save the updated article version to my database, it aint saving the div styles ( as example) which are in the contenteditable div.
Example:
<div id="article_content" class="edit_article_content_container_inner" contenteditable="true"><?php echo $db_content ?></div>
outputs:
<div id="article_content" class="edit_article_content_container_inner" contenteditable="true">
<div>Dear visitor,</div>
<div><br /></div>
<div>Thank you for visiting</div>
</div>
When I make changes and decide to save the new version, the db_content column gets updated and looks like:
Dear visitor,Thank you for visiting this page
So the contenteditable div destroys my div styles when saving the new updated article. Is there a way to still store these div styles?
Thank you.
This is the part where I make the ajax call
$("#btn-save-new-article").on('click', function (event) {
var article_id = $('.edit_article_title_container').attr('data-article-id');
var article_title = $("#article_title").text();
var article_content = $("#article_content").text();
event.preventDefault();
$.ajax({
type: "POST",
url: "/includes/db-requests/admin/db-save-edited-article.php",
data: {article_id: article_id, article_title: article_title, article_content: article_content},
success: function(data,textStatus,jqXHR){ finish_editing_article(data,textStatus,jqXHR); }
});
});
function finish_editing_article(data,textStatus,jqXHR) {
//alert (data);
if (data == "article_edited_success") {
//location.reload();
alert(data);
} else {
alert(data);
}
}
As you can see, I'm storing the article_id, article_title and article_content.
Receiving the data to actual store it:
//DIV SUBMITTED DATA
$article_id = safe($mysqli,$_POST['article_id']);
$article_title = safe($mysqli,$_POST['article_title']);
$article_content = $_POST['article_content'];
.text() returns just the text content of an element. .html() returns the content with the HTML intact.
var article_content = $("#article_content").html();

LocalStorage does not update when I submit details from edit form

I am using jQuery to develop a mobile app. The interesting thing is when I edit the details of an employee, in the listview the update is visible, but when I look in the localstorage the update does not reflect, also the page for full details of the employee does not update as well. However if I refresh the browser the updates show. How do I get both the localstorage and details page to update without refreshing the browser.
I am using two different forms, one to add a new employee, and another to edit employee details.
Thanks for any suggestions
Here are my codes for adding new employee
//user input to Add Employee Form
$('#add_new_employee_form').on('submit', function(){
var newEmployee = {
id: employees.length+1,
employeeno: $('#employeeno').val(),
employeename:$('#employeename').val(),
employeebirth:$('#employeebirth').val(),
employeestate: $('#employeestate').val(),
employeephone:$('#employeephone').val(),
};
employees.push(newEmployee);
addEmployee(newEmployee);
//save offline
localStorage.setItem('employees', JSON.stringify(employees));
//Alert when case saved successfull
toast('Employee added successfully.');
//refresh the list view
$('#employee_list').listview("refresh");
//Change page to home
$.mobile.changePage('#home_page');
return true;
});
//execute function to show cases
showEmployees();
Here is my code for editing employee
// Editing Saved Cases
//User input to Edit form function
$('#edit_employee_form').on("submit", function(){
var x=document.forms["edit_employee_form"]["id"].value; //here we are taking the value of employee id
//and saves the new values to editEmployees
var editEmployees = JSON.stringify({
id: x,
employeeno: document.forms["edit_employee_form"][" employeeno"].value,
employeename:document.forms["edit_employee_form"]["employeename"].value,
employeebirth:document.forms["edit_employee_form"]["employeebirth"].value,
employeestate: document.forms["edit_employee_form"]["employeestate"].value,
employeephone:document.forms["edit_employee_form"]["employeephone"].value,
});
var y=x-1;
cases[y]=JSON.parse(editCases); //here we updates the values
//After the selected case has been edited
localStorage.setItem("employees", JSON.stringify(employees)); //set the update values to localstorage
toast('Employee Updated Successfully');
//refresh the list view
$('#employee_list').listview("refresh");
//update list view
showCases();
$.mobile.changePage('#home_page');
//refresh the list view
$('#employee_list').listview("refresh");
return true;
});
//Edit button
$(".edit_button").live('click', 'tap', function(e){
e.stopPropagation();
$.mobile.changePage("#edit_employee_page"); // the edit_employee_page was brought to front for making
// the edit_employee_form inside the access scope
var employeeId=$(this).attr('id'); // here we are taking the id of the button for that particular employee.
$('#edit_employee_page').ready(function(e) { //this is for initializing the values on ready of the edit_employee_page
for (var i = 0; i < employees.length; i++){
if(employees[i].id == employeeId){
document.forms["edit_employee_form"]["id"].value=employeeId;
document.forms["edit_employee_form"]["employeeno"].value=employees[i].employeeno;
document.forms["edit_employee_form"]["employeename"].value=employees[i].employeename;
document.forms["edit_employee_form"]["employeebirth"].value=employees[i].employeebirth;
document.forms["edit_employee_form"]["employeestate"].value=employees[i].employeestate;
document.forms["edit_employee_form"]["employeephone"].value=employees[i].employeephone;
document.forms["edit_employee_form"]["id"].setAttribute('id',"readonly");
}
}
});
return false;
});
Here is the code for the dynamic list view, and dynamic pages for each list item
//add an eliment to list view
var addEmployees = function(empData){
//HTML content of one list element
var listElementHTML = '<li><a class="employee_list" ui-btn ui-btn-e ui-btn-icon-right ui-icon-carat-r" data-transition="fade" data-split-icon="delete" href="#item'+empData.id+'">'+empData.employeename+'<br> '+empData.birth+'</br></a></li>';
//appending the HTML code to list view
$('#employee_list').append(listElementHTML);
//Dynamically adding HTML Pages
var employeePageHTML = '<div id="item'+empData.id+'" data-role="page" data-theme="b"><div data-theme="a" data-role="header"><h1>'+empData.employeename+'</h1>Home\
Delete</div><div data-role="content">\
<div data-role="collapsible" data-inset="false" data-collapsed="true" data-theme="b"><h3>Case Details</h3><i><strong>Employee No:</i></strong>'+empData.employeeno+'</br><i><p><strong>Employee Name:</i></strong> '+empData.employeename+'</br><i><p><strong>State Of Origine:</i></strong>'+empData.state+'</br><i><p><strong>Employee Phone:</i></strong>'+empData.employeephone+'</br><i><p><strong>Date Of Birth:</i></strong>'+empData.birth+'</div></div>\
<div data-position="fixed" data-theme="a" data-role="footer">Edit</div></div></div>';
You can make an AJAX request in jquery that loads the content asynchronously. Using AJAX allows requests and functions to act without reloading the browser because it connects to the server and back within the method. In your jquery you could do the following:
var data="all the data you want to update with";
$.ajax({
$("body").load(data);
//this would load that string inside the body but you can do whatever
you want in this ajax function.
});

Best way to pass JS/ css info to a form

I am sure this is so easy and I'm just a huge huge noob. I have a form on a PHP page, and it has a few normal form elements (1 textarea, 1 text field).
I am also dynamically adding 100 small images to the page, which are random, and I am using JQuery to let someone select or deselect these images:
Here is the html that loops 100 times to display the images:
<div class='avatar'><img class='avatar_image' src='$this_profile_image' name='$thisfriend'></div>
and here is the Jquery:
<script type="text/javascript">
$(document).ready(function() {
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
});
</script>
What I want to do is, when the form is submitted, have the script that processes it be able to tell which of those 100 images is selected (so it's class will be "red" instead of "avatar_image"). I am blanking on this.
You'll need to add hidden inputs with some kind of identifiers for those images, and toggle the state of those inputs based on the image selected-ness. Something like this:
Change your image markup:
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend'>
<input type="hidden" name="avatar_image[]" value="$this_profile_image" disabled="disabled" />
</div>
Change jQuery binding (and use event delegation, maybe pick a better container than document.body):
<script type="text/javascript">
$(function() {
var selClass = 'red';
$(document.body).on('click', ".avatar_image", function() {
var $this = $(this);
var $inp = $this.siblings('input[type="hidden"]');
var isSelected = $this.hasClass(selClass), willBeSelected = !isSelected;
$this.toggleClass(selClass);
if(willBeSelected) {
$inp.removeAttr('disabled');
} else {
$inp.attr('disabled', 'disabled');
}
});
});
</script>
Read the submitted data in PHP (assuming you're submitting via a POST form):
$selectedImages = $_POST['avatar_image'];
Add a ID to each image, when its clicked grab the id and then inject it into a hidden textfield
<input type="hidden" name="avatar" id="avatar" value="" />
$(".avatar_image").click(function() {
$(this).toggleClass("red");
//assign its id to the hidden field value
$("input[name='avatar']").attr('value', $(this).attr('id'));
// pass that to your DB
});
I presume your using ajax to grab this data back
success : function(callback){
$("image[id*='"+callback.avatar+"']").addClass('red');
}
Try this
PHP: Add the id for the friend to the html you had
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend' data-id='$thisFriendsId>
</div>
JS: Create an empty array. Use each function to go through push the selected id into your array. Then use post to submit to your php.
selected = [];
$(function(){
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
$('.submit').click(function(){
$('.red').each(function(){
var selectedId = $(this).data('id');
selected.push(selectedId);
});
$.post ('http://mysite.com/process.php', selected, function() { alert('succes!'); });
});
​});​

how to use AJAX to fetch content

I need to do a fetch using ajax. I need to use this: ajax/get_item_list/group_id/offset/limit/true (return true as JSON) where id comes from a link that user clicks. And when user clicks that link, it should call(?) that "ajax/get_item_list/group_id/offset/limit/tru" to get content to a div. And when user clicks another link (in navigation), it should do that again, but ofcourse it should get new content.
I am using drupal if that info is needed.
//Mario
Have you tried some jquery?
<div id="display"></div>
Click me
And then some javascript:
$(document).ready(function(){
$('a.ajaxToDisplay').click(function(){
$('#display').load(this.href);
return false;
});
});
I get this kind of error on firebug: $(this).href is undefined
[Break on this error] var group_id = $(this).href.replace(/.*#/, '');
this is when i use jcubic's proposal.
//mario
You can use JQuery.
$('a.link_class').click(function() {
var group_id = $(this).href.replace(/.*#/, '');
$.get("ajax/get_item_list/" + group_id + "/offset/" + limit "/true", null, function(data, status, xhr) {
$('#your_div_id').html(data);
});
});
and in html use links:
link
<div id="your_div_id"></div>

Categories

Resources