Sebb
Sebb

Reputation: 911

jQuery - Transfer Data by ID from PHP to JavaScript + jQuery

I'm having a list with a lot of entries (100+) identified by an (MongoDB-)ID. Each of the entries is in an html-table and has a checkbox. When the user now selects a group, I need to query the server if each of the entries is in the specific group. The query for getting the membership isn't to heavy, but I can't execute it 100+ times, that's too much load.

Currently I have php code for getting the group membership (too long to post) and following javascript code, which is executed whenever the select is changed:

$('checkbox[data-type="group"]').each(function(idx, val) {
  // get the ID and set it checked/unchecked
});

My problem is: How can I query performantly the Server once and then check for every ID if the entry is in the selected group?

Upvotes: 0

Views: 38

Answers (1)

Cooper Maruyama
Cooper Maruyama

Reputation: 1612

Your question is a little hard to understand, but I think you should post a JSON list and post that in one query, and handle the iteration server-side, like so:

id_list = {};

$('checkbox[data-type="group"]').each(function(idx, val) {
  the_id = //get the id into a variable somehow;
  id_list[the_id] = val;
});

$.ajax({
  url: "some url",
  dataType: "json",
  type: "post",
  data:id_list
}).done(function(data) {
 //using returned data, set each to check/unchecked

 //assuming that the returned data had format of id:boolean, and the boolean defines whether it should be checked (e.g. {1: true, 2: false, 3: false}   )
 $.each(data, function(index,value) {
  if (value == true) {
    $('checkbox#'+index).attr('checked',true);
  } else {
    $('checkbox#'+index).attr('checked',false);
  }
});

If this doesn't answer your question then please rephrase your question with more detail.

Upvotes: 1

Related Questions