Reputation: 79
I have the following code to get a json response using ajax. From the response I am taking the "prodId". More responses are coming to the page when the page load and each response will contain different "prodId"s. I need to check the "prodId" is already recieved or not. I have some divs already in the page with the above recieved prodId.
I am new to handling array. One thing to remember that all the json responses are coming in the page load itself. So after getting the first response I need to check any duplicate response is coming and should avoid it. Please help me out
$.ajax({
type: "GET",
dataType: "jsonp",
success: function(data){
prodId = data.prodID;
//populate this data in page
});
Upvotes: 0
Views: 163
Reputation: 129812
Add something to the elements that will help you identify them based on prodID
. Element ID would be a good fit here, but in case you're using something else for that, just add another class.
newElement.addClass('prod-' + data.prodID);
Then when deciding whether to add a new element to the DOM, just check if:
if($('.prod-' + data.prodID).length == 0) { ... }
You could of course make a local dictionary and perform the lookup in memory rather than in DOM:
var addedProducts = {};
Each time you add an element to the DOM:
addedProducts[data.prodID] = newElement;
When deciding whether to add an element to the DOM:
if(!addedProducts.hasOwnProperty(data.prodID)) { ... }
The complete code could look something like this:
success: function(data){
prodId = data.prodID;
if($('.prod-' + prodId).length == 0) {
var newElement = $('<div/>').html(some content as determined by data);
newElement.addClass('prod-' + prodId);
newElement.appendTo('body');
}
});
Of course, how you create your elements and where you append them depend on what you want to achieve. I trust you have this figured out under your "populate this data in page" comment. All you need to add is the addClass
call, and the wrapping if
.
Upvotes: 1