remove rows from google spreadsheet using ajax only - ajax

i want to remove entire rows from Gsheet using simple jquery my code is:
var arr = {
"deleteDimension": {
"range": {
"sheetId": sheetId,
"dimension": "ROWS",
"startIndex": 276,
"endIndex": 277
}
}
};
$.ajax({
type: 'delete',
headers: { Authorization: "Bearer " + auth, 'content-type': 'application/json' },
// data: JSON.stringify(arr),
url: 'https://sheets.googleapis.com/v4/spreadsheets/' + sheetId +'/sheetname!A276:A277' ,
success: function (r) {
console.log(r)
;
}, error: function (r) {
console.log(r)
}
});
I think the url or post data param is not correct. any help will appreciate.

Modification points:
In your script, sheetId of range property is the sheet ID. And, at the endpoint, please use Spreadsheet ID.
You can see about Spreadsheet ID and Sheet ID at this official document.
In order to use "deleteDimension", please use "Method: spreadsheets.batchUpdate".
In this case, the POST method is used.
Please use data: JSON.stringify(arr) for including the request body.
When these points are reflected in your script, it becomes as follows.
Modified script:
var spreadsheetId = "###"; // Please set your Spreadsheet ID here.
var sheetId = "###"; // Please set your sheet ID here.
var auth = "###"; // Please set your access token.
var arr = {
"requests": [{
"deleteDimension": {
"range": {
"sheetId": sheetId,
"dimension": "ROWS",
"startIndex": 276,
"endIndex": 277
}
}
}]
};
$.ajax({
type: 'POST',
headers: { Authorization: "Bearer " + auth, 'content-type': 'application/json' },
data: JSON.stringify(arr),
url: 'https://sheets.googleapis.com/v4/spreadsheets/' + spreadsheetId + ':batchUpdate',
success: function (r) {
console.log(r);
}, error: function (r) {
console.log(r);
}
});
When this script is run, row 277 of the sheet of Spreadsheet is deleted using "Method: spreadsheets.batchUpdate".
Note:
This modified script supposes that your access token can be used for using "Method: spreadsheets.batchUpdate". Please be careful about this.
References:
Method: spreadsheets.batchUpdate
DeleteDimensionRequest

Related

Sending a json object with ajax post

