Correct syntax for Google Spreadsheet update - Javascript - javascript

Anybody know the correct syntax for updating a row in Google Spreadsheets using the Javascript API?
I'm working off of the API documentation here and I can't figure out what is the correct syntax I need to send the data in. What I have currently is:
var serialObject = $('#basicForm').serialize();
$.ajax({
url: updateBasicUrl,
type: 'PUT',
data: serialObject,
});
What should the syntax of the data field be (the above throws an unidentifiable error)?
EDIT - after converting a JSON object to XML to conform to the exact look of the xml here, it still doesn't work:
var updateBasicUrl = "https://spreadsheets.google.com/feeds/list/*spreadsheetIDnumber*/od6/private/full/*cellID*/*versionnumber*?access_token=*accesstoken*
$.ajax({
url: updateBasicUrl,
type: 'PUT',
contentType: 'application/atom+xml',
//contentType: 'text/xml', //tried both of these, they don't seem to work
data: xmlBasic,
})
EDIT - So it seems there is a Cross-Domain Origin problem. The Google Spreadsheets API won't allow it. Anybody know of a work-around?

you could search the java source code for the solution - http://code.google.com/p/gdata-java-client/source/browse/trunk/java/src/com/google/gdata/client/spreadsheet/SpreadsheetService.java?r=94
this triggers the send in the java version:
service.insert(cellFeedUrl, newEntry);
public void setCell(int row, int col, String formulaOrValue)
throws IOException, ServiceException {
CellEntry newEntry = new CellEntry(row, col, formulaOrValue);
service.insert(cellFeedUrl, newEntry);
out.println("Added!");
}

Related

Ajax request not passing parameter to ASP.NET MVC controller

Tried looking in stackoverflow because this looked so trivial. Found many similar questions and read through them. Found no solution using these examples. Here is my code, can anyone help?
function testAjax() {
return $.ajax({
type: "GET",
url: '#Url.Action("Nodes","Competence", new { userId = Sven });',
contentType: "application/json;charset=utf-8",
dataType: "json"
});
}
var promise = testAjax();
promise.success(function (data) {
var dataConverted = JSON.stringify(data);
$('#tree').treeview({ data: dataConverted, multiSelect: true });
});
ASP.NET MVC method
public JsonResult Nodes(string userId)
{
var temp = userId;
var list = new List<Node>();
list.Add(new Node("Test1"));
list.Add(new Node("Test2"));
list.Add(new Node("Test3"));
return Json(list, JsonRequestBehavior.AllowGet);
}
EDIT:
Just before I was about to turn crazy on Halloween night, i figured out to try in a new session. Turns out it was just a caching problem..Thanks for the help everyone
Since your server may not expecting a request with JSON content, try removing the contentType parameter on your ajax call. Its default value is "application/x-www-form-urlencoded; charset=UTF-8" and is fine for most cases.
It's type should be "POST"
return $.ajax({
type: "POST",
url: '#Url.Action("Nodes","Competence")',
data: { userId: "Test" },
contentType: "application/json;charset=utf-8",
dataType: "json"
});
As it's a GET verb, it'll be easiest to pass this in as a querystring value. This also conforms better with a RESTful design.
For example replace #Url.Action("Nodes","Competence")
with
#Url.Action("Nodes","Competence", new { userId = id });
Then you can delete the data property. This will append ?userId=valueOfId into your url and then it should be mapped correctly to your action with the userId correctly populated.
Update
As #freedomn-m stated:
This will generate the url when the view is built server-side. If the
parameters never change, then fine - but it's relatively unlikely that
the parameters won't change, in which case you should add the url
parameters at runtime if you want them on querystring.
This is completely accurate. Without knowing your exact implementation I can only make assumptions. But technically you could wrap your ajax call in a function and then you could either pass in the userId and generate the url within that function or pass in the url, performing the url generation outside of the function.
This would mean that you only need one function that performs the ajax request and you can have another function that gets the userId (and possibly generates the url) and then passes that into the ajax function. How you store the userId is entirely up to you, but one thing I would suggest is investigating data attributes which is a fairly well defined way for storing data on html elements.

Passing a string array to mvc controllers using ajax

