Turning jquery into an includable, callable function - javascript

I'm so frustrated! As an ok PHP developer I can't get my head around the simplist of jquery problems!
I have recently moved my HTML jquery include to the end of the HTML body, instead of in the head to improve google pagespeed score.
This has broken some jquery which is used for simple comment voting. This was written badly as it repeats for every comment.
<div id="voterow-19907" class="commentfooter">UP</a> | <a id="comment-vote-down-19907" href="#" rel="nofollow">DOWN</a></div>
<script>
$("#comment-vote-up-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=up",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
$("#comment-vote-down-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=down",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
</script>
Since moving the jquery include to the bottom of the page this naturally doesn't work.
What I'm trying to do is turn the above code into a mini function I can include after the jquery include, then pass the ID and VOTE-DIRECTION to the function from the HTML a hrefs using the jquery DATA- attribute.
Any help would be greatly appreciated. I'm running out of hair!

I think, repeated codes will hurt your page than placement of JQuery file.
You can solve this problem using more general event listener. Remove all listeners inside code (all of them) and append the code below after Jquery include.
$('[id^=comment-vote]').click(function() {
var elementId = $(this).attr('id');
var elementIdParts = elementId.split("-");
var voteType = elementIdParts[2];
var id = elementIdParts[3];
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v="+id+"&d="+voteType,
success: function(data){
$("#voterow-"+id).text("Thank you for your vote")
}
});
return false;
});
$('[id^=comment-vote]") selects all elements which have id starting with "comment-vote". If user clicks one of these elements, event handler gets id of elements, split into parts like "comment", "vote", "up", "19900". 2nd part is voteType and 3rd part is ID of row. We can use these variables while generating/operating AJAX request.
I didn't try the code but the idea behind that would be beneficial for you.

To really give a great working answer, I would need to see your an example page / the exact structure of your html, but here's what I have for you.
In a script file that you include after jQuery, you can include something similar to the below code assuming your html is as follows:
<div id="voterow-1" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
<div id="voterow-2" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
Having the class of upvote and downvote makes it easy to target these elements in jQuery:
// After jQuery is loaded, the function passed to ready() will be called
$(document).ready(function () {
// bind a click event to every direct child with the upvote class of an element with the voterow class
$('.voterow > .upvote').click(function (event) {
// get the voterow parent element
var $parent = $(event.target).parent();
// use regex to strip the id number from the id attribute of the parent
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
// call your ajax function
vote(id, 'up', $parent.find('.voteresult');
});
$('.voterow > .downvote').click(function (event) {
var $parent = $(event.target).parent();
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
vote(id, 'down', $parent.find('.voteresult');
});
function vote(id, direction, $resultElement) {
$.ajax({
type: "GET",
url: "/ajax.php",
// here we have the id and the direction needed to make the ajax call
data: "a=rv&v=" + id + "&d=" + direction,
success: function(data){
$resultElement.text("Thank you for your vote")
}
});
}
});
Here is a demo: https://plnkr.co/edit/ECL376hZ3NOz8pBVpBMW?p=preview

Related

How to generate a button with its own js function?

Well I have data retrieved from ajax, I need to parse it in order to generate inputs with different <input> values. While clicking on <a> that should get near standing input value and go to ajax
<script type="text/javascript">
function proceed() {
var ID = document.getElementById('btnid').value;//probably that`s the wort way, because all of `<a>` buttons would have same id
//ajax with ID to proceed further
}
$.ajax({
async: false,
type: "POST",
url: "../api/",
data: {'data': "mydata"},
dataType: 'JSON',
complete: function (res) {
for(var i = 0; i < 10; i++) {
document.getElementById('nie').innerHTML = "
<ul class=\"somec\">
<li class=\"liclass\">
</input id=\"btnid\" value=\""+res.response[i].animal+"\" class=\"thatclass\" onclick=\"proceed();\"></input>//different values
<a id="clicker" onclick="proceed()"></a>//clickable link
</li>
</ul>
";
}
});
</script>
<html>
<div id="nie">
</div>
</html>
Any help or advises for solution ?
You cannot have more than one id in a single DOM -- only one unique id is allowed. Since jQuery is used here, you can take advantages of the other methods and API it provides.
First of all, I would move the loop to success handler of $.ajax because that ensures that I have data returned from the server.
As for "appending" input and anchor pairs, use $.append. What you're currently doing is just updating #nie with the last element's data in the loop.
For events, delegate the clicks on anchors. This is better because you might continue adding more elements, so you have to go through binding them to an event.
And please, don't set async to false in $.ajax settings. This has unexpected results and makes the browser slow to point that freezes and crashes. jQuery ajax async: false causes a strange warning?
$(function(){
var $nie = $('#nie');
// Delegate the click event
$(document).on('click', '.clicker' function(){
var id = $(this).siblings('input').val();
// Use id in upcoming AJAX request.
});
$.ajax({
type: "POST",
url: "../api/",
data: {'data': "mydata"},
dataType: 'JSON',
success: function (res){
$.each(res.response, function(i, r){
$nie.appeand('<ul class="somec">\
<li class="liclass">\
<input value="'+ r.animal+ '" class="thatclass"/>\
<a class="clicker"></a>\
</li>\
</ul>');
});
}
});
});

Update div content using PHP and Javascript variables

I'm new to Ajax and need some help with this.
The idea is simple, I have a list of directories within the div 'list' and when I click on one of the directories, the div 'content' must list the content of this directory with a php function.
This is my html code:
<div id="list">
<ul>
<li id="directory_1" class="test">directory_1</li>
<li id="directory_2" class="test">directory_2</li>
<li id="directory_3" class="test">directory_3</li>
<li id="directory_4" class="test">directory_4</li>
</ul>
</div>
<div id="content">
<!-- Here you can see the folder content-->
</div>
This my jQuery + Ajax:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
It works, I arrive to list.php. And on PHP I have a function that lists directory content.
So how can I refresh 'content div' with the php function?
So if I click on directory_1 it will show /var/www/pg/directory_1 folders, and then if I click on directory_2 it will clear the 'content' div and will then list out the directory_2 folders.
Here is a jsfidde without the PHP code:
http://jsfiddle.net/e5v1dgpc/
Sorry for my English, if someone has a question I will try to clarify.
You could do something like this:
jQuery('#content').html('');
Which will just set everything inside the html to be blank.
Or I think you could use .empty() - http://api.jquery.com/empty/
If you called it at the start of your function then it should clear the div before repopulating it.
$(".test").click(function(){
var name = $(this).attr("id");
$( "#content" ).empty();
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
In order to set the target of your ajax you could do something like this with a success condition. You'd need to change it to display whatever content you want.
$.ajax({
url: 'list.php',
type: 'POST',
success: function(html) {
var divSuccess = $('#content', $(html)).addClass('updated');
$('#content').html(divSuccess);
}
});
This link might also be useful to you - jquery ajax load certain div
Instead of Emptying the 'content' div initially, you can empty it
OnSuccess of the Ajax post, as below:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
success: function(){
$( "#content" ).empty();
}
});
});
Hope this is what you are looking for..

Jquery removing issue divs still remains

Yesterday I coded a Commentbox in PHP, HTML and ajax. The ajax part gives me the opportunity to delete a comment without refreshing the page. The way I do this, is that I give each and every comment (div) a unique id via the database. So let us for example say that in my mysql database this is how a comment looks like:
Username: blabla<br>
Comment: haha this is so funny<br>
id: 52
This will be printed out in the html page likes this for example:
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment">Delete the comment here!</div>
</div>
AND THEN!
Comes the ajax part which is coded something like this:
$(document).ready(function(){
$(".deleteComment").click(function(){
//Getting the id of comment
id = $(".deleteComment").attr("id");
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
});
This works fine when deleting the first comment. But it WONT LET ME DELETE OTHER COMMENTS UNLESS I REFRESH THE PAGE >.<. The first comment can be perfectly deleted without refreshing the page, but when I want to delete other comments I have to refresh the page multiple times.
How do I solve this?
The code in your document ready event would work properly only for the first click. In order to get this work, you must have an on click event registered within the tag.
Example :
<div class="deleteComment" onclick="DeleteMe(id)">Delete the comment here!</div>
</div>
function DeleteMe(id)
{
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
}
If the on click on a div does not work, you can use an anchor tag (Delete here) instead.
.deleteComment is child of <div class="commentStyle".., so you can select it with parent() selector:
var id = $(this).parent().attr("id");
Or more specifically:
var id = $(this).parent('.commentStyle').attr("id");
Looks like you need to get the id from the parent element first and then target the child, the element you clicked, to hide the comment from it after the ajax request returns success:
$(".deleteComment").click(function(){
var id = $(this).parent().attr("id");
var child = $(this);
$.ajax({
type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
child.hide();
// or if you want to delete the entire element with the id of X
// child.parent().hide();
}
});
});
There are few changes which need to be done in your code.
First of all add ID tag to the inner div.
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment" id="<?php echo $commentid; ?>">Delete the comment here! </div>
</div>
Secondly use this
id = $(this).attr("id");
instead of...
id = $(".deleteComment").attr("id");
Thirdly change the ajax call like this:
$.ajax({
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id
}).done(function(){
$("#" + id).hide();
});
Hope this works for you, if not just reply me.

Making a function affect a element in another page

I made a function that is invoked for the lack of better words from a page, lets call it Page1, the function is called when a button is clicked, at the end of said function it calls another one that creates (or should seeing I haven't been able to test it) a html and appends it to a div with a #lista id.
The problem is that this div is another page (Page2), so I don't know if there is some syntax like in ajax where you specify where you want those values to go, so basically page 1 calls a function (on another file just in case) that function calls another and the result of that function goes on Page1 (another file, again just in case)
Here is my jQuery/JS code to further illustrate:
$("#btnAceptar").click(function() {
var idlab = $('#txtNumLab').val(),
capacidad = $('#txtCapacidad').val(),
carrera = $('#txtCarrera').val(),
ubicacion = $('#txtUbicacion').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'addLab',
'pIdLab':idlab,
'pCapacidad':capacidad,
'pCarrera':carrera,
'pUbicacion':ubicacion},
dataType: 'json',
success: function(response){
alert('exito')
agregar();
}
});
});
This function should affect a element with id #Lista on Page2.
function agregar(){
var div = $( "#lista" ).append( "<div class='box'>
<p>Lab #'numero'</p>
<p class='info'><a href='#' id='lnkInfo'>Info</p></a>
<p class='info'><a href='reservarLab.html'>Reservar</p></a>
</div>" );
div.id = querySelectorAll('#lista > div').length +1;
var numero = div.id;
$('#numero').append(div);
}
Thanks a lot in advance!
Yes you can get content from another page using jQuery:
Ajax request gets the entire file, but you can filter the content once it's retrieved:
$.ajax({
url:href,
type:'GET',
success: function(data){
$('#content').html( $(data).find('#IDofDivToFind') );
}
});
Second Approach (Untested)
You can use JQuery .load() method:
$( "#content" ).load( "ajax/test.html div#content" );
Reference:
http://api.jquery.com/load/

click event on dynamic li elements

Updated the question as per #Jonathan Kuhn's feedback and it works like a charm
I am building a messaging system for my web application.
where the users should be able to communicate with me via messages (ajax)
I am being able to append <ul> with additional <li> from jQuery
$('#send').click(function(e){
e.preventDefault();
var reply = $('#reply').val();
var project_id = 44; // just for reference
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>messages/send",
data:{ msg:reply, project_id:project_id },
success: function (response) {
if(response=="success"){
$(".messages").append('<li class="message" id="message">'+reply+'<a id="delete">delete</a></li>');
var clearText = "ture";
}else{
}
}
});
Which is working perfectly fine. But I am having problem while deleting the dynamically added list element.
I tried bind() and on() jQuery functions but as I am not much good at it, I am facing a lot of issues.
$("#messages").on('click', '#delete', function(event) {
event.preventDefault();
var id = 22 ; // just for reference
$.post( "<?php echo base_url(); ?>messages/delete", { type:'single', id:id } )
.done(function( data ) {
});
$(this).closest('li').remove();
});
My HTML structure is as below
<ul class="messages" id="messages">
<li class="message" id="message">sdaghds<a id="delete">delete</a></li>
</ul>
You have id="#messages" on the <ul>. Remove the # and then the .on one should work.
Also, ids are supposed to be unique throughout the page. So you shouldn't have multiple message ids throughout. If you need multiple, use classes. Remove the id from the <li>.

Categories

Resources