Help with Javascript for update with a checkbox

Hello I am trying to update several records marked with a checkbox in a table the data I am trying to update is a connection field, the code that I currently have in addition to putting the checkbox in the table is supposed to update the records but only update a record and that does it if the field that I update is not a connected field.left the attached code

var addCheckboxes = function(view) {

// add the checkbox to to the header to select/unselect all
$('#' + view.key + '.kn-table thead tr').prepend('<th><input type="checkbox"></th>');

$('#' + view.key + '.kn-table thead input').change(function() {
$('.' + view.key + '.kn-table tbody tr input').each(function() {
$(this).attr('checked', $('#' + view.key + '.kn-table thead input').attr('checked') != undefined);
});
});

// add a checkbox to each row in the table body
$('#' + view.key + '.kn-table tbody tr').each(function() {
$(this).prepend('<td><input type="checkbox"></td>');
});
}

var updateRecords = function(id, records, data) {
$.ajax({
url: ' https://api.knackhq.com/v1/objects/object_143/records/' + id,
type: 'PUT',
/***** CHANGE TO YOUR OWN APPID AND API KEY HERE *****/
headers: {'X-Knack-Application-ID': 'xxx', 'X-Knack-REST-API-Key': 'xxx'},
data: data,
success: function(response) {
if ( records.length ) {
// Every time a call is made, the array is shifted by 1.
// If the array still has a length, re-run updateRecords()

updateRecords(records.shift(), records);
} else {
// We know all records are processed when length = 0
alert('Update complete!');
Knack.hideSpinner();
}
}
})
}

/**** CHANGE VIEW_ID TO YOUR OWN VIEW ID ****/
$(document).on('knack-view-render.view_2465', function (event, view) {

// Add an update button
$('<button id="update"">Update</button>').insertAfter('.view_2465');
//$('<input type="text" id="update""></input>').insertAfter('.view_2465');

// Add checkboxes to our table
addCheckboxes(view);

// Click event for the update button
$('#update').click(function () {

// We need an array of record IDs
var record_ids = [];

// Populate the record IDs using all checked rows
$('#' + view.key + ' tbody input[type=checkbox]:checked').each(function() {
record_ids.push($(this).closest('tr').attr('id')); // record id
});

Knack.showSpinner();

// Define the fields you want to update
var data = {
field_1875: "alv"
};

// Use the first ID in the array, then pass in the rest of the array
updateRecords(record_ids.shift(), record_ids, data);

})
});

Again, thanks for your help, sometimes this solution works, however when it does not work, there are two possible solutions, 1. activate and inactivate the user, 2 create the user again. -.-

@Manuel

Make Sure that the user role you're logged into has permission to edit the form you're sending the data to.

If it does then log out, clear your cache/cookies, re-log in and it should work.

I'm getting this error with some users and I have no way to fix it

After trying it hard and doing some minimal fixes at the end this is functional and works wonders, many many thanks for your help

this is the code

var data = {
field_2225: window.location.href.split('/')[window.location.href.split('/').length - 2] // getting record ID in the URL
}

var addCheckboxes = function(view) {
// Add the checkbox to to the header to select/unselect all
$('#' + view.key + '.kn-table thead tr').prepend('<th><input type="checkbox"></th>');
$('#' + view.key + '.kn-table thead input').change(function() {
$('.' + view.key + '.kn-table tbody tr input').each(function() {
$(this).attr('checked', $('#' + view.key + '.kn-table thead input').attr('checked') != undefined);
});
});
// Add a checkbox to each row in the table body
$('#' + view.key + '.kn-table tbody tr').each(function() {
$(this).prepend('<td><input type="checkbox"></td>');
});
}

$(document).on('knack-view-render.view_2465', function(event, view) {

$("#view_2465 tr td.field_1869").html('<input type="checkbox">');
$("#view_2465 tr th.field_1869").html('<input type="checkbox" id="check_uncheckall">');
$("#update").remove();
$("#view_2465").prepend("<button id='update1' type='button' style='padding: 0 10px; line-height: 22px;' class='kn-button-menu'>Update</button>");
});

$('#check_uncheckall').live("click",function() {
$('#view_2465' + '.kn-table tbody tr input').each(function() {
$(this).attr('checked', $('#check_uncheckall').attr('checked') != undefined);
});
});

var done_invoice1 = 0;
$('#update1').live("click", function() {
done_invoice1 = 0;
var objects_selected = $('#view_2465 tbody input[type=checkbox]:checked');
Knack.showSpinner();
for (var x = 0; x < objects_selected.length; x++) {
updateRcd_voice2($(objects_selected[x]).parent().parent().attr("id"));
}
});

