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?
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.
Related
first of all I got a huge JSON file of data with products returned from the server. I managed to do pagination on the "index" page using the "page" parameter passed to the URL, however, the search button is an AJAX event.
My question is is there a way to do pagination just with the JSON data given from the Server (PHP) side, essentially "cutting",e.g. 150 products to 10 a page, or do I have to change the logic of the search and print of products?
Is there a way to make a pagination based only on returned JSON data that is being added to a variable and then printed out?
JS:
function searchAjax()
{
var text = $("#name").val();
var id = getGroupId(); // AJAX CALL FOR GETTIN A SPECIFIC GROUP that was selected.
var html = ``;
var page = 0;
$.ajax({
url: './models/ajaxSearch.php',
method: 'get',
dataType: 'json',
data: {
text: text,
id: id
},
success: function(data)
{
html += `<h2>Results: </h2>`;
if (data.length == 0)
{
html += `<h4>There are no such Products. Try Again!</h4></div>`;
}
else
{
for(let i = 0; i<data.length; i++)
{
html +=`<div>`+data[i].call+`</div>`//ADDING data to html variable e.g.
}
$('#divId').html(html);
btnChange(); //For editing each article.
},
error: function(error,xhr, statusText)
{
console.log(id);
console.log(text);
alert("There Was An Error "+xhr.status+" "+statusText);
alert(error);
}
});
}
The PHP just returns JSON data with one SELECT.
ANSWER
Managed to find the solution by adding an event on the pagination buttons that have page numbers on their "href" attribute and getting that attribute and forwarding it to a seperate Ajax Call in order just to refresh the where the content was being printed.
Managed to find the solution by adding an event on the pagination buttons that have page numbers on their "href" attribute and getting that attribute and forwarding it to a seperate Ajax Call in order just to refresh the where the content was being printed.
I have a large number of inputs on a page, each input is disabled (and hidden) by default unless a checkbox is checked. Checking a related checkbox enables the input for a user to type an amount - that works fine.
After I've typed an amount into a given box and I shift my blur focus to something else (indicating I'm done with this input), I'm looping through every visible input to check if it has an amount in it and then sending an ajax request to update the back-end (this also works but maybe approach is wrong?).
What doesn't work is when I loop through more than 5-10 checkboxes, it seems to be extremely slow or simply doesn't send the ajax requests.
Code the listens for an enabled/visible amount box to change:
$(document).on("blur", ".dollar-amount", function(){
MainPage.amountInputListener('add');
});
Here is the foreach loop, which updates each associated user's backend data with the amount in the visible field:
var MainPage = {
amountInputListener: function (type) {
$(".dollar-amount:visible").each(function () {
//Get the employee being updated
var empID = $(this).data('empid');
//get the amount
var amount = $(this).val();
//Send update request to backend
$.ajax({
type: "POST",
url: "update/amount?empid=" + empID + "&amt=" + amount + '&type=' + type,
dataType: "html"
});
});
},
}
The HTML for the input:
<input type="text" name="dollar_hour_amountX" value="0" class="form-control dollar-amount disabled" data-empid="1" tabindex="-1" disabled>
Note: dollar_hour_amountX, X is a dynamic number related to the row's employee ID. data-empid is the same dynamic number, also used in the for loop.
Things I've tried to ensure the loop works properly:
Adding async: false. This allows it to work 100% of the time, but it's extremely slow the more inputs that are added.
Adding a timeout of 100-1000ms around the entire function, this simply delays the round-trip time of the Ajax call.
I'm open to Vanilla JS suggestions if it aids in making the calls to my back-end much faster and consistent.
// capture the passed in event
$(document).on("blur", ".dollar-amount", function(e){
// give the element to the method
MainPage.amountInputListener(e.target, 'add');
});
var MainPage = {
// accept the element on the arguments
amountInputListener: function (element, type) {
// use the element in place of `this`
//Get the employee being updated
var empID = $(element).data('empid');
//get the amount
var amount = $(element).val();
//Send update request to backend
$.ajax({
type: "POST",
url: "update/amount?empid=" + empID + "&amt=" + amount + '&type=' + type,
dataType: "html"
});
},
}
Does not make sense to update everything, just update what changes.
$('.dollar-amount').on("change", function () {
console.log(this.value, $(this).data('empid'))
// make the one Ajax request
})
Or change your backend to be able to handle multiple things being sent up at once so you are not hammering the backend with a bunch of calls.
"I'm looping through every visible input to check if it has an amount in it and then sending an ajax request to update the back-end (this also works but maybe approach is wrong?)."
I would strongly recommend you change this approach. I suspect it will fix your issues. Don't loop through all of these each time. There is no need. Simply, on blur, just check if this specific input has changed, and then send an ajax call ONLY if that specific one was edited.
Just pass "this" into the amountInputListener as an argument, and then get rid of the above "each" function. The rest would be the same. Instead of $(this), just pass the argument value that represents "this" from the event.
The first and foremost thing is using a get http verb request for update should be avoided.
This is not per standard, usually get requests are used to retrieve data.
And the next thing is instead of making an ajax call for each element with callname .dollar-amount and visible, it is better to declare a global variable above the foreach block of type array of objects and then add each item in the block to that global variable and then finally make an ajax request after the for block execution is done
amountInputListener: function (type) {
var objList = [];
$(".dollar-amount:visible").each(function () {
//Get the employee being updated
var empID = $(this).data('empid');
//get the amount
var amount = $(this).val();
//Send update request to backend
objList.push({
'empId':empId,
'amt':amount,
'type': type
});
});
$.ajax({
type: "post",
url: "update/amount"
dataType: "application/json",
data:{'data':objList}
});
},
}
This way you can send all data in one shot to server and it really helps in the performance.
Note: code is just to give you an idea.
I have a Javascript AJAX function that can send some data (to a MongoDB database)f
. The database only consists of one document which keeps track of the total amount of questions answered and also the number of questions answered correctly.
The function can take either of these numbers (updated in different places in the code), but how do I check which number it is inside of the function? It would look something like this:
function updateQuestionsProgress(number) {
//TODO Check which of the two numbers is sent
$.ajax({
type: "POST",
url: "/statistics/quick_test",
data : theNumber,
error:function(msg, string){
console.log(msg);
},
success:function(data){
alert("sd");}
});
Knowing which number it is, I could then update it accordingly in that URL middleware.
Am I better of just doing two different functions instead? Seems very inconvenient if you have a very large database and you just want to update part of a document.
What you need is the caller of the function to tell you which number it is.
You can send a string a bool flag (since it's just two options), or an object.
function updateQuestionsProgress(dataObj) {
//TODO Check which of the two numbers is sent
$.ajax({
type: "POST",
url: "/statistics/quick_test",
data : dataObj,
When you call updateQuestionsProgress(dataObj) you can pass whatever object you like to the function. E.x. var dataObj = {"answers" : 5, "correct_answers": 3} and anything else you need.
I have a simple list populated via MySql via Ajax / Json. The list is just a title and description and every entry has a checkbox. I need the checkbox, once clicked, to push to database that it is clicked. How would you go about doing that?
[btw...
right now since I have a setTimeInterval on my SQL data to deliver the list on the fly it automatically resets my checkbox. I'm assuming that if I record that my checkbox has been set via boolean in the SQL that there could be a way to keep it checked...]
I'm new at this and I'm just playing around and trying to learn so this information is entirely theoretical.
You can use the on() function to listen to checkbox clicks.
$(function() {
$(document.body).on('click', 'input.mycheckbox', function() {
var checkbox = $(this);
var checked = checkbox.attr('checked');
$.ajax('service.url', {
type: 'post',
data: {action: 'checkbox-select', id: checkbox.attr('id'), checked: checked},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
// Revert
checkbox.attr('checked', !checked);
}
});
}
});
Feel free to ask if you need any clarification or if this doesn't fit your situation.
EDIT:
The data parameter of the AJAX function is an object that will be posted to your PHP page. When your PHP code is running, $_POST will be an array containing the values we passed. So, $_POST['action'] will be 'checkbox-select', $_POST['id'] will get the ID, and $_POST['checked'] will be true or false depending on whether the checkbox was selected or deselected. Your method of getting the ID in the Javascript will probably change; I just put checkbox.attr('id') to give you an idea.
When learning PHP it can be helpful to dump the responses from the server on the client-side. Example PHP code:
if($_POST['action'] == 'checkbox-select']) {
$checkbox = $_POST['id'];
$checked = $_POST['checked'];
// Your MySQL code here
echo 'Updated';
}
echo 'Code ran';
I edited the JS to show the result from the server.
We're working on a big ASP.NET\VB.NET website project.
I need to populate three dropdownlists. To last two are independent of the previous ones. The population data comes from an SQL Server. I'd have no problem doing this with code-behind with post back but we don't want any PostBacks so I started to develop this in Ajax\jQuery.
Preface:
The dropdownlist's values and text are both different and tied up to the database. Server-side, the function called by the Ajax method returns a list of list of string with the values and text, i.e.
list[0][0] = "ID0"
list[0][1] = "VP"
The list is well built and returns the right value taken from the database.
Problem:
Now I want to populate the dropdownlist from the list sent to the ajax success response and I have a hard time doing it.
Here's the ajax part of it so far
$.ajax(
{
type: "POST",
url: "Projet.aspx/GetDir",
data: "{VP:'" + dd_effort_vp + "',DP:'" + dd_effort_dp + "',Direction:'" + dd_effort_d + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
// This code works if only a simple list of string is
// returned from the server-side called function.
var cars = response.d;
$.each(cars, function(index, value) {
$('#<%= dd_effort_directionp.clientid()%>').append(
$('<option></option>').val(value).html(value));
});
}
This code works IF and only IF I have a simple list of string returned by the server side function.
Now I want to modify it to get the values from the List of List of String (in var cars and assign the right ID and Description to each item in the newly populated DropdownList.
If your server is returning to you a list of list of strings, that will come to jQuery via an array, whose elements are arrays. You need to figure out/know which element of that array—which, again, will contain a list of strings—needs to go with your dropdown. If you want the 0th array, you would do:
var cars = response.d[0];
Also, it looks like you're going through a lot of trouble to find the relevant dropdown lists since asp.net is giving them unpredictable names.
Consider giving each drop down a unique class, via the CssClass property, and then select it that way.
<asp:DropDownList runat="server" CssClass="dd_effort_directionp"></asp:DropDownList>
$.each(cars, function(index, value) {
$(".dd_effort_directionp").append(
$("<option />").val(value).html(value));
});