tabulator: Loading Google Sheets data via Ajax - ajax

I'm trying for a few days now and I can't figure out how to load a Google Sheets document into Tabulator.
What I did:
Getting the JSON data back from the Google Sheets doc
https://spreadsheets.google.com/feeds/list/1Ze31_SUFd0ZyqeG1mt1qrEU61onnYhmI9mR1BC1pM7Y/od6/public/values?alt=json
Added the Tabulator library on this page
https://www.avpec1910.nl/pages/98/Alle-baanrecords/
But still getting these errors:
Ajax Load Error - Connection Error: 0
Ajax Load Error: Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}
And how can I get the fields 'entry' > 'gsx$naam' -- 'Joan van den Akker - KAV Holland' into a column (the key 'gsx$naam' has an object '{"$t":"Joan van den Akker - KAV Holland"}' as value, but I only need the name...)
My Tabulator code:
var table = new Tabulator("#baanrecords", {
ajaxConfig:{
mode: 'no-cors',
method:'GET',
credentials: 'same-origin',
headers: {
'Content-type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
},
ajaxURL: 'https://spreadsheets.google.com/feeds/list/1Ze31_SUFd0ZyqeG1mt1qrEU61onnYhmI9mR1BC1pM7Y/od6/public/values?alt=json',
height:'400px',
layout:'fitColumns',
autoColumns:true,
placeholder:'De records worden geladen, een moment...',
index: 'onderdeelnaam',
columns:[
{title:"Onderdeel", field:"gsx$onderdeelnaam", sorter:"string", width:200},
{title:"Prestatie", field:"gsx$prestatie", sorter:"number", formatter:"progress"},
{title:"Eenheid", field:"gsx$prestatieeenheid", sorter:"string"},
{title:"Naam", field:"gsx$naam", sorter:"string", align:"left", width:100},
{title:"Categorie", field:"gsx$categorie", sorter:"string", sortable:true},
{title:"Datum", field:"gsx$datum", sorter:"date", align:"left"},
{title:"Plaats", field:"gsx$plaats", align:"right", sorter:"string"},
],
ajaxResponse:function(url, params, response){
//url - the URL of the request
//params - the parameters passed with the request
//response - the JSON object returned in the body of the response.
return response.entry; //return the tableData property of a response json object
},
});
table.setData("https://spreadsheets.google.com/feeds/list/1Ze31_SUFd0ZyqeG1mt1qrEU61onnYhmI9mR1BC1pM7Y/od6/public/values?alt=json");
Unfortunately, I can't figure out what I'm doing wrong.
Thanks in advance for any help.

bldgChange: function () {
console.log(this.selected)
this.tabulator.parameter = this.selected
fetch('<API-URL>?Building=' + this.selected)
.then(response => response.json())
.then(json => this.tabulator.setData(json.recordset))
},
I abandoned the ajaxURL as too many people were having issues with it and no real solutions. This is a method I created for what I needed. Maybe you can retrofit it to your needs.

Related

reCAPTCHA sitekey not sent on AJAX code for verification

So, I've been working on a project that citizens can report problems on public places for the municipal government by filling a little form after selecting the place on Google Maps.
We need to implement reCAPTCHA for validation and stop/slow people from spamming our servers.
The data inputted in the form is sent through AJAX to an API that redirects it to add-problem.php but when I add 'g-recaptcha-response' and recaptcha.getResponse(); on my formData, the code stops working.
var formData = new FormData();
formData.append("description", description);
formData.append("pic", picture[0]);
formData.append("cpf", cpf);
formData.append("status", 1);
formData.append("keyword", keyword);
formData.append("type", "add-problem");
formData.append("place_id", $("#name").attr('data-id'));
formData.append("g-recaptcha-response", recaptcha.getResponse());
$.ajax({
type: 'POST',
url: '../../back/api/api.php',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
$("#loader").show();
},
success: function (data) {
$("#loader").hide();
console.log("success");
data = JSON.parse(data);
if (data.error) {
swal('Error', data.msg, 'error');
} else {
swal({
title: 'Sucess',
text: data.msg,
type: 'success',
onClose: () => {
location.reload();
}
The error on my console log is
Uncaught SyntaxError: Unexpected token O in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (municipe.php:467)
at u (jquery-3.3.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
I also tried to send the code statically creating a var and attributing the secret key into it, but I had the exact same error. What could it be?
EDIT: So... I realized what was the problem. Basically, I was sending a var called "g-recaptcha-response" throught the AJAX but my PHP was trying to receive one named as "recaptcha-response". That fixed the problem with my SweetAlert Modal!

Wordpress returns 400 Bad Request on ajax call with fetch API

I am making a Ajax call to the admin-ajax.php with a fetch API syntax. Here is the code that calls the back-end script:
fetch(ajax_obj.ajaxurl, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
})
and getting 400 Bad Request response.
Can someone tell me where does this request is not right?
When checking the Network Development Tools in chrome, I can see that the body that is sent is ok, the url is also ok...
... and as far as I know 4xx status codes are for errors on the client, so I don't even look on the server side code... if I am wrong please give me feedback on this...
Actually, I had jQuery ajax call like this:
this.data = {
'action': 'ajax_product_query',
'locations': this.locations,
'type': this.category != '' ? this.category : [],
'all-locations': this.filters['locationFilter'].all.checked,
'page': ajax_obj.current_page
};
$.ajax({
url: ajax_obj.ajaxurl,
method: 'post',
dataType: 'json',
data: this.data,
beforeSend: function(xhr) {
button.innerHTML = 'Loading...';
},
success: (data) => { ...
... and it worked like a charm...
Than, willing to remove jQuery dependency, wanted to turn the jQuery ajax call into Fetch API syntax like this:
fetch(ajax_obj.ajaxurl, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json()) ...
And than the requests turned into 400 Bad Requests...
Thanks!
Because after JS fetch 'POST' request you can't get $_POST data in Php. Dirty solution. You could add this code in u "/wp-admin/admin-ajax.php" to resolve this:
if ( !empty( trim( file_get_contents("php://input" ) ) ) ) {
$post = trim(file_get_contents("php://input"));
$_POST = ( array ) json_decode( $post );
$_REQUEST['action'] = $_POST['action'];
}
Or try to find a better solution.
P.S. Sorry for my English

Extjs 4.2: How to send parameters properly in a Ext.Ajax.Request POST

I have to do a POST from my ExtJs script in order to delete something from my DB:
Ext.Ajax.request({
url: 'deleteRole.html',
method: 'POST',
headers: {'Content-Type': 'text/html'},
waitTitle: 'Connecting',
waitMsg: 'Sending data...',
params: {
"rolename" : rolename
},
scope:this,
success: received,
failure: function(){console.log('failure');}
});
when the post is sent i can see in the firebug the rolename in font but not as a param. I would like to show you another post (made with spring:form) relative to the user registration. If i inspect the post i can see the following:
(source: subirimagenes.com)
And i can get the parameters in my controller using #RequestParam.
But in the post that i have problems i can't see the parameters part, i can only see the Font(Fuente) part:
(source: subirimagenes.com)
As a consequence, my spring controller does not detect any parameter. Is it something wrong in my POST?
Thank you
The problem is that you are using the line headers: {'Content-Type': 'text/html'}, in your original question. This would set the content to text/html instead of the content being post data.
I solved it with the following code:
var rolename = 'myRol';
Ext.Ajax.request({
url: 'deleteRole.html',
method: 'POST',
params: {
rolename: rolename
},
success: received,
failure: function(){console.log('failure');}
});
I'm using this in a Sencha Touch app. I had to add an extra config called jsonData and make it true or else nothing is passed to my endpoint url.
Ext.Ajax.request({
url: endpoint,
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : {add: formattedAddress, lat: latitude},
jsonData: true,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
Ext.Msg.alert("Success", 'yea');
},
failure : function(response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.Msg.alert("Error", respObj.status.statusMessage);
}
});

How to call Twitter v1.1 API in javascript using AJAX

Aim - to get the twitter followers of a particular user using javascript
I have tried the below code as a POC-
$(document).ready(function() {
// Handler for .ready() called.
$.ajax({
url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
type: "GET",
data: { cursor: "-1",
screen_name: "twitterapi" },
cache: false,
dataType: 'json',
success: function(data) { alert('hello!'); console.log(data);},
error: function(html) { alert(html); },
beforeSend: setHeader
});
function setHeader(xhr) {
if(xhr && xhr.overrideMimeType) {
xhr.overrideMimeType("application/j-son;charset=UTF-8");
}
//var nonce = freshNonce();
//var timestamp = freshTimestamp();
//var signature = sign(nonce,timestamp);
//alert(signature);
//alert(accessToken+"-"+consumerKey);
//alert(oauth_version+"-"+oauth_signature_method);
xhr.setRequestHeader('Authorization','OAuth');
xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
xhr.setRequestHeader('oauth_timestamp', '1359955650');
xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
xhr.setRequestHeader('oauth_version', '1.0');
}
});
I calculated the signature values from the Twitter OAuth tool ..
This gives me 400 Bad Request error ....
Please let me know what the problem is...
The problem is your request's header, it should be like this:
xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');
Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a
It support both client side and node.js
Cheers
The oauth_* fields are all part of the Authorization header string, so they need to be concatenated as shown at the bottom of this page - https://dev.twitter.com/docs/auth/authorizing-request
They should not be presented as separate header fields.

Trigger.io Ajax Requests - with Parse Facebook User authentication

I'm trying to authenticate users from Trigger.io, ideally via Facebook.
I authenticate the user via Facebook (using the Parse Facebook module), and pass their access token, acess expiry date, and facebook Id to my call to Parse.
It is here things go wrong. Whenever I try and post this data via Ajax to the Parse REST API, I get an error in my forge/Trigger console reading:
{ type: 'EXPECTED_FAILURE', content: '{"code":107,"error":"This
endpoint only supports Content-Type: application/json requests, not
application/x-www-form-urlencoded."}', statusCode: '400', message:
'HTTP error code received from server: 400' }
The code I used to try and post this data is...
function auth(facebookId,accessToken,expirationDate) {
forge.logging.log('auth started');
forge.request.ajax({
url: 'https://api.parse.com/1/users',
headers: {
'X-Parse-Application-Id': config.parseAppId,
'X-Parse-REST-API-Key': config.parseRestKey,
'Content-Type': 'application/json'
},
type: 'POST',
dataType: 'json',
data: {
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
},
success: function (data) {
forge.logging.log('auth finished 1');
forge.logging.log(data);
},
error: function(error){
forge.logging.log('auth finished 2');
forge.logging.log(error);
}
})//success
} //auth
I can't figure out how to send this as a JSON object/ in the correct format. If anyone has any ideas they'd be much appreciated. Thanks. Josh.
Whenever the data option passed to forge.requests.ajax is an object like in your example, what actually gets posted is a query string that represents the object. The contentType option merely allows you to set the Content-Type header, it does not effect how objects are encoded for the request.
However if the data option is just a string, then this string is used as the body of the request. You can generate a JSON string to use as the body using JSON.parse like so:
forge.request.ajax({
...
contentType: 'application/json',
data: JSON.stringify({
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
})
});

Resources