I'm trying to create a task in todoist but cant seem to do so
According to this todoist documentation, the below should work for creating a todoist task
$ curl https://todoist.com/api/v7/sync \
-d token=0123456789abcdef0123456789abcdef01234567 \
-d sync_token="VRyFHr0Qo3Hr--pzINyT6nax4vW7X2YG5RQlw3lB-6eYOPbSZVJepa62EVhO" \
-d resource_types='["projects", "items"]' \
-d commands='[
{ "type": "item_add",
"temp_id": "fdef5d16-a40a-475e-bd4a-0ccbd6fd8c3f",
"uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752",
"args": { "project_id": "24a193a7-46f7-4314-b984-27b707bd2331", "content": "Task1" } },
{ "type": "item_add",
"temp_id": "6f5e0b50-af7a-4133-bfc0-e8c041b819d2",
"uuid": "d16ad84a-e10b-4894-af7d-93ba6adf7a1e",
"args": { "project_id": 176637191, "content": "Task2" } },
]'
I've tried the following with little luck
commands = [{"type": "item_add", "uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752", "args": {"project_id": 2159935681,"content":"Test Task"}}]
$.ajax({
type: "GET",
url: 'https://en.todoist.com/api/v7/sync/',
dataType: 'json',
async: false,
data: {
'token': todoist_api_token,
'sync_token':'*',
'resource_types':'["projects", "items"]',
'commands':commands
}
})
I've also tried the following:
commands = [{"type": "item_add", "uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752", "args": {"project_id": 2159935681,"content":"Test Task"}}]
$.ajax({
type: "POST",
url: 'https://en.todoist.com/api/v7/sync/',
dataType: 'json',
async: false,
data: {
'token': todoist_api_token,
'sync_token':'*',
'resource_types':'["projects", "items"]',
'commands':commands
}
})
This results in the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://en.todoist.com/api/v7/sync/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I've also tried removing the project id
commands = [{"type": "item_add", "uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752", "args": {"content":"Test Task"}}]
$.ajax({
type: "GET",
url: 'https://en.todoist.com/api/v7/sync/',
dataType: 'json',
async: false,
data: {
'token': todoist_api_token,
'sync_token':'*',
'resource_types':'["items"]',
'commands':commands
}
})
I've also tried adding the temp_id parameter:
commands = [{"type": "item_add","temp_id": "fdef5d16-a40a-475e-bd4a-0ccbd6fd8c3f", "uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752", "args": {"project_id": 2159896038,"content":"Test Task"}}]
$.ajax({
type: "POST",
url: 'https://en.todoist.com/api/v7/sync/',
dataType: 'json',
async: false,
data: {
'token': todoist_api_token,
'sync_token':'*',
'resource_types':'["projects", "items"]',
'commands':commands
}
})
I've even tried the todoist api v8 version following the todoist instrucitons for the v8 api here
$.ajax({type: "POST",
url: 'https://beta.todoist.com/API/v8/tasks',
dataType: 'json',
async: false,
data: {'token':todoist_api_token,'content': 'Appointment with Maria'}
});
This returns "Bad Request"
I did find that the following works for v6:
$.ajax({type: "POST",
url: 'https://todoist.com/API/v6/add_item',
dataType: 'json',
async: false,
data: {'token':todoist_api_token,'content': 'Appointment with Maria'}
});
sync_token
In the first example I see that the sync token is set. It should be var sync_token = '*' and after the ajax request you should save the token with sync_token = response.sync_token; I see that you realized that in the later examples.
commands
The rest looks good but I can't see your commands and I guess the problem comes from there. The commands object has to be stringified with JSON.stringify(commands).
working example
I created a working example below. You have to replace the todoist_api_token = "" with your token and the project id's in the example task.
// Global variables
var todoist_api_token = ""; // Put your token here
var sync_token = "*";
// To get a project id: clicke on a project and look at the url.
// In the example "#project%2F2179064046" you have to remove "#project%2F".
// and the project id is 2179064046
// Run example task after document load
window.onload = function() {
console.log("Add example task to todoist");
var example_tasks = [
{"content": "Task1", "project_id": 2179064046},
{"content": "Task2", "project_id": 2179064046}
];
todoist_add_tasks_ajax(example_tasks);
}
// Functions
todoist_add_tasks_ajax = function(tasks) {
var commands = todoist_tasks_to_commands(tasks);
var data = {
"token" : todoist_api_token,
'sync_token' : sync_token,
'resource_types' : '["projects", "items"]',
'commands' : commands
};
jQuery.ajax({
url: "https://todoist.com/api/v7/sync",
data: data,
type: "POST",
dataType: "json",
success: function(response) {
console.log(response);
sync_token = response.sync_token;
},
error: function(response) {
console.log(response);
},
});
}
todoist_tasks_to_commands = function(tasks) {
var commands = [];
tasks.forEach(function(args) {
var temp_commands = {
"type": "item_add",
"temp_id": create_guid(),
"uuid": create_guid(),
"args": args
};
commands.push(temp_commands)
});
commands = JSON.stringify(commands);
return commands;
}
function create_guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
/*
// Install jQuery
javascript: (function(e, s) {
e.src = s;
e.onload = function() {
jQuery.noConflict();
console.log("jQuery installed");
};
document.head.appendChild(e);
})( document.createElement('script'), 'http://code.jquery.com/jquery-latest.min.js')
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
Related
In index.js I have:
$("#weather_form").on("submit", function(event){
event.preventDefault();
$.ajax({
url: "/weather/",
type: "POST",
data: {type_of_person: "1",
exercise: "2",
unit: "3",
zip_postal: "4"},
dataType: "json",
contentType: "json",
success: function (data){
alert("success");
},
error: function(xhr,errmsg,err) {
alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText);
}
});
});
I'm getting the following error:
So we know it's going into the error function of the AJAX call because of the popup. But why?
I specifically hard-coded the JSON values to pass.
The view that processes the AJAX data:
class weather(base.TemplateView):
template_name = "weather/index.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = forms.input_form()
return context
#staticmethod
def post(request, *args, **kwargs):
form = forms.input_form(request.POST)
if form.is_valid():
# process the data
type_of_person = form.cleaned_data["type_of_person"]
exercise = form.cleaned_data["exercise"]
unit = form.cleaned_data["unit"]
zip_postal = form.cleaned_data["zip_postal"]
results_matrix = interface.get_results_matrix(type_of_person, unit, exercise, zip_postal)
return http.JsonResponse({"results_matrix": results_matrix.tolist()}, status=200)
else:
return http.JsonResponse({"error": form.errors}, status=400)
Things I've tried, but to no avail:
data: JSON.stringify({type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"})
I think the form could not read data as you are sending contentType of json. Just removing that line should work. Also, you have to add csrf header to post request. So:
$.ajax({
url: "/weather/",
type: "POST",
data: {
"csrfmiddlewaretoken": $('[name=csrfmiddlewaretoken]').val(),
"type_of_person": "1",
"exercise": "2",
"unit": "3",
"zip_postal": "4"
},
dataType: "json",
// contentType: "json", remove this
success: function (data){
alert("success");
},
error: function(xhr,errmsg,err) {
alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText);
}
});
Well, it doesn't make sense to call success if you're receiving a 400 status code from the server.
Your data is valid in frontend and goes to the server, but it does not pass backend validations (or the backend fails to accept it properly) and therefore it returns you 400 Bad Request.
Any error code that is between 200-299 and different than 304 is considered an error when making an jQuery AJAX call.
I have some problem with Getting workitems from tfs via the following javascript code:
var res = new XMLHttpRequest();
var body = "{'query' : \"select * from workitems where [Change Number] = 'CH-0000433' \"}" ;
res.open("POST","<SERVER_NAME>/tfs/InternalApplications/Testing%20Services/_apis/wit/wiql?api-version=1.0",true,<LOGIN>,<PASSWORD>);
res.setRequestHeader('Content-type', 'application/json');
res.send(body);
when I am trying to execute this script, I am getting the 401 - Unauthorized error
I`ve wrote the PowerShell analogue of this script, and it works fine:
$q2 = """select Id from workitems where [Change Number] = 'CH-0000433' """
$res = Invoke-WebRequest <Server_Name>/tfs/InternalApplications/Testing%20Services/_apis/wit/wiql?api-version=1.0 `
-ContentType application/json `
-Credential $(Get-Credential) `
-Method Post `
-Body "{'query' : $q2}" `
-UseBasicParsing
I suppose that in javascript case I am passing credentials incorrectly, so how should I change it?
I've tested on TFS 2017 with the code snippet below and it is working:
var jsonObj = [{
"op": "add",
"path": "/fields/System.Title",
"value": "cecetest1"
}];
$.ajax({
url: 'http://TFS2017:8080/tfs/DefaultCollection/ScrumProject/_apis/wit/workitems/$Task?api-version=1.0',
type: 'PATCH',
contentType: "application/json-patch+json",
data: JSON.stringify(jsonObj),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("domain\\username" + ":" + "password"));
},
})
I have tried searching all possible matches of my problem and also have tried a couple of solutions but unfortunately none worked
My backend code:
Person p;
foreach(DataRow dr in dt.Rows)
{
p = new Person();
p.id = Convert.ToInt16(dr["Id"]);
p.name = dr["Name"].ToString();
p.phone = Convert.ToInt64(dr["Phone"]);
pList.Add(p);
}
string ans = JsonConvert.SerializeObject(pList, Formatting.Indented);
jQuery.ajax
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Alert output
[
{
"id": 1,
"name": "Bhavik",
"phone": 9601109585
},
{
"id": 2,
"name": "Xyz",
"phone": 1234567890
},
{
"id": 3,
"name": "Abc",
"phone": 9876543210
}
]
console.log(list.Person.length); returns undefined and hence does not enters the for loop.. So to work out with it.. and why is it necessary to specify contentType while dataType already exist.. Also can I use $.getJSON instead of $.ajax.
You should change your code to be var list = {"Person": data.d}; to reflect what you're alerting.
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data.d };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Also this should be a GET request not a post, then you would be able to use $.getJSON.
I'm trying to filter the json array through ajax and not sure how to do so.
{
posts: [{
"image": "images/bbtv.jpg",
"group": "a"
}, {
"image": "images/grow.jpg",
"group": "b"
}, {
"image": "images/tabs.jpg",
"group": "a"
}, {
"image": "images/bia.jpg",
"group": "b"
}]
}
i want it so that i can only show items in group A or group B.
how would i have to change my ajax to filter through the content?
$.ajax({
type: "GET",
url: "category/all.js",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
$('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' + post.image + '" /></div></li>');
});
initBinding();
},
error: function(xhr, status, error) {
alert(xhr.status);
}
});
Also, how can I can I make each link process the filter?
Group A Group B
Sorry for all these questions, can't seem to find a solution..
Any help in the right direction would be appreciated.
Thanks!
You'll need to write a filter function, more than likely:
function filterGroup(obj, filteredGroup) {
var resultObj = $.extend({},obj);
for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].group && obj[i].group !== filteredGroup ) {
delete resultObj[i];
}
}
}
return resultObj;
}
Then you'd just run your data through that filter. You'll also probably want to switch to a POST with a bunch of JSON like this.
$.ajax({
type: "POST",
url: "category/all.js",
dataType: "json",
cache: false,
data: {"posts": filterGroup(posts, 'a')},
contentType: "application/json",
success: function(data) {
$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
$('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' +
post.image + '" /></div></li>');
});
}
});
Most of this code is hypothetical since I don't know exactly what you're doing, but it should get you close. Just don't expect to be able to copy/paste it. This assumes you actually named your data variable as posts for instance.
To make a link run code, you'll need to attach a click handler and identify each link. I'll assume you added a classname to each (filterA and filterB):
$('.filterA').click(function(){
filterGroup(someDataObject, 'a');
return false;
});
$('.filterB').click(function(){
filterGroup(someDataObject, 'b');
return false;
});
I was given this code earlier but am having a hard time parsing the correct data.
I have the following JSON
{
flavors: [{
"image": "images/bbtv.jpg",
"desc": "BioBusiness.TV",
"id": "1"
}, {
"image": "images/grow.jpg",
"desc": "Grow Staffing",
"id": "2"
}]
}
and I want to only show id:1 or id:2.
I have the following code for Ajax
$.ajax({
type: "POST",
url: "foodservice/all.js",
dataType: "json",
cache: false,
data: {"flavors": filterId(flavors, 'a')},
contentType: "application/json",
success: function(data) {
$('#flavor-detail').html("<div/>");
$.each(data.flavors, function(i,item){
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});
and the following function to filter through the JSON object
function filterId(obj, filteredId) {
var resultObj = $.extend({},obj);
for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].id && obj[i].id !== filteredId ) {
delete obj[i];
}
}
}
return resultObj;
}
However, this code does not return anything.
Can someone tell me what I am missing?
Im pretty new to JSON, Ajax so any help would be greatly appreciated.
Thanks!
Why not just check in the "each" code?
$.each(data.flavors, function(i,item){
if (item.id > 2) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
I changed the following code to make it filterable
$.ajax({
type: "GET",
url: "foodservice/all.js",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$('#flavor-detail').html("<div/>");
$.each(data.flavors, function(i, item) {
if (item.id != flavorid) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});
and for each link to change the output,
$('#amare').click(function() {
flavorid = "1";
});
$('#sec').click(function() {
flavorid = "2";
})