This is my code :
jQuery(document).ready(function () {
jQuery(".jlk").live("click", function (e) {
e.preventDefault();
var task = jQuery(this).attr("data-task");
var post_id = jQuery(this).attr("data-post_id");
var nonce = jQuery(this).attr("data-nonce");
var currentClass = $(this).attr('class');
jQuery(".status-" + post_id).html(" ").addClass("loading-img").show();
jQuery.ajax({
type: "post",
dataType: "json",
url: wtilp.ajax_url,
data: { action: "wti_like_post_process_vote", task: task, post_id: post_id, nonce: nonce },
success: function (response) {
jQuery(".lc-" + post_id).html(response.like);
jQuery(".unlc-" + post_id).html(response.unlike);
jQuery(".status-" + post_id).removeClass("loading-img").empty().html(response.msg);
}
});
});
// Other users tooltip
jQuery("span.wti-others-like").live("mouseover", function () {
jQuery(this).children("span").show();
});
jQuery("span.wti-others-like").live("mouseout", function () {
jQuery(this).children("span").hide();
});
});
And I'm trying to add the conditional statement like this :
if (jQuery(".lc-" + post_id).html(response.like)) {
$(".action-unlike-" + post_id + " img").removeClass('opacity-none'); $(".action-like-" + post_id + " img").addClass('opacity-none'); alert('positive');
}
else if (jQuery(".unlc-" + post_id).html(response.unlike)) { $(".action-like-" + post_id + " img").removeClass('opacity-none'); $(".action-unlike-" + post_id + " img").addClass('opacity-none'); alert('negative'); }
But it always alert 'positive' like its not reading my conditions.
How can i accomplish this?
If (response.like == 'true') {do this} else if (response.unlike == 'true') {do this} ?
the jQuery HTML Method always returns true since it is a method to set HTML when you pass in a value.
See: http://api.jquery.com/html/
If your HTML is an input string your looking for the "Val" Method.
See: http://api.jquery.com/val/
if you literally want to check the HTML you need to check the .html() with NO Values passed in. Then do a string or other comparison of that HTML.
H i,
The if statement is a declaration ( it is setting html, not getting html and checking )
if (jQuery(".lc-" + post_id).html(response.like)) { ...
do you mean to do :
if (jQuery(".lc-" + post_id).html()===response.like) { ...
You should actually check the HTML value like $(".lc-" + post_id).html() with the response.like instead of setting the value in it. You can replace the code with the below one:
if ($(".lc-" + post_id).html() == response.like) {
$(".action-unlike-" + post_id + " img").removeClass('opacity-none');
$(".action-like-" + post_id + " img").addClass('opacity-none');
alert('positive');
} else if ($(".unlc-" + post_id).html() == response.unlike) {
$(".action-like-" + post_id + " img").removeClass('opacity-none');
$(".action-unlike-" + post_id + " img").addClass('opacity-none');
alert('negative');
}
Good luck!
Related
I am calling an Ajax function from another function and want to get the response and then parse the Json in order to assign it to new divs.
The call is made like this: thedata = GetChequesByBatchID(batchId); and this is the response:
Then, I am trying to loop through the response, but this is where the problem is. I am not sure how to get the response and loop through the thedata. This data should be assigned to the htmlFromJson so it will be inserted as group of divs in the TR. Any ideas?
My function:
<script type="text/javascript">
$(document).ready(function (params) {
var batchId;
var thedata;
var htmlFromJson = "";
$('.showDetails').click(function () {
// Show Details DIV
$(this).closest('tr').find('.details').toggle('fast');
batchId = $(this).data('batchid');
thedata = GetChequesByBatchID(batchId);
var json = jQuery.parseJSON(thedata);
$.each(json, function () {
htmlFromJson = htmlFromJson + ('<div class="ListTaskName">' + this.ChequeID + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAccountNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAmount + '</div>');
});
}).toggle(
function () {
// Trigger text/html to toggle to when hiding.
$(this).html('Hide Details').stop();
$(this).closest("tr").after("<tr class='456456'><td></td><td colspan = '999'>" + '<div class="zzss">' + htmlFromJson + '</div></td></tr>');
},
function () {
// Trigger text/html to toggle to when showing.
$(this).html('Show Details').stop();
//$(this).find('.zoom').remove();
$('tr.456456').remove();
}
);
});
</script>
My Ajax function:
<script type="text/javascript">
function GetChequesByBatchID(BatchID) {
var xss;
var qstring = '?' + jQuery.param({ 'BatchID': BatchID });
return $.ajax({
url: '<%=ResolveUrl("~/DesktopModules/PsaMain/API/ModuleTask/GetChequesByBatchID")%>' + qstring,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
jQuery.parseJSON(result); //the response
},
error: function (response) {
alert("1 " + response.responseText);
},
failure: function (response) {
alert("2 " + response.responseText);
}
});
return xss;
}
</script>
$.ajax is async operation (if you don't include async:false option which is not recommended) so your GetChequesByBatchID function immediately returns either $.ajax object or undefined. Correct usage of $.ajax is to call DOM changing methods from success or error parts of $.ajax.
I've researched this in depth on stackexchange and I don't think I am making a 'common' mistake, and the other answers have not solved this.
The problem is I am trying to append data to a DEFINITELY existing div of a certain ID. What I DO know is that the div is dynamically generated, and that is probably why it is hidden.
Despite using jquery on I cannot seem to get jquery to find the particular div.
Here is the code:
$(document).ready(function() {
function example_append_terms(data) {
var sender_id = data['sender_id'];
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = '<span data-lemma="' + v['key'] + '" class="lemma">' + v['name'] + '</span>';
$('#' + sender_id + ' .lemmas').append(html);
}
});
}
function example_get_options(data) {
$.ajax({
url: '/example/',
type: 'post',
data: data,
success: function(data) {
//alert(JSON.stringify(data))
example_append_terms(data)
},
failure: function(data) {
alert('Got an error dude');
}
});
return false;
}
$(document).on('click', ".example-synset-option", function() {
var synset = $(this).data('name');
var sender_id = $(this).attr('id')
example_get_options({
'synset': synset,
'sender_id': sender_id,
});
});
});
On clicking a certain div, an action is fired to "get options" which in turn runs an ajax function. The ajax function runs the "replacer" function example_append_terms.
Having tested up to example_append_terms the .each iteration is definitely working. But when I did tested $('#' + sender_id + ' .lemmas').length I continue to get 0.
Where is this jquery newb going wrong?
I fixed it by changing stuff...
For some inexplicable reason fetching the data attribute worked better than the id..
function intellitag_append_terms(data) {
var sender_id = $('*[data-location="'+data['sender_id']+'"] .lemmas');
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = $('<span data-lemma="' + v['key'] + '" class="label label-primary lemma">' + v['name'] + '</span>');
html.appendTo(sender_id)
//$('#' + sender_id).append(html);
}
});
}
If you have field with same class but different value I know there is a way to send value with $(this) in jquery but when returning the function result I want to update the specific field that has been clicked ? How I can do this $(this) is changing every field with the same class.
Class is auto generated in loop and I don't want to use different classes for every field.
There must be a way I am missing to achieve this
Here is my code.
$(".voteclick").click(function () {
var dynname = $(this).attr('name');
var votevalue = $(this).next().val();
$.ajax({
url:'http://localhost/wpcomnt/wp-content/themes/smart-mag-child/subrating.php',
type:"POST",
data:"dynname=" + dynname + "&" + dynname + "=" + votevalue + "&measure=" + $('#measure').val(),
dataType:'json',
success:function (mydata) {
if(votevalue == 'up') {
$(this).val('Agree: ' + mydata); // this must not change every .voteclick field it should change only the clicked one ?
}
else if(votevalue == 'down') {
$(this).val('Disagree: ' + mydata); // this must not change every .voteclick field it should change only the clicked one ?
}
//$(".voteclick").val('Agree: '+mydata);
},
error:function () {
$(".errormainbtn").slideDown();
}
});
});
Please read the comment next to this line $(this).val('Disagree: '+mydata);
there are many field's they are changed once I click it because the class is same, and auto generated please tell me a way by which I can change only the field I clicked the class is
".votelick"
As Wolff mentioned, you need to set context:this in the options for the ajax call. By default, in the success function, $(this) refers to the jqXHR object. If your ajax call is in an event handler, and you set context:this, $(this) in the success function will instead refer to the element that triggered the handler.
Here's a working example
$(".voteclick").click(function () {
var dynname = $(this).attr('name');
var votevalue ='up';//changed for example
$.ajax({
url:'test.php',//changed for example
type:"POST",
context:this, //this is the line you need to add
data:"dynname=" + dynname + "&" + dynname + "=" + votevalue + "&measure=" + $('#measure').val(),
dataType:'text', //changed from 'json' for my example
success:function (mydata) {
if(votevalue == 'up') {
$(this).val('Agree: ' + mydata);
}
else if(votevalue == 'down') {
$(this).val('Disagree: ' + mydata);
}
},
error:function () {
$(".errormainbtn").slideDown();
}
});
});
When testing this code, I purposely make it so the text returned from the ajax call is not 1. It reaches that else statement. The other statements execute, however, I never see an alert.
$.ajax ( {
type: "GET",
processData: false,
url: SITE_URL + "/system/check_user_project/" + session_id + "/" + cart_id + "/" + project_id + "/" + revision_id, //send data to this url
dataType: 'text',
})
.done (function(text) //When we have the data
{
if ("1" == text)
{
photos_populate_albums(session_id); //Call function to populate albums
if (typeof(project_id) !== "undefined" && project_id > 0) //If we have a project
{
mattes_add_default_matte(null, null, null, null, SITE_URL + "/system/xml/export/" + project_id + "?rid=" + revision_id);
}
else //otherwise...
{
mattes_add_default_matte(); //Add the default matte
}
common_change_step(document.getElementById("step1")); //Set the step to 1
}
else
{
$("#content").empty();
alert("Invalid project.");
window.location.href = (SITE_URL + "/user/mystuff/projects/?pid=" + partner_id);
}
});
UPDATE: I just realized I accidentally checked the box that asks if you want to keep receiving alerts from this webpage when it came up. Now I don't know where to undo it.
The code works. To reset the alert setting I had to re-open the tab.
Probably it's because you're doing a redirect just after the alert, and it is being supressed.
You may try replacing this:
$("#content").empty();
alert("Invalid project.");
window.location.href = (SITE_URL + "/user/mystuff/projects/?pid=" + partner_id);
For something like this:
$("#content").empty();
if (alert("Invalid project.") || true)
window.location.href = (SITE_URL + "/user/mystuff/projects/?pid=" + partner_id);
I am implementing the jQuery Easy UI plugin for checkbox tree. I am having a problem while loading the node data from my action class. The url property does not seem to accept the parameters -
If i give url: '/webapp/fetchData' i'm able to get the data. But if I give
url: '/webapp/fetchData?nodeId='+nodeId
my action class is not able to get the nodeId parameter.
Any solution?
Edit Code ported from comment:
onExpand: function(node) {
alert("inside expand");
var nodeId = node.id;
url: '/webapp/fetchdata?nodeId='+nodeId ;
}
Try this:
Using POST
function DoAction( id, name )
{
$.ajax({
type: "POST",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Using GET
function DoAction( id, name )
{
$.ajax({
type: "GET",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Here is what works for me:
Solution 1: from static HTML
javascript: on the caller side:
function onBeforeLoad (node, data)
{
data.Name=name;
}
HTML on the caller side:
<ul id="ScriptTree1" class="easyui-tree" lines="true" data-options="onBeforeLoad:onBeforeLoad, lines:true, processData:false" url="someural.php"/>
Solution 2: from dynamic code:
HTML
<ul id="ScriptTree2" class="easyui-tree" animate="true"></ul>
Javascript function triggered on any specific event:
function filltree ()
{
$('#ScriptTree2').tree
({
dataType:'json',
method:'POST',
lines: true,
processData:false,
onBeforeLoad: function (node,param) { param.Name=name; return true;},
onLoadError: function (dom)
{
if (!String.prototype.trim)
{
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
}
var sResponse = new String (arguments[0].responseText);
alert ('Compl: ' + arguments[1] + ' ' + arguments[2].description + ' ' + arguments[2].name + '\r\nAnswer:\r\n' + sResponse.trim() + '\r\nQuery: \r\n' + decodeURIComponent(arguments.caller.caller.caller[0].data));
return true;
},
url:'someurl.php'
});
}
and callee script:
someurl.php
<?
if ($_POST['Name'] != '') {$Name=$_POST['Name'];} else {$Name='';};
if ($_POST)
{
$kv = array();
foreach ($_POST as $key => $value)
{
$kv[] = "$key=$value";
}
$query_string = join(" | ", $kv);
}
echo '[{"id":100,"text":"params","state":"open","children":[{"id":104,"text":"query_string: '.$query_string.'","state":"open"}]}]';
?>