function updateRcd_voice2(id) {
var data = {
field_1869: window.location.href.split('/')[window.location.href.split('/').length - 2]
}

$.ajax({
url: 'https://api.knack.com/v1/pages/scene_1231/views/view_2465/records/' + id,
type: 'PUT',
/***** CHANGE TO YOUR OWN APPID AND API KEY HERE *****/
headers: {
'Authorization': Knack.getUserToken(),
'X-Knack-Application-Id':'xxxxx',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
success: function(response) {
done_invoice1 = done_invoice1 + 1;
var expectedNum = $('#view_2465 tbody input[type=checkbox]:checked').length;

console.log(done_invoice1, expectedNum);
if (done_invoice1 == expectedNum) {
Knack.hideSpinner();

location.reload(); //optional reload screen
}
},
error: function(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
};

Received an email with a question for this but for some reason it's not posted.

Here's my best guess to solve your problem.

It says the error is on line 57. I don't know what line 57 is in your code but I'll assume it's this line by the error:

url: 'https://api.knack.com/v1/pages/scene_325/views/view_556/records/' + id,

So, when it tries to put together a url for the ajax call, 'id' is undefined.

Most likely you have the wrong view specified on this line:

var objects_selected = $('#view_556 tbody input[type=checkbox]:checked');

Make sure that view matches the view # where you have your checkboxes.

It should then be able to grab the attribute 'id' for each selected record.

Hope that helps. Good luck

PS: If you have more syntax errors, copy and paste your code into jshint.com --It will tell you where the errors are. Linters are great for tracking down syntax errors.

Este Comentario no Funciono no se publico nunca -.-

 

Thank you very much for your help.

I will try to use this and I will tell you.

Thank you again :D

Here is another example you might find helpful.

This has some minor improvements over the code you're using which was it's source.

1. Better error handling

2. Using tokens rather than API keys for Auth - (Don't expose you API keys if you can help it )

*Must change URL to a form your user has access to that edits this record rather than the object url used for object based calls

*The function names have been changed so as not to interfere with other code running. That's not really important.

In this example - I'm getting a record.ID from the URL -this represents the Invoice each line item will be connected to after being checked.

var data = {
field_362: window.location.href.split('/')[window.location.href.split('/').length - 2] // getting record ID in the URL
}

The API call sends that record.id (for the invoice) to the connection field (362)on each line item that has been checked.

//checkbox script for occasional Agency invoicing

// Function that adds checkboxes
var addCheckboxes = function(view) {
// Add the checkbox to to the header to select/unselect all
$('#' + view.key + '.kn-table thead tr').prepend('<th><input type="checkbox"></th>');
$('#' + view.key + '.kn-table thead input').change(function() {
$('.' + view.key + '.kn-table tbody tr input').each(function() {
$(this).attr('checked', $('#' + view.key + '.kn-table thead input').attr('checked') != undefined);
});
});
// Add a checkbox to each row in the table body
$('#' + view.key + '.kn-table tbody tr').each(function() {
$(this).prepend('<td><input type="checkbox"></td>');
});
}


/* CHANGE VIEW_ID TO YOUR OWN VIEW ID */
$(document).on('knack-view-render.view_556', function(event, view) {

$("#view_556 tr td.field_342").html('<input type="checkbox">');
$("#view_556 tr th.field_342").html('<input type="checkbox" id="check_uncheckall">');
$("#update").remove();
$("#view_556").prepend("<button id='update1' type='button' style='padding: 0 10px; line-height: 22px;' class='kn-button-menu'>Assign to this Invoice</button>");
});

$('#check_uncheckall').live("click",function() {
$('#view_556' + '.kn-table tbody tr input').each(function() {
$(this).attr('checked', $('#check_uncheckall').attr('checked') != undefined);
});
});

var done_invoice1 = 0;
$('#update1').live("click", function() {
done_invoice1 = 0;
var objects_selected = $('#view_556 tbody input[type=checkbox]:checked');
Knack.showSpinner();
for (var x = 0; x < objects_selected.length; x++) {
updateRcd_voice2($(objects_selected[x]).parent().parent().attr("id"));
}
});

function updateRcd_voice2(id) {
var data = {
field_362: window.location.href.split('/')[window.location.href.split('/').length - 2]


};


// the object in call is essentially line item

$.ajax({
url: 'https://api.knack.com/v1/pages/scene_325/views/view_556/records/' + id,
type: 'PUT',
/***** CHANGE TO YOUR OWN APPID AND API KEY HERE *****/
headers: {
'Authorization': Knack.getUserToken(),
'X-Knack-Application-Id': Knack.application_id,
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
success: function(response) {
done_invoice1 = done_invoice1 + 1;
var expectedNum = $('#view_556 tbody input[type=checkbox]:checked').length;

console.log(done_invoice1, expectedNum);
if (done_invoice1 == expectedNum) {
Knack.hideSpinner();

//location.reload(); //optional reload screen
}
},
error: function(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
}

Hi Manuel,

I 'd really have to be on a chat with you to troubleshoot it.

Also, there is a bit of a language barrier prohibiting me from really fully understanding these posts.

First step is to open the inspector in chrome.

Add some console logs to make sure your code is executing and to test your variables to see what's in there,.

See if any errors are popping up in the console. If not.

click on the network tab and look at the API call.

Was it sent?

what does the payload look like?

What response code was returned from Knacks API?

If all of this sounds like greek to you;

Create a codementor account and hire someone with high javascript and jquery marks to help you out. you will probably get your issue solved for $50-$75 and learn a lot while doing so.

I would offer to help but I don't want to ruffle any feathers by soliciting work on these boards.

Best of luck with it. Justin

Hello, thank you very much for your help and for your answer.
When I select several records as seen in the image and try to update them, only the first one is updated.
You have also reason the field that I try to enter is not static, but I tried it with a static data that I found in the other table in order to see if it worked but apparently it is not, you could help me by showing me how it should be make the call to the record Id that I need from the other table please.
Thank you very much for your help.

I can probably help you if you rephrase

"the code that I currently have in addition to putting the checkbox in the table is supposed to update the records but only update a record and that does it if the field that I update is not a connected field.left the attached code"

I think I might understand where you're going with this.

Connection fields need to be updated with the record ID of the connected record, not it's identifier value.

So, if that value is not static, ie 'it changes' then you might need to add a call first to GET the record ID you need from another table or object, save as a var and then put that var in your payload.

If the record is static ie 'not changing' / always 'alv' then find the record titled 'alv' in the builder and inspect it using chrome inspector. you will see a string of #'s and letters, this is the record ID. Substitute that record.id for the text 'alv' and it should work.

Good luck