Update a google spreadsheet by row id - javascript

I need to update the information in a specific row in the google spreadsheets.
I get the data from the inputs in the front end, and the number of the row that I need to update from the userID.
I tried to use ajax, sending the URL of the form response, but what it does is adding a new row.
Is there a way to send the data and the row ID, so I can update that row in the google sheet?
I use tabletop.js to get/read the data from the google sheets, but dont know if it work to update
function Update() {
var ID = userID;
$.ajax({
url: 'https://docs.google.com/forms/d/e/key/formResponse?',
data: {
"entry.2085722051": v_NAME
},
type: "POST",
dataType: "xml",
success: function (d) {
},
error: function (x, y, z) {
$('#success-msg').show();
$('#form').hide();
}
});
}
I expect the function Update() to update the row [number] on the google sheet by using the [number ID] of the user.
But what actual happens is that the function save the data in a new row.

Related

Remember the state of clicked button with AJAX

I have different cards displayed on an app, the information is coming from the database in a loop. I have the option to put a 'redeem button' on cards if it's something a user can use just once. When the user clicks the redeem button, I get in the database the information (card name, clientID). Then, I made another AJAX call to get the information from the database and what I want is to check if the clientID and the carndame are already in the database then delete it just for that user. I don't wanna use localStorage or cookies because if the user delete the cookies they would see the card again and I don't want this to happen.
-- AJAX CALL TO POST --
$(`#promotion-container .promo${i} .redddButt`).click(function(e){
e.stopPropagation();
var esc = $.Event("keyup", { keyCode: 27 });
$(document).trigger(esc);
$('#deletePromo').on('click', function(){
if (eventName && customerID)
$(`#promotion-container .promo${i}`).remove() // this removes it but if you reload the page it appears again.
})
$('#just-claimed-popup2').addClass('reveal');
var theDiv = document.getElementById("card-just-claimed");
var content = document.createTextNode(eventName);
theDiv.appendChild(content);
$.ajax({
type: 'POST',
url: '/api/promotions_redemption',
crossDomain: true,
dataType: 'json',
data: {
eventName : eventName,
dateReedem : dateReedem,
}
});
})
--AJAX CALL TO GET INFO FROM DATABASE --
let success = function(res, eventName) {
let cardData = res['cardData'] //cardData is the info from database
for(i=0; i<cardData.length; i++){
let nameEvent = cardData[i]['event_name']
let customerID = cardData[i]['customer_id']
let clicked_button = cardData[i]['clicked_button']
let eventName1 = promotions['event_name'] // getting the names of all cards displayed
if(customerID && nameEvent == eventName1){
$(`#promotion-container .promo${i}`).remove(); // HERES THE PROBLEM
}
}
}
$.ajax({
type: 'GET',
url: '/api/promotions-check',
crossDomain: true,
dataType: 'json',
success: success,
});
The problem is that my conditional on my GET call is successful but it forgets the id of the card, meaning that when I try to console.log the id of the promo it comes as 0, instead of the actual number, so it's forgetting the information of the cards rendered and don't know what to delete.
What would be the best way to achieve the card to be deleted? Do I need to do it in the click event too? and if yes, can I have 2 Ajax calls in the same function?
If you change the approach you would be able to achieve this more easily. When you send a post request to delete the item or redeem the code in your case, upon success return same data and upon some condition just delete the item from DOM. On page load it shouldn't load whichever was redeemed.
I personally don't see a point of doing another GET to delete the code which was redeemed.
$.ajax({
type: 'POST',
url: '/api/promotions_redemption',
crossDomain: true,
dataType: 'json',
data: {
eventName : eventName,
dateReedem : dateReedem,
},
success: function(result){
//on success, ie when the item is deleted -> delete from the DOM.
}
});

Send a List to JavaScript

