Find closest class and reload it AJAX jQuery - javascript

This is a "LIKE" system similar to Facebook.
I've got an html layout with multiple links where each one looks something like this when rendered :
<a class="like-comment-link" href="#" data-id="278">
<span class="like-comment"></span></a>
<span class="likes">Bob, John and Peter like this</span>
I'm using AJAX to insert and delete the likes into the database, this is all working great. But I'm having trouble targeting the "likes" class from the ajax script to update the names of the people that liked it.
I basically need something which does the following :
$(this).closest(".likes").find(".likes").load(location.href + " .likes");
I know this doesn't work but I don't know the correct way to code it.
Basically, on a successful like or unlike I need jQuery to find the closest instance of ".likes" to the parent which is ".like-comment-link" and then reload that class only on this element.
EDIT
Including AJAX script
$(document).ready(function(){
$(document).on('click', "a.like-comment-link", function(event) {
event.preventDefault();
var $self = $(this);
var data = {
post_id: $self.data('id'),
nonce: likecom.nonce,
action: 'comment_likes'
};
$self.addClass('loading');
$.post(likecom.ajaxurl, data, function(res) {
if (res.success) {
$self.html(res.data);
$self.siblings(".likes").load(location.href + " .likes");
} else {
alert("It went tits up!");
}
$self.removeClass('loading');
});
});
});
If this is overly complicated I could change target class' name to include the id of the current item like this :
<span class="likes-278">....</span>
But I can't figure out how to concatenate strings in jQuery.
I tried a few things like this :
$(".likes-" + $self.data('id')).load(location.href + " .likes-" + $self.data('id'));
But that obviously didn't work.
Maybe somebody could show me how to correctly formulate this in the AJAX script?

You may try something like this. Since the span is always after the anchor element in your example, you may also use .next() function to locate the element
$('.like-comment-link').on("click",function()
{
if($(this).next("span").hasClass("likes"))
{
$(this).next("span").removeClass("likes");
$(this).next("span").addClass("nolikes");
// Write value to db
}
else
{
$(this).next("span").removeClass("nolikes");
$(this).next("span").addClass("likes");
// Write value to db
}
});
http://jsfiddle.net/3k0vLdt4/3/
Hope it helps doing what you want to do.

Related

Having issues calling an ID after I have appended data from an ajax call

Ok,
So I have a .on click event which is called to an ajaxed script. The script returns a set of HTML information.
Now, what I seem to be having an issue with and maybe I am just not typing the right search terms in for this so my apologies if this was answered already.
When the html is appended to the correct box, the user is then able to click a link on that box, drop down the box and see a new input box. The user should be able to type the text in and hit the enter key and it should work.
When I run an inspect element, I do see the element's ID properly inserted, but it is like javascript doesn't even recognize the new element id.
UPDATE: I am really not sure why you need code to be able to answer this question, however here it is. The code works normally unless the above happens so yes I am appending it, and yes I am SURE i am appending it, please make sure to read everything before posting a comment, thanks!
$('body').on('keypress', '.peapComment', function(event) {
if(event.which == 13) {
var peap_id = $(this).attr('rel');
var comment = $(this).val();
$.ajax({
type: "POST",
url: "index.php",
data: {
page: "postPeapComment",
peap_id: peap_id,
comment: comment,
}
}).done(function(msg) {
console.log(msg);
$('#comment_' + peap_id).append(msg);
});
console.log('Send to Peap #' + peap_id + ': ' + comment);
$('#commentbox_' + peap_id).val('');
}
});
I have tested your code, and it seems to work without problems for me. My assumption would be that the data returned from your ajax call, is failing to return the proper "Peap_ID" or not returning anything all around, as this is the only way I can reproduce what you have claimed your error is, otherwise the code you have posted looks great.

Get URL To Add Inline Style

