I'm writing a cloud based program that utilizes UTC for date saving to the server, and convert it back on the round trip. Problem is, my instance in the cloud is autoconverting the JsonResult datetime values according to the localization settings on the browser obtaining the result.
I have gone through tons of steps to make sure the server side code on both levels is returning the proper data, and it is on all instances, and no Javascript code on my page is making the change either (even removed all my Javascript date formatting just in case), I have traced out with Firebug to determine the exact point that it changes, is when my page receives the Json Result from my JsonResult method. Like I said, I have debugged the values before being sent to the page, and they are proper, and on my response, they are modified based upon browser location....
Has anyone had a similar problem?
Value returned:Date(1341792000000) 07/08/2012 17:00
Should be: Date(1341817200000) (07/09/2012 12:00AM)
Thanks
I finally ended up getting the proper results, with many modifications to my application. I did a lot of stuff to make this happen... First, I implemented timezone.JS to get a listing of timezones that will be used within the application, and used jstz to get current timezone of browser loading the page. Next, I have to make (for mvc) an file get method that accesses the timezones to load into timezoneJS.
Next, on save of the timezone, I specified pst as the type, and then convert back to utc on roundtrip to update the interface.
On formatting of my Json date, I run the timezoneJS method and get the timezone name from jstz, and set the new date value like such:
var timezone = jstz.determine();
timezoneJS.timezone.zoneFileBasePath = '/Item/GetTz'; // get file method
var dt = new timezoneJS.Date(parseInt(jsonDate.substr(6), timezone.name())); // strips out date from json date
dt.setTimezone('America/Los_Angeles');
This allows on the cloud projects to be ran on any server, and displayed in any browser regardless of timezone, and allow the user to view and configure timezone sensitive data natively, and allow for users to see the start/end date of configurable database values.
Maybe using http://msdn.microsoft.com/en-us/library/system.datetime.specifykind.aspx
Did you try with,
date.toLocaleString()
Alternatively,
You can create a new Date object and use Date.setUTC
As the OP said:
Problem is, my instance in the cloud is autoconverting the JsonResult datetime values according to the localization settings on the browser obtaining the result.
Recently experienced something similar. Strange behavior coming from $.ajax response. Depending on the language setting of the browser, a date received in string format gets converted into whatever is set in the language setting.
For example, in Postman, Web API response is like so:
{
"id": "10057",
"d_date": "3/30/2017 3:00:00 AM",
"sum": 253.0
},
If the browser is set to english(en/en-us), response is the same as above.
If the browser is set to english-uk(en-gb), response becomes:
{
"id": "10057",
"d_date": "30/03/2017 03:00:00",
"sum": 253
}
If the browser is set to german(de), response becomes:
{
"id": "10057",
"d_date": "30.03.2017 03:00:00",
"sum": 253
}
So somehow, the browser or the $.ajax library is trying to be smart and formatting the dates automatically.
Probably, the best solution is that the Web API send the date in ISO date time format.
Another solution if you can't change the backend is to add accept-language: en in the AJAX header request. Something like so:
$.ajax({
type: 'POST',
url: '/endpoint/',
contentType: 'application/json',
data: JSON.stringify(body),
dataType: 'json',
async: false,
headers: {
'accept-language': 'en'
}
})
Related
The following query using the Yahoo API started to return a result of 'null' since yesterday. (in fact all my queries against the geo.placefinder) return result: null.
Is anyone aware of an update / work that yahoo is doing? I have tried using their developer console but that returns null result as well. This query is a crucial part of my application that now is dysfunctional.
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D%22sfo%22&format=json
I have encountered the same problem, as I understand the placefinder was meant to be shutdown on Nov 17, 2012 and we were meant to use the paid service Boss Geo.
see:
https://developer.yahoo.com/blogs/ydn/introducing-boss-geo-next-chapter-boss-53654.html#more-id2
YQL tables for development
If you are looking to continue experimenting with the standalone PlaceFinder and PlaceMaker services, we are excited to continue supporting you through our YQL tables. These tables will be limited to 2,000 queries per day and are meant for non-commercial usage. We intend to shut down the current free versions of PlaceFinder and PlaceMaker on November 17, 2012.
Workaround:
For a direct replace of the current url you can use a combination or YQL and gws2.maps.yahoo.com. For example, to get the location of the random co-ordinates below the url will be the following:
var url = https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%27http%3A%2F%2Fgws2.maps.yahoo.com%2Ffindlocation%3Fpf%3D1%26locale%3Den_US%26offset%3D15%26flags%3D%26gflags%3DR%26q%3D52.01%2C4.82%27&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
to execute it with ajax it would be something like the following:
$.ajax(
{
url: url,
type: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: getWeatherForLocation,
error: appErrorHandler
});
This is the same as the post at Yahoo YQL query with gFlags returns nothing
Several solutions to this are posted on that thread.
I cannot consistently successfully send form variables that may/may not include special characters e.g. ? & #
Depending on where I try to escape the chars I encounter different errors when reading the data server-side.
I am aware that an update is due for React Native 0.7 to include formdata but wondered if I could safely post objects without needing this.
Someone has already posted a similar issue but no example code was posted to illustrate the POST working:
How to post a form using fetch in react native?
I have tried - amongst other things :
fetch(APIURL, {
method: 'POST',
body: JSON.stringify({
object1: {
param1a: "value 1a",
param1b: "value 1b - with bad chars & # ?",
},
object2:
{
param2a: "value 2a",
param2b: 0,
}
})
})
but it groups the data into a single unnamed parameter (changing the API to accept this is not an option).
also this:
fetch(APIURL, {
method: 'GET',
accessPackage: JSON.stringify({
accessToken: "abc123",
tokenType: 2,
}),
taggData: JSON.stringify({
title: "test",
wishlistID: 0,
anotherVar: "anotherVal"
})
})
I wish to receive the data as two strings that can be parsed as json objects at the other end.
Looking at the the fetch repo https://github.com/github/fetch hasn't helped as this assumes the post with be a full JSON post (which it isn't) or uses FormData which isn't available to React Native yet.
Another solution may be to safely encode/serialise all of the data to URL parameters but this has also proven inconsistent so far especially with the # char.
What's the best way to do this?
"it groups the data into a single unnamed parameter (changing the API
to accept this is not an option)."
It would, because you've set the post body. This is how it's supposed to work.
I wish to receive the data as two strings that can be parsed as json objects at the other end.
You can do whatever you want, but there's no magic happening here. You will receive a single string, the string you set body to. Likewise, the post body can contain anything but shouldn't get confused with "special" characters. Most likely it is your server-side that is causing the problems.
If you want to use FormData then I think it'll be in v0.7.0 which should be out any day now, or you could probably just include the JS file in your own project. You can find it here. Usage examples are in the UIExplorer demo.
We currently have a generic MVC method that GET's data from ASP.NET Web API
public static T Get<T>(string apiURI, object p)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(Config.API_BaseSite);
HttpResponseMessage response = client.GetAsync(apiURI).Result;
// Check that response was successful or throw exception
if (response.IsSuccessStatusCode == false)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
throw new HttpException((int)response.StatusCode, responseBody);
}
T res = response.Content.ReadAsAsync<T>().Result;
return (T)res;
}
}
Our question is:- obviously, we can not send 'p' as you would with a post,
client.PostAsync(apiURI, new StringContent(p.ToString(), Encoding.UTF8, "application/json")
but how we go about sending this object / JSON with a get.
We have seen sending it as part of the URL, however, is there an alternative?
GET sends the values with the query string (end of url), in regards to "but how we go about sending this object / JSON with a get. We have seen sending it as part of the URL, however, is there an alternative?".
The alternative is POST or PUT.
PUT is best used when the user creates the key/url. You can look at examples such as cnn.com - where the URL's are just short versions of the article title. You want to PUT a page at that URL.
Example:
http://newday.blogs.cnn.com/2014/03/19/five-things-to-know-for-your-new-day-wednesday-march-19-2014/?hpt=hp_t2
has the url of "five-things-to-know-for-your-new-day-wednesday-march-19-2014", which was generated from the article title of "Five Things to Know for Your New Day – Wednesday, March 19, 2014"
In general, you should follow these guidelines:
Use GET when you want to fetch data from the server. Think of search engines. You can see your search query in the query string. You can also book mark it. It doesn't change anything on the server at all.
Use POST when you want to create a resource.
Use PUT when you want to create resources, but it also overwrites them. If you PUT an object twice, the servers state is only changed once. The opposite is true for POST
Use DELETE when you want to delete stuff
Neither POST nor PUT use the query string. GET does
I have a Durandal/Hot Towel test app I'm trying to wire up. I have the below ajax call but I'm getting a 404 error.
GET http/.../api/Pizza/GetPizzasByOrderId?%22a8926610-a713-494c-bb15-46f6487a01c7%22 404 (Not Found)
I can manually change the url to:
http/.../api/GetPizzasByOrderId?orderId=a8926610-a713-494c-bb15-46f6487a01c7
It works. But I would like to know why the other call isn't working or more so, why is the ajax messing the parameter up in the URL and not as data like it does with complex objects. I have a get and a save that is working just fine. The get has zero params and the save is passing a complex object in.
C# Web Api Controller:
public class PizzaController : ApiController
{
[HttpGet]
public IEnumerable<Pizza> GetPizzasByOrderId(Guid orderId)
{
return DATA.GetPizzasByOrderId(orderId);
}
}
JAVASCRIPT:
var dataCall = $.ajax(config.getPizzasByOrderIdUrl, {
data: ko.toJSON(orderId),
type: "get",
contentType: "application/json"
});
Should I just change my JavaScript code to the below and be done with it or is there a better way to talk to the Api?
var getPizzasByOrderId = function (orderId) {
return Q.when($.getJSON(config.getPizzasByOrderIdUrl + "?orderId=" + orderId));
};
You could either use the code as you have it in that last code block, or you could pass in an object in place of your orderId as in the code block below. Either way, the difference is that the orderId parameter is being named.
var dataCall = $.ajax({
url: config.getPizzasByOrderIdUrl,
type: "GET",
data: {orderId : orderId},
});
In regard to why $.ajax() works fine for your POST, you can check this out pretty easily by running these two bits of code and viewing the requests that go across the wire. I recommend using google chrome.
Load a page that has jQuery loaded
Open the developer tools and go to the console
Enter the following code snippet
$.ajax("", {
data: {orderId: 123},
type: "get",
contentType: "application/json"
});
Switch to the network tab and click on the one that ends in ?orderId=123
Notice that it does have the data appended as query string parameters
In the snippet above, replace the "get" with "post"
After you hit enter, you should see another request on the network tab of the developer tools.
Notice that when changing nothing but the request type, the data is moved from the query string to the body. As noted in the comments, WebApi will pull from the body of the request and use the model binder to populate the complex object.
I'm creating a page that outputs a list of 1000-3000 records. The current flow is:
User loads a page
jQuery hits the server for all the records and injects them into the page.
Problem here is that those records for some users can take 3+ seconds to return which is a horrible UX.
What I would like to do is the following:
1. User loads a page
2. jQuery hits the server and gets at most 100 records. Then keeps hitting the server in a loop until the records loaded equal the max records.
Idea here is the user gets to see records quickly and doesn't think something broke.
So it's not really an infinite scroll as I don't care about the scroll position but it seems like a similar flow.
How in jQuery can I the the server in a loop? And how in rails can I query taking into account a offset and limit?
Thank you
You can simply query the server for a batch of data over and over again.
There are numerous APIs you can implement. Like:
client: GET request /url/
server: {
data: [ ... ]
rest: resturl
}
client GET request resturl
repeat.
Or you can get the client to pass in parameters saying you want resource 1-100, then 101-200 and do this in a loop.
All the while you will render the data as it comes in.
Your server either needs to let you pass in parameters saying you want record i to i + n.
Or your server needs to get all the data. Store it somewhere then return a chunk of the data along with some kind unique id or url to request another chunk of data and repeat this.
// pseudo jquery code
function next(data) {
render(data.records);
$.when(getData(data.uniqueId)).then(next);
}
function getData(id) {
return $.ajax({
type: "GET",
url: ...
data {
// when id is undefined get server to load all data
// when id is defined get server to send subset of data stored # id.
id: id
},
...
});
}
$.when(getData()).then(next);