My code is as follows:
$('*[data-pickup]').change(function(){
var value = $(this).val();
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + $(this).attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + $(this).attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + $(this).attr("data-pickup") + "']").show();
})
The AJAX call shows a response when viewed through Firebug, which wasn't being refreshed on the screen, so I changed it to a simple "Hello" response, which still doesn't work.
If I comment out the .html("HELLO 2") line, it shows the once hidden div containing the HTML5 data element of data-pick=1 or data-pick=2, etc. (depending on what attr("data-pickup") is) which is automatically filled with "Test", so it shows "Test".
If I uncomment the .html("HELLO 2") line, the div once shown says "HELLO 2". But, in the case of the commented out .html("HELLO 2") line, it should be being updated from "Test" to "Hello" via the AJAX call, but it isn't. If I change the data* to a simple HTML id element and update all the code to #" + $(this).attr("data-pickup") + ", it works the exact same with the data attribute (the AJAX call doesn't update anything).
And when I make a var called "el" and make it equal to *[data-pick='" + $(this).attr("data-pickup") + "'], and then print it to the console it appears as: "[data-pick='1']" or "[data-pick='2']", etc. Then if I update all the code from $("*[data-pick='" + $(this).attr("data-pickup") + "']").whatever to $(el).whatever (thinking there might be a bug somewhere), it still works the same as before.
So, what have I done wrong? Why won't the div get refreshed via the AJAX call but it will after the AJAX call?
The problem is that 'this' in the success handler of the ajax function is the ajax function itself not the element that triggered the event handler. What you need to do is store the value of the element var el = $(this) then reference that whenever you want to access the element taking advantage of closures.
$('*[data-pickup]').change(function(){
var value = $(this).val();
var el = $(this);
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + el.attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + el.attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + el.attr("data-pickup") + "']").show();
})
Try this:
$('*[data-pickup]').change(function() {
var self = this;
var value = $(self).val();
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + $(self).attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + $(self).attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + $(self).attr("data-pickup") + "']").show();
})
this inside the success function is not the same this as elsewhere in the change handler.
Here's a solution :
$('*[data-pickup]').change(function(){
var value = $(this).val();
var $el = $("*[data-pick='" + $(this).attr("data-pickup") + "']");//here keep a reference to the element(s) of interest.
console.log(value);
$.ajax({
type: "POST",
cache: false,
url: "a.php?pickup",
data: {'X': value},
success: function(data) {
$el.html("HELLO");//$el is still available here, from the closure formed by the outer function
}
});
$el.show().html("HELLO 2");
});
Related
test.xml
<Bock1>
<No>123</No>
<RoomNo>10</RoomNo>
<UpdateTime>1230</UpdateTime>
</Block1>
run.js
$.ajax({
type: "GET",
url: test.xml,
dataType: "xml",
success: function (xml) {
$(xml).find('Block1').each(function () {
var updateTime = $(this).find("UpdateTime").text();
var no= $(this).find("No").text();
var roomNo = $(this).find("RoomNo").text();
var status = no + '<br/>' + roomNo + '<br/>' + updateTime;
});
}
});
$('<div>')
.attr({
'data-role': 'collapsible', 'data-collapsed': 'false', 'data-mini': 'true'
})
.html('<h4>' + item_name + '</h4><p>' + status + '</p>')
.appendTo(collapsibleset);
}
});
I'm using this to generate collapsibleset with xml data,
but status can't correctly fill into
<p> + status + </p>
status will get correctly inside ajax, but can't get to collapsibleset.
I've tried to use global variable, but get same situation.
How could I fill it in correctly?
I'm new to jquery & javaScript,
Thanks for any answers!!!
jQuery.ajax() is expecting string for the URL value.
Therefore your URL just needs wrapping in quotes.
Then your DOM reference of the
$('< div >')
is wrong.
To reference an element in JQuery, you have several options, but the easiest is to give an element an id and then reference that (think CSS)
$('div') would get all divs
$('div#my_id') would get this particular element:
I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}
I am using two drop down(first drop-down category and second drop-down sub category) in a page,both drop-down will be loaded dynamically, in which I will be selecting a value from first drop-down accordingly I have to load value to second drop-down.I has done that,but thing is that it will get done for first time.
But when I click on some other option in states drop-down, its not getting updated on second drop-down.
And My code is:
This piece of code is to get list of category while loading page ie under document.ready
$.ajax({
url : "../category/getCategory",
type : "post",
contentType : "application/json",
dataType : "json",
success : function(data) {
var categoryBOs = data.categoryBOs;
$.each(categoryBOs, function(key, value) {
$("#productCategory").append(
'<option value='+value.categoryId+'>'
+ value.categoryName
+ '</option>');
});
}
});
This part of ajax is to load sub category
$("#productCategory").on('change', function() {
alert($(this).val());
$.ajax({
url : "../category/getSubCategory",
type : "post",
cache : false,
dataType : "json",
data : "categoryId=" + $(this).val(),
success : function(data) {
var subCategoryBOs = data.subCategoryBOs;
$.each(subCategoryBOs, function(key, subCategoryBO) {
subCategories.push({lable:subCategoryBO.categoryId , value:subCategoryBO.categoryName});
$("#productSubCategory").append(
'<option value='+subCategoryBO.categoryId+'>'
+ subCategoryBO.categoryName
+ '</option>');
});
}
});
});
From what I see in your code you always append new entries, yet never remove old ones before. So possibly your list just keeps getting longer with new entries at its end? Try to remove the entries before append new ones:
$("#productSubCategory option").remove();
$("#productSubCategory").append(
'<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>');
In my experience $.each with $.append can get very slow at some amount of list entries. I would rewrite it in native javascript with for() and createElement().
Try adding $("#productCategory").empty() before the first $.each and $("#productSubCategory").empty() before the second $.each.
you need to make html in .each and append after .each end. No option change from first drop down you need to remove the previous on by using $("#productSubCategory option").remove();
$.ajax({
url: "../category/getCategory",
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
var categoryBOs = data.categoryBOs;
var html = '';
$.each(categoryBOs, function (key, value) {
html += '<option value=' + value.categoryId + '>' + value.categoryName + '</option>';
});
$("#productCategory").append(html);
}
});
$("#productCategory").on('change', function () {
alert($(this).val());
$.ajax({
url: "../category/getSubCategory",
type: "post",
cache: false,
dataType: "json",
data: "categoryId=" + $(this).val(),
success: function (data) {
var subCategoryBOs = data.subCategoryBOs;
var html = '';
$.each(subCategoryBOs, function (key, subCategoryBO) {
subCategories.push({ lable: subCategoryBO.categoryId, value: subCategoryBO.categoryName });
html += '<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>';
});
$("#productSubCategory").append(html);
}
});
});
Just simple thing you have to do here is that every time when you load sub-categories just place following before that .
$(dropdown).empty();
Thanks !
$("select#catname").change(function () {
// part of code
$("#subcatname").append($newOpt1);
// appending the category of dropdown
}
$("#subcatname").trigger('contentChanged');
// changing the contenet
}
});
$("select#subcatname").change(function () {
// something changes after trigger in dropdown
});
// removing the content or clearing the content after selecting
$("#subcatname").empty();
});
});
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();
}
});
});
I have next javascript code:
function getLetterOfResponsibilityNote(dialogNoteLink, visitCountryName) {
$.ajax({
type: "GET",
url: "/Admin/Applications/GetLetterOfResponsibilityNote/?selectedCountryName=" + visitCountryName,
cache: false,
success: function(data) {
if (data != "") {
dialogNoteLink.dialog();
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
}
}
});
}
I want to call it, for example, 5 times and get data from server, then I will display it in dialog. But I get one Jquery UI Dialog with message. Problem is that script doesn't pause while dialog is open.
If I write instead of it:
dialogNoteLink.dialog();
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
with alert() - it works fine!
How I can resolve this problem?
That is how JavaScript alert works. If you want to make the calls wait for the dialog to close, then you will have to make the subsequent calls in a callback after the dialog is closed. You should do something like this -
var arrayofNotesAndCountryNames = [{
"dialogNoteLink" : link1,
"visitCountryName" : "country1"
},{
"dialogNoteLink" : link2,
"visitCountryName" : "country2"
},{
"dialogNoteLink" : link3,
"visitCountryName" : "country3"
}];
var currentIndex = 0;
function getLetterOfResponsibilityNote() {
var dialogNoteLink = arrayofNotesAndCountryNames[currentIndex].dialogNoteLink;
var visitCountryName = arrayofNotesAndCountryNames[currentIndex].visitCountryName;
$.ajax({
type: "GET",
url: "/Admin/Applications/GetLetterOfResponsibilityNote/?selectedCountryName=" + visitCountryName,
cache: false,
success: function(data) {
if (data != "") {
dialogNoteLink.dialog({close : function(){
currentIndex++;
if (currentIndex < arrayofNotesAndCountryNames.length){
getLetterOfResponsibilityNote();
}
}
});
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
}
}
});
}
getLetterOfResponsibilityNote();
The dialog should be shown from the callback of the query to the server.
There are no blocking function or dialogs on JQuery.