I'm using Blogger and on the "Preview" post page, it is hiding an element with 'display:none'. What I am trying to do, is use javascript to apply 'display:block' to that element during the "Preview".
I have to use javascript, because Blogger doesn't have any kind of XML conditional statement I can use; and default styling cannot be changed.
The URL looks something like this: https://myblogexample.blogspot.com/b/post-preview?token=XXXXXXXXXXXXXXXXXXXXXXXXXX&type=POST
The token is obviously always random. So how can I grab the part of the URL and apply an inline style to a particular element? My javascript skills suck, but this is what I came up with, and it doesn't work...
$(document).ready(function(){
if((window.location.protocol + "//" + window.location.host + "/b/post-preview) = document.getElementById('Main-Section').style.display = 'block'})
});
Your javascript code is not valid, it can't be parsed by the browser.
You are asking to show some part of the page when you are in the page "yourbloghost.com/b/post-preview?token=something", right?
You can do this with something like:
$(document).ready(function(){
if (window.location.pathname == "/b/post-preview")
{
document.getElementById('Main-Section').style.display = 'block';
}
});
or also:
$(document).ready(function(){
if (window.location.pathname == "/b/post-preview")
{
$("#Main-Section").show();
}
});

jQuery submit for two buttons

I have a basic form popup that will display when the button buy now of the main product is clicked with this code: onclick="productAddToCartForm.submit(this)"
and i have related products too in the same page with this main product with exactly the same button, and i want this pop up to be displayed also when it's clicked, and i tried to add onclick="productAddToCartForm.submit(this)" to it too but if i push it the pop up WILL work but will add to the CART both products.
how can i do this?
the code looks like this:
<div style="display: none;" id="ajax-popup">
<span class="button b-close"><span>X</span></span>
<h2 id="ajax-popup-message"></h2>
<div id="ajax-popup-content"></div>
</div>
<script type="text/javascript">
//<![CDATA[
var productAddToCartForm = new VarienForm('product_addtocart_form');
productAddToCartForm.submit = function(button, url) {
if (this.validator.validate()) {
var form = this.form;
var oldUrl = form.action;
if (url) {
form.action = url;
}
var e = null;
// Start of our new ajax code
if (!url) {
url = jQuery('#product_addtocart_form').attr('action');
}
url = url.replace("checkout/cart","ajax/index"); // New Code
var data = jQuery('#product_addtocart_form').serialize();
data += '&isAjax=1';
jQuery('#ajax_loader').show();
try {
jQuery.ajax( {
url : url,
dataType : 'json',
type : 'post',
data : data,
success : function(data) {
jQuery('#ajax_loader').hide();
//alert(data.status + ": " + data.message);
jQuery('#ajax-popup-message').addClass(data.status);
if(jQuery('#ajax-popup')){
jQuery('#ajax-popup-message').html(data.message);
}
if(jQuery('#ajax-popup')){
jQuery('#ajax-popup-content').html(data.sidebar);
}
if(jQuery('.header .links')){
jQuery('.header .links').replaceWith(data.toplink);
}
jQuery('#ajax-popup').bPopup();
}
});
} catch (e) {
}
// End of our new ajax code
this.form.action = oldUrl;
if (e) {
throw e;
}
}
}.bind(productAddToCartForm);
productAddToCartForm.submitLight = function(button, url){
if(this.validator) {
var nv = Validation.methods;
delete Validation.methods['required-entry'];
delete Validation.methods['validate-one-required'];
delete Validation.methods['validate-one-required-by-name'];
// Remove custom datetime validators
for (var methodName in Validation.methods) {
if (methodName.match(/^validate-datetime-.*/i)) {
delete Validation.methods[methodName];
}
}
if (this.validator.validate()) {
if (url) {
this.form.action = url;
}
this.form.submit();
}
Object.extend(Validation.methods, nv);
}
}.bind(productAddToCartForm);
//]]>
</script>
HTML looks like this:
<div class="main">
<div class="first">
<div class="add-to-cart">
<img onclick="productAddToCartForm.submit(this)" title="Add to Cart" src="../images/add-to-cart.png">
</div></div>
//STUFF
<div class="second">
<button onclick="window.location='URL'; productAddToCartForm.submit(this)" class="form-button add-to-cart" type="button"></button></div>
</div>
The root of your issue is, from what I can see from your example, that you are calling the form submission function twice. It appears that the second onclick had debug code with the window.location left in it when you pasted it here, of which is, what I can only determine from your description, the popup window markup that causes an endless loop of submitting items to the cart.
Firstly you're using jQuery to make programming with Javascript easier, get rid of the onclick= DHTML events in your html and use jQuery.
then add
jQuery(document).ready(function(){
jQuery('.add-to-cart').click(function(e){
e.preventDefault();
productAddToCartForm.submit(this);
});
});
Secondly there's no reason to wrap jQuery.ajax in a try catch, it has it's own error processing functionality. Unless you believe something would be wrong with jQuery's ajax function. Otherwise if you are trying to catch errors within the success method, you need to place the code inside the success method.
Think of ajax as a completely separate browser being opened up the instant it is executed.
Here's an example of what I am referring to: http://jsfiddle.net/73gpC/1/
Here's an example of an error method:
jQuery.ajax({
error: function(jqXHR, text, errorThrown){
if(errorThrown){
alert('Error: ' + errorThrown);
}
}
});
Next you have already declared the form with var form = this.form;, why search the DOM for it again?
jQuery('#product_addtocart_form').serialize();
should be form.serialize();
Every time you execute jQuery('selector'), jQuery "searches" for the element within the DOM.
While it sounds okay at first, as you begin dealing with more complex applications it is extremely slow to do things this way while the user interacts with your application.
It is much faster to use the declared variable instead since you already found it. With that said always favor ID's over class names as they are much faster to find but require valid HTML (ID's are unique and can not be reused).
From the look of it <button onclick="window.location='URL'; productAddToCartForm.submit(this)" is just completely broken and you are expecting it do something it simply won't because window.location='URL' is going to redirect the users browser to 'URL' when they click it and productAddToCartForm.submit(this) will never execute.
Example: http://jsfiddle.net/CZqDL/
No alert box will be displayed on click, indicating the function never fired.
I am all for helping someone learn how to figure out an issue if I am able, but this is really beyond your experience level with Javascript or jQuery in general.
I suggest getting a jQuery programming book or hiring a developer to program it correctly.
Especially seeing as how VarienForm is a part of Magento, which should be listed in your tags, which is an eCommerce application.
If you're just learning I suggest reaching out on the jQuery or Magento forums on how to use the applications or possibly for training.
Otherwise you will lose customers, get incorrect orders, or possibly be sued or arrested (depending on if you are processing credit cards) should your form mess up due to poor programming practices.
There are many websites where you can hire a freelancer to do just what you need for very low costs and avoid the hassles.

Loading Content best practices

I am sort of new to JavaScript and something has been bugging me.
Say I have some code like this:
$('button').on('click', function() {
var id = $(this).attr("id") // id being a file name sans extension
$('.content').load(id + '.php');
});
Everything works just fine, but something in the back of my head tells me that this is bad practice. Any thoughts?
It's fine but you can save some operations using this.id
$('button').on('click', function() {
$('.content').load( this.id +'.php');
});
I like this article here: https://stackoverflow.com/tags/jquery/info
You should not be using the ID attribute for this purpose. Instead, you should use a custom attribute. For instance:
<button data-url="mypage">Click me</button>
Then get that attribute instead of the ID.

Popup using jQuery?

I'm trying to do a pretty simple thing, I believe. I need to popup a success confirmation dialog after a user clicks to add someone to his friends list. Simply there's an add link on the page with the url (mysite.com/add/friendname). I needed to make issue this request asynchronously so I used jQuery.ajax built-in function to send the request. Take a look at the following code:
$(document).ready(function() {
$('.track_links').click(function() {
if (confirm("are you sure you want to track <firstname lastname>?")) {
$.ajax({
type: "GET",
url: this.href,
success: function() {
alert("Congratulation! you're now tracking <firstname lastname>");
},
error: function() {
alert("Oops! An error occured, plz try again later!");
}
});
return false;
}
else {
return false;
}
});
});
Now, here's what I need to do in short:
1- I need to use an already designed Html form as the success or failure confirmation message, instead of just alerting!
2- I also need to replace a placeholder (###username###) on that html page with the actual user name (firstname space lastname) which is the value of another field on the document. How to manipulate this html before poping it up on the client?
p.s: My Html/Javascript skills is totally awesome ;) (well, not really)!
For the first part
You can use the
show
function to show a div in the ajax success function.
$("#divResult").show();
if divResult is the id of the div to be shown
For the second part
you can get the value of first name and last name using
$("#txtFirstname" ).val();
and
$("#txtLastname" ).val();
if your first name text box id is txtFirstname and last name text box id is txtLastName
This is how I setup an Acknowledgement dialog, which could quickly be modified to be a confirmation for an action like yours.
http://professionalaspnet.com/archive/2009/06/02/Displaying-a-Confirmation-Dialog-with-the-JQuery-UI-Dialog.aspx
For the Form, I would suggest the html() Method, which injects raw HTML you have to provide. Since you already have it, you can give it to the Method via parameters.
For the Placeholder Part, I would suggest the val() Methods, coupled with Javascript's built-in regex functions.
If your placeholder is "###firstname###", then you should try something like
var firstname = jQuery('input#firstname').val();
var lastname = jQuery('input#lastname').val();
var text = jQuery('span#ThePlaceMyPlaceholderIsAt').text();
text = text.replace(/\#\#\#firstname\#\#\#/,firstname);
text = text.replace(/\#\#\#lastname\#\#\#/,lastname);
jQuery('span#ThePlaceMyPlaceholderIsAt').text(text);

Categories

Resources