This is my layout
I want to update in relativaly "real-time" let's say every 10 seconds or so... the badge that says approved will say the getStatus()
My problem is that i need to fetch data from a List and I have no idea how to send all this data to the JavaScript file.
runningContainers is a List and i need to get runningContainers.getName() and runningContainer.getStatus() for every one in the list and send it to the javascript.
I just need a way to pass all the data to the javascript so I can update the badges relativally to that name.
Java
try {
DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost("tcp://localhost:2375")
.withDockerConfig("/")
//.withRegistryUsername("profile")
//.withRegistryPassword("profile")
.build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
List<Container> runningContainers = dockerClient.listContainersCmd()
.exec();
JavaScript
$.ajax({
type: 'post',
url: 'Containers',
success: function () {
},
error: function() {
}
});
});

jQuery - Add row to datatable without reloading/refreshing

I'm trying add data to DB and show these data in same page using ajax and jQuery datatable without reloading or refreshing page. My code is saving and retrieving data to/from database. But updated data list is not showing in datatable without typing in search box or clicking on table header. Facing same problem while loading page.
Here is my code
//show data page onload
$(document).ready(function() {
catTable = $('#cat_table').DataTable( {
columns: [
{ title: "Name" },
{ title: "Level" },
{ title: "Create Date" },
{ title: "Status" }
]
});
get_cat_list();
});
//save new entry and refresh data list
$.ajax({
url: 'category_save.php',
type: 'POST',
data:{name: name,level: level},
success: function (data) {
get_cat_list();
},
error: function (data) {
alert(data);
}
});
//function to retrieve data from database
function get_cat_list() {
catTable.clear();
$.ajax({
url: 'get_category_list.php',
dataType: 'JSON',
success: function (data) {
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
] );
});
}
});
}
The solution is here - for DataTable server side data source enabled
.draw() will cause your entire datatable to reload, say you set it to show 100 rows, after called .row().add().draw() > datatable will reload the 100 rows again from the server
I wasted an hour trying to find any solution for this very old question, even on DataTable official support there is no good solution suggested ...
My solution is
1- call .row().add()
2- do not call .draw()
3- your row must have an Id identifier to use it as a selector (check the rowId setting of the datatable)
4- after calling .row().add(), the datatable will have the row added to it's local data
5- we need to get this row from datatable object and transform it to HTML using the builtin method .node()
6- we gonna prepend the result HTML to the table :)
All that can be done in two lines of code
var rowData = someRowCreatedByAnAjaxRequest;
myDataTableObject.row.add(rowData);
$("#myTable-dt tbody").prepend(myDataTableObject.row(`tr#${rowData.Id}`).node().outerHTML)
Thanks ☺
From the documentation,
This method will add the data to the table internally, but does not
visually update the tables display to account for this new data.
In order to have the table's display updated, use the draw() method, which can be called simply as a chained method of the row.add() method's returned object.
So you success method would look something like this,
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
]).draw();
});

Removing rows from DataTables from a Ajax call