I need to pass list of strings from multiple select to the controller. Though the requirement looked very simple to me, I was breaking my head for the past hour in this. I have did a fair research on this, but unable to succeed.
Below is my Javascript code. Please ignore the comments. I was successfully able to fetch the list of items in the multiple select. While i do the ajax call, I get the error "Object reference not set an instance of an object.
function submitForm() {
var selected = $('#selectedTasks option').map(function(){
return this.value
}).get()
var postData = { selectedTasks : selected } //corrected as suggested
//selectedTasks = JSON.stringify({ 'selectedTasks': selected });
alert(postData);
$.ajax({
type: "POST",
//contentType: 'application/json; charset=utf-8',
url: '#Url.Action("AssignTasks", "MonthEndApp")',
dataType: 'json',
data: postData,
traditional: true,
success: function (data) {
alert("Success");
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
MonthEndAppController.cs
[HttpPost]
public void AssignTasks(List<String> selectedTasks)
{
//do something
}
Can someone guide me where exactly I have gone wrong? Can someone suggest me what is wrong?
EDIT : As suggested by Mr. Rory I have made the java script changes. Now the Java script part works absolutely fine. But the Controller is not getting called when the ajax request is made. Can someone help me out if something wrong in the call made to controller ?
Have you tried with string[] instead of List<String> ?
The parameter your AssignTasks action is expecting is called selectedTasks, not values:
var postData = { selectedTasks: selected };
Also note that when debugging anything in JS you should always use console.log() over alert(), as the latter coerces all types to a string, which means you're not seeing a true representation of the actual value.

python unpack a dict from json

I've been searching around, but I cannot find an answer, my guess is that my question is not defined very well, so i hope to get some guidance
I'm using turbogears2.2
I'm sending from the client view a JavaScript object through $.post(),
On the server I receive this object (as kw):
{'phones[1][surname]': u'sym', 'phones[2][name]': u'', 'phones[1][phone]': u'5498498', 'phones[0][phone]': u'0564', 'phones[1][name]': u'jhon', 'phones[0][surname]': u'cat', 'phones[2][phone]': u'', 'phones[0][name]': u'bob'}
I'm sending a data from a table with 3 columns
On my server I'm trying to separate the data for each row, but I'm a bit lost here.
how can I split that dict into different rows of data?
Doing
import json
json.loads(str(kw))
Fails
{ValueError}: Expecting property name: line 1 column 2 (char 1)
How can I convert that dict/object to a nested dictionary (or something else)?
Thanks
Thanks for the help Martijn Pieters , I thought I was posting JSON, but i wasn't.
You didn't post JSON; you posted application/x-www-form-urlencoded data that jQuery formatted for the PHP array feature. – Martijn Pieters
Here is my JavaScript, I'm trying out HandsOnTable (jQuery data grid editor)
$("#sendToServer").click(function(){
var tableData = $("#myTable").data('handsontable');
$.post(
URL,
{phones:tableData.getData()},
function(data){
console.log(data)
}
)
})
And that wasn't JSON, even though I thought it was
Anyway, simple fix:
Client side (JavaScript):
var tableData = $("#myTable").data('handsontable');
var jsonData = JSON.stringify(tableData.getData())
...
$.post(URL,
{phones:jsonData},
...
)
And now on the server side (Python):
import json
def getPhones(self,**kw):
phones = json.loads(kw['phones'])
...
And I have the data as a dict of rows, great
Thanks for the guidance
To post JSON, don't use $.post(). Use $.ajax() instead, and set the content type explicitly:
$.ajax({
url: URL,
type: "POST",
data: JSON.stringify({phone: tableData.getData()}),
contentType: 'application/json; charset=utf-8'
dataType: 'json',
success: function(data) {
console.log(response);
},
});
This can especially help if you have a controller that handles JSON directly, such as those provided by TurboGears Web Services.

GeoServer get GeoJSON from AJAX issue

I am using GeoServer version 2.2.5, and what I try to do is making a AJAX call to get the json string from the output GeoJSON url, for example:
http://localhost:8080/geoserver/sf/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=sf:archsites&maxFeatures=50&outputFormat=json
the javascript I used is like this:
var processJSON = function (data) {
console.log(data);
};
function init() {
//geojson url
var url = "http://localhost:8080/geoserver/sf/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=sf:archsites&maxFeatures=50&outputFormat=json&&format_options=callback:processJSON";
//execuate ajax request to get data
$.ajax({
url: url,
dataType: 'jsonp',
jsonp: 'processJSON'
});
}
I am pretty sure that this method works, because I can get the json object from the url which is from GeoServer version 2.2.4. But it just doesn't work for GeoServer 2.2.5 and later. I read somewhere that says "JSONP support has been disabled by default since it is perceived as a security issue." But I have no idea how to make it work.
Can anyone give me some suggestion on this?
Thank you very much

themoviedb JSON API with jQuery

I'm trying to do something that seems like it should be simple. Get the input of a text field and search the themoviedb.org database for it via the API.
I'm using jQuery and the themoviedb.org APIv3, which supports JSONP. All I get, though, is this response:
{"status_code":6,"status_message":"Invalid id - The pre-requisite id is invalid or not found"}
That doesn't really tell me a lot. ID of what?
Things I know:
I have the right API key
The search button is submitting and getting the value of the input correctly
Here's a jsfiddle, and here's the API documentation about searching movies. Also, check out this version of the API docs. I think it has to do with the query params.
Really, I have no idea what I'm doing with JSON, so I'm hoping this will be a representative example that will help me understand it.
You just need the correct number of query string parameters. The required paramaters are query and api_key. I found these requirements here http://docs.themoviedb.apiary.io/#get-%2F3%2Fsearch%2Fmovie. Give this a try instead:
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = '&api_key=470fd2ec8853e25d2f8d86f685d2270e';
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});​
Working Fiddle: http://jsfiddle.net/fewds/srdHD/3/
Note: Since thats most likely your REAL api key I would suggest requesting a new one!
The URL you use is not correct, your examples generates the following request:
http://api.themoviedb.org/3/search/MOVIENAME?api_key=APIKEY
but according to the API documentation it should look like this:
http://api.themoviedb.org/3/search/movie?api_key=APIKEY&query=MOVIENAME
I have forked and updated your jsfiddle
Need the correct number of query parameters. The required paramaters are query and api_key
If you are getting error on this by urlencode or decodeing please check your url at urlencode.in or urldecode.in

Categories

Resources