Im working on a project, where we try to exchange different parameters between the UI and a RestAPI via AJAX. The RestAPI defines how the data has to look:
I tried to solve it this way:
$(document).ready(function(){
$("#submit").click(function(){
var credentials = [
{user_name: $("#uname").val(),
password: $("#pwd").val()
}
];
alert(credentials);
$.ajax({
url:"../rest/user/login",
type:"POST",
data:JSON.stringify({credentials: credentials}),
success: function(){
window.location.href = "startrackhome.html";
},
error: function error(response){
try{
var json = JSON.parse(response.responseText);
if(typeof json.message === 'undefined'){
throw new Error("Response json has no message");
}
else{
alert(json.message);
}
}
catch(ex){
alert("unexpected error (code:" + response.status +")");
}
}
});
});
});
The alert shows this: [object Object]
And I always get an error message (error: 400), which means that I mus have made a mistake and I think the format I'm sendig is wrong but I dont know how to fix it.
I hope you can help me! :)
I made some changes to your code :
// credentials is an object
var credentials = {
user_name: $("#uname").val(),
password: $("#pwd").val()
}
alert(credentials);
$.ajax({
// check this url seems a bit off
url: "../rest/user/login",
type: "POST",
data: {
credentials: credentials
},
success: function() {
window.location.href = "startrackhome.html";
},
error: function error(response) {
try {
var json = JSON.parse(response.responseText);
if (typeof json.message === 'undefined') {
throw new Error("Response json has no message");
} else {
alert(json.message);
}
} catch (ex) {
alert("unexpected error (code:" + response.status + ")");
}
}
});
in my case it makes this request :
fetch("https://stackoverflow.com/posts/rest/user/login", {
"headers": {
"accept": "*/*",
"accept-language": "",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Linux\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://stackoverflow.com/posts/72620005/edit",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "credentials%5Buser_name%5D=test&credentials%5Bpassword%5D=test",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
credentials[user_name]: test
credentials[password]: test
which seems good, if the server needs a json, you can stringify the credentials, which gives this paylaod :
credentials: {"user_name":"test","password":"test"}

Youtube search autocomplete not working with Framework 7

I am trying to use Framework 7 autocomplete feature with youtube search API v3. I had used search api for autocomplete using Jquery UI. Framework 7 has also Ajax autocomplete feature. But my code is not working with Framework 7.
Here is my youtube search autocomplete js code for jquery UI, that works 100% and shows up video search suggestion on text input
//code for auto complete using jquery UI works perfect
jQuery( "#vid-search" ).autocomplete({
source: function( request, response ) {
//console.log(request.term);
var sqValue = [];
jQuery.ajax({
type: "POST",
url: "http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1",
dataType: 'jsonp',
data: jQuery.extend({
q: request.term
}, { }),
success: function(data){
console.log(data[1]);
obj = data[1];
jQuery.each( obj, function( key, value ) {
sqValue.push(value[0]);
});
response( sqValue);
}
});
},
select: function( event, ui ) {
setTimeout( function () {
youtubeApiCall();
}, 300);
}
});
And here is my youtube search autocomplete code with framework 7, Doest show up video search suggestions on text inpute..
var autocompleteDropdownAjax = myApp.autocomplete({
input: '#autocomplete-dropdown-ajax',
openIn: 'dropdown',
preloader: true, //enable preloader
valueProperty: 'id', //object's "value" property name
textProperty: 'name', //object's "text" property name
limit: 20, //limit to 20 results
dropdownPlaceholderText: 'Try "JavaScript"',
expandInput: true, // expand input
source: function (autocomplete, query, request, response, render) {
var results = [];
if (query.length === 0) {
render(sqValue);
return;
}
// Show Preloader
autocomplete.showPreloader();
// Do Ajax request to Autocomplete data
$$.ajax({
type: "POST",
url: "http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1",
dataType: 'jsonp',
data: jQuery.extend({
q: request.term
}, { }),
success: function (data) {
// Find matched items
console.log(data[1]);
obj = data[1];
jQuery.each( obj, function( key, value ) {
sqValue.push(value[0]);
});
response( sqValue);
// Hide Preoloader
autocomplete.hidePreloader();
// Render items by passing array with result items
render(sqValue);
}
});
},
select: function( event, ui ) {
setTimeout( function () {
youtubeApiCall();
}, 300);
}
});
That is because the jSon result should be in a special format, the result rendered by the API looks like:
["funn",["funny vines","funny videos 2016","funny videos","funny","funnel vision","funny cat videos","funny fails","funny pranks","funny cats","funny songs"]]
First parent array has the query you typed, second child array has the result array, you must push the child array to the result.
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i])
}
And here is the result:
Full code:
var autocompleteDropdownAjax = myApp.autocomplete({
input: '#autocomplete-dropdown-ajax',
openIn: 'dropdown',
preloader: true, //enable preloader
valueProperty: 'value', //object's "value" property name
textProperty: 'text', //object's "text" property name
limit: 20, //limit to 20 results
dropdownPlaceholderText: 'Search Youtube',
expandInput: true, // expand input
source: function(autocomplete, query, render) {
var results = [];
var returned = [];
if (query.length === 0) {
render(results);
return;
}
// Show Preloader
autocomplete.showPreloader();
// Do Ajax request to Autocomplete data
$$.ajax({
url: 'http://suggestqueries.google.com/complete/search?client=firefox&ds=yt',
method: 'GET',
crossDomain: true,
dataType: 'json',
//send "query" to server. Useful in case you generate response dynamically
data: {
q: query
},
success: function(data) {
// Find matched items
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i])
}
// Hide Preoloader
autocomplete.hidePreloader();
// Render items by passing array with result items
render(results);
}
});
}
});
I hope this helps :)