I have a DataTables (datatables.net) table setup which have a custom column where I have icons for different kind of actions.
One of these actions is deletion and I don't want to reload the data into the table so I was wondering if there was any function built-in for removal of datatable rows locally (so my script deletes the actual post on the server and then I can remove the same row in my datatable).
After some research I've found "fnDeleteRow" but I don't know how to use it. In my script I have an ajax call and on the success event I want to delete the row but I have trouble identifying what row that had the link was clicked. This below is where I am at the moment:
function Delete(id) {
$.ajax({
url: "ajax/ajax.php",
type: "POST",
data: {
action: "delete",
id: id
},
success: function(response){
oTable = $('#table').DataTable();
var row = oTable.closest('tr');
var nRow = row[0];
oTable.DataTable().fnDeleteRow(nRow);
},
error: function (response) {
alert("Something went wrong.");
console.log(response);
},
});
};
This prints the following in the console:
TypeError: oTable.closest is not a function
I'm pretty new to jQuery and don't know how to implement this to my case. Do anyone of you have any idea? I'm guessing that even if my script within the success event had the right syntax, it won't have a clue what row had the button/link that was clicked at the first place. How do I ensure it does?
EDIT:
This is how my datatable is initiated, in case it is confusing:
function DrawTable() {
$('#table').DataTable( {
"cache": false,
"columnDefs": [
{
"targets": [ 0, 1 ],
"visible": false,
"searchable": true
}
]
} );
}
I was told to use a jsfiddle, so I've uploaded one. Never used this site and my markup is generated but I manually did one.
https://jsfiddle.net/nqeqxzub/9/
Maybe it's too late, but I will put it anyway. After two days of searching all over the web, I find a simple solution without any DataTable functions
<td>
<button type="button" id="{{$lead->id}}" name="{{$lead->id}}" onclick="deleteRecord(this.id,this)" data-token="{{ csrf_token() }}">Delete</button>
</td>
this cell above has an onclick function that takes 2 parameters, the first one (this.id) is the id of the button (that comes from the DB, and will be passed to ajax to update the DB), and the second one (this) which is the index of the button itself (later we will extract the index of the row from it)
function deleteRecord(mech_id,row_index) {
$.ajax({
url:"{{action('MechanicController#destroy')}}",
type: 'get',
data: {
"id": mech_id,
"_token": token,
},
success: function ()
{
var i = row_index.parentNode.parentNode.rowIndex;
document.getElementById("table1").deleteRow(i);
}
});
}
Now in the success function, I have used 2 lines:
the first one is to extract the row index from the button (2 parents because we have to pass from the parent of the button, in this case , and then the parent of the which is the row)
the second line is a simple delete row of our index from table1 which is the name of my table

How to show jqgrid data dynamically using entityframwork with sql data?

hi bosses i have used sql pivot to show employeewise product in grids. when i execute the query in management studio it is working fine but the problem is when i want to show data in jqgrid in with dynamic rows and columns it is not working. I am new in jqgrid.
here is my controller action method
public ActionResult FindOrderByEmployeeCall()
{
var query = (from fo in db1.FindOrderByEmp1()
select fo).ToList();
return Json(query, JsonRequestBehavior.AllowGet);
}
my ajax method for show data in jqgrid in view page is
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Invoice/FindOrderByEmployeeCall/",
dataType: "json",
success: function(result){
var colD = result.couponStripList,
colM = result.colModelList;
$("#list").jqGrid({
//datatype: 'local',
data: "",
gridview: true,
colModel :colM,
height: "auto",
loadComplete: function(data){
alert('loaded');
},
loadError: function(xhr,status,error){
alert('error');
}
});
},
error: function(x, e){
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
});
</script>
and my sql pivot query is
ALTER proc [dbo].[FindOrderByEmp1]
as
BEGIN
SET FMTONLY OFF;
DECLARE #query nvarchar(max)
DECLARE #Product NVARCHAR(max),#Product1 NVARCHAR(max)
SELECT #Product = STUFF(( SELECT distinct'],['+ rtrim(ProdId) FROM OrderDetails ORDER BY '],['+ rtrim(ProdId) FOR XML PATH('')), 1, 2, '')+']'
set #Product1 =SUBSTRING(( select distinct ',IsNull(['+rtrim(ProdId)+'],0) as ['+rtrim(ProdId)+']' from OrderDetails for xml path('')),2,8000)
SET #query =
'SELECT EmpId,'+#Product1+' FROM
(
SELECT d.ProdId,m.EmpId,isnull(convert(int,d.Qty),0.0) as oqty
FROM OrderMaster m inner join OrderDetails d on m.OrdId=d.OrdId
)t
PIVOT (SUM(oqty)
FOR ProdId
IN ('+#Product+')) AS pvt'
EXECUTE (#query)
end
Please help me..
JqGrid supports the pivot grid see below link
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:pivotsettings
it loaded only once if you want to change the rows and column at runtime use GridUnload before creating and loading the grid.
jqGrid GridUnload/ GridDestroy

Categories