0

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
});

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks David, But I didnt understand the solution because I am new to JQuery
David I tried your code and is really helpful for me. Thank you very much :) One more doubt, Is there any way to avoid the json call from being fired if duplicate product are there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.