Working around recent $.parseJSON change - javascript

With jQuery 1.9, they changed $.parseJSON to behave in the same way as JSON.parse. The most notable change that has caused me headaches is that now empty strings are considered invalid JSON, and cause jQuery to throw an error.
In the codebase who's version of jQuery I am upgrading, there are many places where we are making ajax requests with dataType: 'json', and in some of those instances there are situations where the server may respond with an empty string. This wasn't an issue in our current version of jQuery, but I'm trying to upgrade, and its causing problems.
It would be a daunting task to change all of the instances of $.ajax with dataType: 'json', in the codebase just to work around the error that $.parseJSON throws, so I am looking for an alternative way of working around this issue. Would something like $.ajaxPrefilter work?
The best solution I could think of is to intercept data that comes in via all ajax calls with dataType: 'json' and pre-process it it using something similar to jQuery's own suggested workaround, to make it work without having to change each ajax call individually.

You can use ajaxSettings() to override the default converters:
$.ajaxSettings({converters: { "text json": yourSafeParseJSON } })

Related

How does ember fetch perform ajax query?

I'm using ember-fetch and from it's source code I cannot figure out where it made the call XHR call.
In another word, where does it call window.XMLHttpRequest?
Coming from a jQuery background, I'm also trying to figure out where can we specify option such as processData = false as seen in here, but this time I want it in ember-fetch-way.
In another word, where does it call window.XMLHttpRequest?
Short answer is: it doesn’t. Its repo says “HTML5 fetch polyfill from github wrapped and bundled for ember-cli users”, so it does what is says on the tin, it uses the Fetch API instead.
(…) I'm also trying to figure out where can we specify option such as processData = false
Right, if I understand this correctly, fetch by default does not process the data it gets, that’s why you see so many examples with something like response.json() (like on the repo you linked).

$.ajaxSetup in js vanilla

I have a jquery ajaxSetup which I want to convert in JS vanilla working cross browser.
So I need the same action (presetting data for all future jquery AJAX calls) written in JS vanilla.
$.ajaxSetup({
data: {
"_token": ajax_token
}
});
Which means I need this setup to be in JS vanilla, but I'll use jquery ajax after that (in rest of the code).
Have any idea? Thanks.
You can't.
The ajaxSetup method in jQuery works because when the various ajax methods in jQuery run, they check the place where ajaxSetup stores its data to see if they need to act other differently to the default.
ajaxSetup is the entry point that the jQuery library uses to store data in that place. It is internal to jQuery and you can't access it other than through that entry point.

Call javascript function onclick in Rails

I have the following code in one of my views:
<button type="button" onclick="analyze();">Analyze</button>
And, the .js.coffee file for the corresponding controller contains
analyze = ->
$.ajax
type: "GET"
url: "http://localhost:3000/api/logs"
success: (data) ->
Analytics.doAnalysis data
return;
return;
But, when I click the button, I get an error in console saying Uncaught ReferenceError: analyze is not defined. I think my onclick is not correctly defined. What is the recommended way of doing this?
I am new to web development
Since you're new, let me give you some ideas on how to improve your code:
Unobtrusive JS (UJS)
This tutorial explains it very well
Rails convention is geared towards "unobtrusive" javascript functionality. This means you can assign events to elements on your page without having to reference those elements directly (don't use inline onclick etc)
This is best described in the same way as CSS - using inline CSS is ridiculously laborious & seen as bad practice (it's not DRY). A much better way is to have a central stylesheet, which you can then use to style elements on the page.
Unobtrusive Javascript works in the same way - keep everything in files you call at runtime:
#app/assets/javascripts/application.js
$(".element").on("click", function(){
...
});
The importance of this cannot be stated enough - having unobtrusive JS is one of the best programming patterns you can apply; it not only DRIES up your code, but also ensures future development can be kept modular (a gold standard in development)
Ajax
Since you're using ajax, you may wish to use the Rails UJS Ajax functionality, which basically means this:
<%= button_to "Analyze", analytics_api_path, id: "analyze", remote: true %>
The remote: true option of this calls the Rails UJS driver's ajax functionality - basically setting up an ajax call without you having to write any code. The caveats of this are that you need to handle your own ajax:success process, and you'll need to point the element to the correct href
I would do this:
#app/assets/javascripts/application.js.coffee
$("#analyze").on "ajax:success", (data, status, xhr) ->
Analytics.doAnalysis data
Change this:
analyze = ->
To this:
window.analyze = ->
Functions in coffeescript are not global by default.

Parsing JSON in javascript for multiple browsers

I'm trying two different approaches. One works in only Firefox, the other works in Safari, but neither work in both. The one that works in Firefox is:
var json = JSON.parse(data);
var results = json.query.results.quote;
The one that works in Safari
var results = data.query.results.quote;
Where data is the JSON that is being returned from a server. Is one of these the proper ways to parse JSON, and what's the best way for browser compatibility
EDIT:
When I debug in Safari using JSON.parse I get the error: Unexpected identifier "object"
If you are using jQuery to get this JSON data, you don't need to worry about parsing it. jQuery can (and sometimes will) do it for you.
Your problem is (probably) that it is already being parsed for you. If you server returns the Content-type: application/json header, jQuery will parse it for you. If it returns a different header, like text/html, then it won't be parsed as JSON. It's never good to be unsure of what a variable contains.
To tell jQuery to always parse it as JSON, use dataType: 'json'. This makes sure that the data in your callback is always an object.
$.ajax({
url: 'file.php',
dataType: 'json',
success: function(data){
var results = data.query.results.quote;
}
});
You can use the official implementation of JSON by Douglas Crockford. It's available here. Major libraries make sure to add JSON functionality. It is also very easy to check if a native implementation of JSON is available within the existing browser.
The JSON library already does that. It checks to see if the browser already has JSON.parse and JSON.stringify implemented. If it does, it won't override anything. If it doesn't it will give you the functionality you need.

How to convert string to JSON object?

I am using jquery 1.3.2 and I can't use the parseJSON since it is added in 1.4.1 & I can't upgrade right now.
Is there any wat to get JSON object from string?
If this is a duplicate please send me the link.
Thanks for reading
You can use a couple of options, see here
Javascript eval function
JSON.parse() function
The eval function has some security issues associated with it, and the JSON.parse function has its own set of incompatibilities. I guess this is why JQuery has its own wrapper function. If you can't use JQuery 1.4+ though, these are two of your best options, without going looking for a specific JSON parsing library.
json2.js : http://www.json.org/js.html

Categories

Resources