I wrote this code for like and dislike for my posts in my blog:
$(".p_like").each(function() {
$(this).click(function() {
ids = $(this).find(".pl_id").val();
t = $(this);
if ($(this).find(".bi").hasClass("bi-heart-o")) {
gfd = 'p';
$(this).find(".bi").addClass("bi-heart");
$(this).find(".bi").removeClass("bi-heart-o");
} else {
gfd = 'm';
$(this).find(".bi").addClass("bi-heart-o");
$(this).find(".bi").removeClass("bi-heart");
}
$.ajax({
type: "POST",
url: "likes.php",
data: {
ids: ids,
k: gfd
},
cache: false,
success: function(result) {
t.find(".nol").html(result);
}
});
});
});
And when I use the code, in some of the post it likes the post and then dislike it.
What is the problem of the code and how can I fix it?
use this :
$(".p_like").find(".bi").click(function(){
ids = $(this).siblings(".pl_id").val();
t = $(this);
if($(this).hasClass("bi-heart-o")){
gfd='p';
$(this).addClass("bi-heart");
$(this).removeClass("bi-heart-o");
}else{
gfd='m';
$(this).addClass("bi-heart-o");
$(this).removeClass("bi-heart");
}
$.ajax({
type: "POST",
url: "likes.php",
data: {ids:ids,k:gfd},
cache: false,
success: function (result) {
t.siblings(".nol").html(result);
}
});
});
and you maybe used this file two time!
Jquery by default query all given selectors ( here .p_like ). It's not needed to iterate over them explicitly.
Jquery methods are chanable. after you select one element you could call methods one after another: $element.addClass(...).removeClass().css(...)
Also you've leaked three variables: ids, t, gfd. maybe they're got overriten before you send em out to server so declare them to make em private to your event handler function.
$('.p_like').click(function() {
var $t = $(this),
$bi = $t.find('.bi'),
$nol = $t.find('.nol'),
ids = $t.find('.pl_id').val(),
gfd;
if ( $bi.hasClass('bi-heart-o') ) {
gfd = 'p';
$bi.addClass('bi-heart').removeClass('bi-heart-o');
} else {
gfd = 'm';
$bi.addClass('bi-heart-o').removeClass('bi-heart');
}
$.ajax({
type: 'POST',
url: 'likes.php',
data: {
ids: ids,
k: gfd
},
cache: false,
success: function(result) {
$nol.html(result);
}
});
});
Related
I have concern regarding of javascript function, The question is there any indicator to determine if the javascript function still on going or still running? because I have problem on inserting hundred of items inserting in the database. I want to condition if the javascript function still on going the insertion will stay until the condition met the else if the javascript function is not running or done, it will automatically redirect to the other page.
In my onclick of my jquery I insert the javascript function.
$('#add_to_cart').on('click', function() {
orders = [];
menu = undefined;
$('.tbody_noun_chaining_order').children('tr').each(function() {
$row = $(this);
if ($row.hasClass('condimentParent')) {
if (menu) {
orders.push(menu);
}
menu = {
'total': $row.find('.total').text(),
'name': $row.find('.parent_item').text(),
'customer_id': customer_id,
'condiments': {
'Item': [],
'Qty': [],
'Total': []
}
};
} else if ($row.hasClass('editCondiments')) {
menu.condiments.Item.push($row.find('.child_item').text());
menu.condiments.Qty.push($row.find('.condiments_order_quantity').text());
menu.condiments.Total.push($row.find('.total').text());
}
});
if (menu) {
orders.push(menu);
}
storeOrder(orders)
});
My Javascript Function
function storeOrder(data) {
var customer_id = $('#hidden_customer_id').val();
var place_customer = $('#place_customer').text();
$id = "";
$total_amount = $('.total_amount').text();
$append_customer_noun_order_price = $('.append_customer_noun_order_price').text();
$tax_rate = $('.rate_computation').text();
$delivery_rate = $('.del_rate').text();
var sessionTransactionNumber_insert = localStorage.getItem('sessionTransactionNumber');
$.ajax({
url:'/insert_customer_order_properties',
type:'POST',
data:{
'hidden_customer_id': customer_id,
'hidden_customer_address': place_customer,
'sessionTransactionNumber': sessionTransactionNumber_insert
},
success:function(data) {
$id = data[0].id;
$.ajax({
url:'/insert_customer_payment_details',
type:'POST',
data:{
'hidden_customer_id': customer_id,
'total_amount': $total_amount,
'customer_sub_total': $append_customer_noun_order_price,
'tax_rate': $tax_rate,
'id_last_inserted': $id
},
success:function(data) {
localStorage.removeItem('sessionTransactionNumber');
}
})
}
})
for (var num in orders) {
$.ajax('/insert_wish_list_menu_order', {
type: 'POST',
context: orders[num].condiments,
data: {
'append_customer_noun_order_price': orders[num].total,
'append_customer_noun_order': orders[num].name,
'customer_id': customer_id
},
success: function(orderNumber) {
$order_number = orderNumber[0].id;
$.ajax({
url:'/insert_customer_order_details_properties',
type:'POST',
data:{
'order_number': $order_number,
'data_attribute_wish_order_id': $id,
},
success:function(data) {
console.log(data);
}
})
if (orderNumber !== undefined) {
$.ajax('/insert_wish_list_menu_belong_condiments', {
context: orderNumber,
type: 'POST',
data: {
'ParentId': orderNumber,
'Item': this.Item,
'Qty': this.Qty,
'Total': this.Total
},
success: function(result) {
console.log(result);
},
})
}
}
})
}
}
I am trying to hide 2 div on Ajax Success by following code
$(".editButton").click(function () {
var self = this;
var membershipid = $(this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembershipDetail","User")',
data: { "MembershipID": membershipid },
success: function (data) {
$('#ddlStoreUpdate').val(data["fk_Store_ID"]);
$('#TxtTitleUpdate').val(data["MembershipTitle"]);
$('#TxtDescriptionUpdate').val(data["MembershipDescription"]);
$('#TxtTimeFrameUpdate').val(data["MembershipTimeFrame"]);
$('#TxtMembershipMinUpdate').val(data["MembershipMinVisit"]);
$('#chkUpdate').prop('checked', data["MembershipGroundLevel"]);
$('#HiddenMembershipID').val(membershipid);
if (data["MembershipGroundLevel"] == true)
{
alert("True");
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
}
else
{
alert("false");
$("#RowTimeFrame").show("slow");
$("#RowMinFrame").show("slow");
var storeid = $("#ddlStore").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("GetTimeFrame","User")',
data: { 'StoreID': storeid },
success: function (data) {
$("#TxtTimeFrame").val(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
},
error: function (data) {
alert(JSON.stringify(data));
}
})
$("#myModalUpdate").modal('show');
});
If condition is working well, but Div(s) doesn't hide
If I remove $(self).closest() from second div, first div hides all well, Issue is with multiple div
You can use class to hide it, like this:
$(".resetValueTo0").val(0);
$(".divToHide").hide();
Therefor, you don't need to do this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
You might want to try this:
Replace this code:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
To this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").each(function(){
$(this).hide();
});
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").each(function(){
$(this).hide();
});
I'm trying to change the class and text of the button that was clicked based on the result from an ajax post. The page has many buttons, none have IDs (although I could add them if it's for sure needed). I have the following javascript:
$('.ph-button').click(function () {
var selected = [];
$(this).closest('tr').each(function () {
$(this).find('td').each(function() {
selected.push($(this).html));
})
})
console.log(selected);
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
//need the if statements here I think
console.log(data);
}
});
});
It works and gives me a 0 or 1 as data. I need to change the class to class='ph-button ph-btn-blue and the text to Watched if data is 0 and change the class to class='ph-button ph-btn-grey and the text to Watch if data is 1.
I tried using $(".ph-button").toggleClass("ph-button ph-btn-blue"); but it changed the class of all the buttons on the page and didn't seem to do it like I need.
I'm guessing toggleClass isn't what I need and i'm not sure how to address the button that was clicked instead of all of them. Here are the two possible buttons:
<td><button class='ph-button ph-btn-blue'>Watched</button></td>
<td><button class='ph-button ph-btn-grey'>Watch</button></td>
SOLUTION:
$('.ph-button').click(function () {
var selected = [];
var btn = $(this);
$(this).closest('tr').each(function () {
$(this).find('td').each(function(){
selected.push($(this).html());
})
})
console.log(selected);
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
console.log(data);
if (data == 1) {
btn.toggleClass("ph-btn-grey ph-btn-blue").text('Watched');
}
if (data == 0) {
btn.toggleClass("ph-btn-blue ph-btn-grey").text('Watch');
}
}
});
});
set a temporary variable referencing the button, so you can use it later on in your AJAX success callback:
$('.ph-button').click(function () {
var selected = [];
var btn = $(this);
$(this).closest('tr').each(function () {
$(this).find('td').each(function(){
selected.push($(this).html());
})
})
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
if(data == "0"){
btn.toggleClass("ph-button ph-btn-blue").text('Watched');
}
}
});
});
I am learning javascript and was trying out some code below. I am calling the below javascript object as
var client=new atrmsClient('6247543');
var val=client.getRosterData();
I get an error on this line:
var postData= {"cmdShow": "Show", "txtEmpId" : EmpId, "txtPeopleSoft_Id": EmpId, "__VIEWSTATE": viewState }
EmpId is undefined. Can anyone tell me what I am doing wrong ?
"use strict";
function atrmsClient(EmployeeId)
{
this.EmpId=EmployeeId;
var siteUrl="http://wncrpma011.japa.ad.aexp.com/TransportRoster/EmployeeReport.aspx";
var getViewState=function()
{
$.ajax
({
type: "GET",
url: siteUrl,
dataType: 'html',
processData: false,
xhrFields:
{
withCredentials: true
}
})
.done(ExtractViewState).fail(errorFunc).always(alwaysFunc);
return "";
};
var SendPostRequest=function(viewState)
{
var postData= {"cmdShow": "Show", "txtEmpId" : EmpId, "txtPeopleSoft_Id": EmpId, "__VIEWSTATE": viewState }
$.ajax
({
type: "POST",
url: siteUrl,
data: postData,
dataType: 'html',
processData: false,
xhrFields:
{
withCredentials: true
}
})
.done(parseRosterData).fail(errorFunc).always(alwaysFunc);
};
var parseRosterData=function(data)
{
console.log(data);
};
var ExtractViewState=function(data)
{
var rawResponse=data;
var viewState=$(rawResponse).find('input[name=__VIEWSTATE]')[0].value;
console.log(viewState);
SendPostRequest(viewState);
};
var errorFunc=function()
{
};
var alwaysFunc=function()
{
};
this.getRosterData=function()
{
var viewStateVal=getViewState();
console.log("calling");
return "";
};
}
You never declare a variable called EmpId.
The only EmpId you have is a property of the atrmsClient instance.
Add
var EmpId = EmployeeId;
… or just use EmployeeId as that is still in scope.
Another solution could be:
function atrmsClient(EmployeeId) {
var that = this;
this.EmpId=EmployeeId;
var SendPostRequest=function(viewState) {
var postData= {"cmdShow": "Show", "txtEmpId" : that.EmpId, "txtPeopleSoft_Id": that.EmpId, "__VIEWSTATE": viewState }
// ...
};
}
It depends if you need EmpId to be available from outside, i.e. using client.EmpId. If yes, then this solution should suit your needs. Otherwise, use #Quentin's.
Is there a more efficient way to write the following? I need to loop through objList and pass the UnqKey to wfrmPrint. On success of that I then have to loop though the Pages. I am looping through the pages and unqkeys by passing a integer and checking to see if it is less than the length. I tried to use .when.apply taken from http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects, but it was loading the unqkeys and then the pages.
//sample objList
[
{
"UnqKey": 1,
"Pages": [
"wfrmSet1Page1.aspx",
"wfrmSet1Page2.aspx"
]
},
{
"UnqKey": 2,
"Pages": [
"wfrmSet2Page1.aspx",
"wfrmSet2Page2.aspx",
"wfrmSet3Page2.aspx",
"wfrmSet4Page2.aspx"
]
}
]
function Loop(iListIndex) {
var obj = objList[iListIndex];
if (iListIndex < objList.length) {
jQuery.ajax({
type: "GET",
url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + obj.UnqKey, //load session that is used in wfrmSet1Pages.. or wfrmSet2Pages..
success: function () {
AddPages(obj, iListIndex, 0);
}
})
} else {
alert('Done');
}
}
function AddPages(obj, iListIndex, iPageIndex) {
if (iPageIndex < obj.Pages.length) {
jQuery.ajax({
type: "GET",
url: obj.Pages[iPageIndex] + '?Print=1', //load html
async: true,
success: function (html) {
iPageIndex++
AddPages(obj, iListIndex, iPageIndex);
},
error: function () {
alert('Failed!');
iPageIndex++
AddPages(obj, iListIndex, iPageIndex);
}
});
} else {
iListIndex++
Loop(iListIndex);
}
}
You might be able to do something like this,
function getData(arr,arrindex) {
$.ajax({
type: "GET",
url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + arr[arrindex].UnqKey
}).then(function(data){
var deferredObj = $.Deferred(), defArr = $.map(arr[arrindex].Pages,function(page){
return $.ajax({type: "GET", url: page + '?Print=1'});
});
$.when.apply(null,defArr).done(deferredObj.resolveWith).fail(deferredObj.resolveWith);
return deferredObj.promise();
}).done(function(){
arrindex++;
if (arr[arrindex]) {
getData(arr,arrindex);
}
else {
alert("done!");
}
}).fail(function(){
alert("FAIL!");
});
}
getData(objList,0);
It gets each wfrm sequentially, and when each one finishes, requests all of the pages for that one at once. Somewhat of a combination between your loop and a deferred $.when
Edit: fixed $.map argument order