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>');
}
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:
So the problem is that I'm loading JSON files from url into my html and it's working perfectly besides for the fact that it shows the information twice..
Does anyone know why this is the case?
Here's the Jquery/Javascript code that I use to load the JSON into my html.
$.ajax({
url: 'http://datatank4.gent.be//bevolking/totaalaantalinwoners.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
i = 0;
var access;
var url;
$(data).each(function(index, value) {
wijkname = value.wijk;
year = value.year_2010;
i++;
$('#pagewrap2').append(
'<div class="dataond col col-xxs-12 col-md-3"> <h2> ' + wijkname + '</h2><p>' + year + '<div id="maps">' + "<iframe width='100%' height='100%' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&q="+ encodeURIComponent( wijkname + ' ' + 'Gent' ) +"&output=embed'></iframe>" + '</div>' + '</p></div>'
);
});
}
});
First check the response of this ajax call.
If the response look fine maybe you're making the ajax call twice.
For example when you add an event listener twice. (add off() function before click() if you're using jquery)
I've found the problem. Really stupid but I linked my file twice in my index.html...
Thanks everyone for your replies.
<script type="text/javascript">
$(document).ready(function() {
var categoriesId = [];
$.getJSON("http://datatank4.gent.be//bevolking/totaalaantalinwoners.json", function(data) {
$.each(data, function(index, item) {
categoriesId.push(item.wijk);
}
);
for (i = 0; i < categoriesId.length; i++) {
alert(categoriesId[i]);
var newInProductPriceDiv = document.createElement('div');
newInProductPriceDiv.setAttribute('id', "recentlyViewedProductPriceDiv" + i);
newInProductPriceDiv.setAttribute('class', "subcategoryListPriceDiv");
newInProductPriceDiv.innerHTML = newInProductPriceDiv.innerHTML + categoriesId[i];
document.getElementById('pagewrap2' + i).appendChild(newInProductPriceDiv);
}
}
);
}
);
</script>
if you have any confusion then tell me ok . and if you not get your exactly output then also tell me.
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();
});
});
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");
});
Guys I have a function which uses ajax call to retrieve data dynamically based upon a value in div. Now lastNoticeID value in the function is not getting updated as its not in any loop..thus it keeps repeating the same data..
CODE :
function callMoreData() {
var lastNoticeID = $('#hiddenLastNoticeID').val();
$.ajax({
type: "GET",
url: "/api/values/getnotice?num=" + lastNoticeID,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
$.each(data, function (index, value) {
BindNotice(value);
});
},
error: function (x, e) {
alert('problem while fetching records!');
}
});
}
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input id="hiddenLastNoticeID" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
As you can see in the code above, I am retrieving value from the above div and then passing it to webApi url... Now this is running fine and on the first scroll I get the values but then the function keeps repeating the same values over and over again i.e. var lastNoticeID is not getting updated. How do I get it to update per scroll event?
btw divNotices has the same html code as BindNotice function.
Use classes instead:
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
And then:
var lastNoticeID = $('.hiddenNotice').last().val();
Or, you could just store the LastNoticeID in a variable:
var lastNoticeID = 0;
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
lastNoticeID = values.LastNoticeID;
}
It would seem that you are adding more elements of the same ID. ID's are supposed to be single instance and Jquery will therefore only grab the first instance in the DOM. (Which is why $('#hiddenLastNoticeID').val(); is the same every time)