Use select2 ajax data to update hidden inputs

I am having trouble updating hidden inputs using data retrieved from Select2 Ajax.
Please see my code:
var select2_town = $('.select-test select').select2({
ajax: {
url : ajax_var.url,
dataType: 'json',
type: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
};
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
id: item.id, //eg 1149
town: item.place_name, //eg Reading
county: item.county, //eg Berkshire
country: item.country,
data: item
};
})
};
},
cache: true;
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: function (item) { return ('<p>' + item.town + ' - ' + item.county + '</p>'); },
templateSelection: function (item) { return (item.town); },
});
This code works fine for me. My issue is what happens after a value is selected.
I would like to update my hidden input ids "#town","#county" and "#country" with town,county and country respectively through an 'change' event.
I have seen many SO examples but they all stop at $(this).select2('data')[0];but do not expand on it.
Weird thing is that the following script displays the correct value in console log. but ALWAYS only apply the object id to #country.
select2_town.on('change', function() {
var obz = $(this).select2('data')[0].country;
console.log(obz);//displays Reading in console
$("#country").attr("value",obz); //displays 1149
});
This actually works.
I had another function that was adding the ID hidden in another file. I deleted that and then the script worked as I wanted it to.
Regards
Thanks

Dojo XhrPost set name for posted json object on server

I have a Dojo ajax request and i am posting the data as json however the data is not reaching the server in json format. I am also not able to see the JSON tab in the browsers Net option of the console. I need the data in json format on the server.
Ajax Request
var someData = [{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}];
function SendData() {
var xhrArgs = {
url:'processData',
postData: someData,
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load:function(data){
console.log('data was posted');
},
error:function(error){
console.log(error);
}
};
dojo.xhrPost(xhrArgs);
Screenshot of server details
I would like the JSON data under to appear in the following format under with the name MyData. How is this format possible on the server?
JSON
MyData [Object{id:"1",age:"44",name:"John"},
Object{ id:"2",age:"25",name:"Doe"},
Object{ id:"3",age:"30",name:"Alice"}]
SOURCE
{"MyData":[{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}]}
Actually url:'' is empty in your Ajax call. Please provide action url,
for suppose
url: "AddTrackServlet"
After playing around with the variable i saw it could be declared
var someData = [{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}];
var formData = {MyData:someData}
function SendData() {
var xhrArgs = {
url:'processData',
postData: dojo.toJson(formData),
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load:function(data){
console.log('data was posted');
},
error:function(error){
console.log(error);
}
};
dojo.xhrPost(xhrArgs);

jQuery DoubleSelect/Cascade/Dependent/WalkRight Select Menus w/ Ajax Support?

Where you can pick an item from a <select> menu and then it populates a second <select> menu.
It goes by too many names and there are too many implementations. I'm looking for an up-to-date one (works well with the latest version of jQuery) that can pull the data using Ajax.
Can anyone recommend a good plugin?
// simple code but can be improved for need
function getListBoxValue(obj) {
obj = $.extend({
url: "",
bindObj: null,
emptyText: "exception",
postValues : {},
onComplete: function () { return true; },
onError: function () { return false; }
}, obj);
$.ajax({
url: obj.url,
data: obj.postValues,
type: "POST",
dataType: "JSON",
success: function (json) {
var options;
$.each(json, function (i, e) {
options += "<option value='" + e.Value + "'>" + e.Text + "</option>";
});
$(obj.bindObj).html(options);
obj.onComplete(obj);
},
error: function (e, xhr) {
$(obj.bindObj).html("<option value='-1'>" + obj.emptyText + "</option>");
obj.onError(obj);
}
});
}
// server response data json
[{ "Value": 1, "Text": "text 1 " },{ "Value": 2, "Text": "text 2"}]
getListBoxValue({
url: responseJsonDataURL, // example
bindObj: $("select#YourID"), // example
emptyText:"exception text", // example
postValues: {"id": 45}, // example
onComplete: _onCompleteFunction, // optional
onError: _onErrorFunction // optional
})

Resources