Setting the cookies for forge.request.ajax in Trigger.io - trigger.io

I'm trying to set an extra cookie in the forge.request.ajax call. Is there a way to dot this?

You could use the headers argument to request.ajax manually if you wanted, e.g.
window.forge.ajax({
type: 'GET',
url: 'http://my.server.com/protected/,
headers: {
'COOKIE': 'csrftoken=47ac86bb7965b343e8ca21343b164ef3',
},
success: function (data) { },
error: function (error) { alert(JSON.stringify(error)); }
});

Making requests through forge.request.ajax actually uses a whole different context to your JavaScript - this is to get around the cross-domain restrictions that can be imposed on normal JavaScript.
We don't currently allow for manually settings cookies in the forge.request context, but note that any cookies which are set as part of a request will be persisted (as applicable) to subsequent requests, so we weren't expecting people to have to set their values by hand...

Related

Catch and pass hangout url to my rails app

I have a button to start a google hangout, everything works great, now I need to get the url using the
gapi.hangout.getHangoutUrl();
but I since this is a JS on my server, I know is possible to pass this to my app. But I don't know how (AJAX or anything else). I need this, because other user could join to this hangout.
Any suggestion with code would be appreciate
Within your hangout script....
Include jQuery - it's useful for X-browser support.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Get the Hangout URL:
var hoUrl = gapi.hangout.getHangoutUrl();
Get/Post the hangout URL to your server:
var uri = encodeURI(server + '?hoUrl=' + hoUrl);
$.ajax(uri,
{
async: true,
beforeSend: function(request) {
// Any beforesend code goes here, e.g. adding headers.
},
data: data,
error: function(jqhr, status, error){
// Error handling goes here.
},
type: verb,
success: callback
});
Handle the AJAX GET request and do your magic with the hoUrl parameter.
To clarify further:
A URL is formed before the AJAX get request to include a GET parameter, hoUrl, that has the hangout URL in it. Your server just needs to use whatever CGI/parameter parser to retrieve the 'hoUrl' parameter and then do whatever backend magic you want to do with it. Hope that helps to clarify.

Rails Devise 401 from Safari Extension

I'm trying to make a simple $.ajax request to a Rails app running locally.
The request works without any issues from the console but when I make the call from the safari extension the app returns a 401 Unauthorized. I'm not sure if I need to create an api token for each user and pass that in the url string to authenticate or if there's a simple reason why devise is not processing the request even though I'm logged in. My guess is that the culprit is the before filter I have on my controller which looks like this:
before_filter: authenticate_user!
But again, I get the 401 when I am signed in to the app. Just for reference, here's the call I'm making from the extension:
$.ajax({
type: 'GET',
url: 'http://localhost:3000/playlists.json?callback=?,
dataType: 'jsonp',
success: function(data) { console.log(data); },
error: function() { console.log('Uh Oh!'); },
jsonp: 'jsonp',
crossdomain: true
});
Any help would be much appreciated.
Ok figured it out. The cookie being set was set to expire after 'session' which basically means that as soon as you navigate away from the page the session is no longer there. Thus the extension did not have access to this extension cookie. The key was to set an expiration date by default on the session cookie which you can do like this in config/initializers/session_store.rb:
YourApp::Application.config.session_store :cookie_store, {
   :key => '_yourapp_session',
   :expire_after => 60*24*60*60
}
You can read more about cookie types here: http://en.wikipedia.org/wiki/HTTP_cookie#Session_cookie

c# MVC best way to make use of AJAX

In terms of making a an AJAX call, we have use the following method:
$.ajax({
type: "POST",
async: false,
url: '#Url.Action("CheckPhone", "Progg")',
data: { input: WebPhoneNum
},
success: function (iReturn) {
if (iReturn == 0) {
alert(Phone Number must be in format (XXX) XXX-XXXX. Please Re-Enter');
submitval = false;
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")"); // Boil the ASP.NET AJAX error down to JSON.
alert('Call to CheckPhone failed with error: ' + err.Message); // display the error raised by the server
}
});
Notice how it makes a call to the controller and returns a value. I was wondering if there was a better way of doing this. I know .NET MVC has some ajax calls built in but couldn't find one that fits what I am doing below. I know .NET MVC has a ajax call build that with a hyperlink but that is not what I need. I just need to make a call to the controller that returns some value(s).
THanks
There's only one thing that you need to fix:
async: false
must become:
async: true
because otherwise you are not doing AJAX. You are sending a synchronous request to the server freezing the client browser.
Other than that you seem to be doing some remote validation with this AJAX request. You probably might take a look at the [Remote] attribute that's built in and which avoids you writing all this code. All you need to do is decorate the view model property that needs to be validated with this attribute and then enable unobtrusive client side validation by including the proper scripts.
try to validate the format of a input with ajax?
I recommend you learn about data annotations to validate that kind of details (please revalidate on server at submit form like a good practice)
here is a usefull tutorial http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs

Strange underscore param in remote links

I use Rails3, JQuery and will_paginate gem to make remote pagination links. Known solution for this is:
$('.pagination a').live('click',function (){
$.getScript(this.href);
return false;
});
With this code I get links like: http://localhost:3000/products?_=1300468875819&page=1 or http://localhost:3000/products?_=1300468887024&page=2. So the little question is: what is this strange param _=1300468887024 (looks like Unix-time). What is its purpose? As I know this can cause some problems with search crawlers.
UPD: The solution is described here.
it's a cache buster. It's also used in development mode, so to avoid getting an old request from the browser cache.
(unfortunately, all the explanations I found are realated to advertisement :S)
This is a simple solution if you don't mind removing it for all requests:
jQuery.ajaxSetup({ cache: true });
Another solution would be to extend jQuery's getScript function as per the documentation:
jQuery.cachedScript = function(url, options) {
options = $.extend(options || {}, {
dataType: "script",
cache: true,
url: url
});
return jQuery.ajax(options);
};
This way, only the ajax calls using this new method will use the cache. On the other hand, if you used the ajaxSetup method, all your ajax calls would cache by default since ajaxSetup sets the cache property globally.
Now you can use $.cachedScript(location.href); instead of $.getScript(this.href);.

Difference Between $.getJSON() and $.ajax() in jQuery

I am calling an ASP.NET MVC action
public JsonResult GetPatient(string patientID)
{
...
from JavaScript using jQuery. The following call works
$.getJSON(
'/Services/GetPatient',
{ patientID: "1" },
function(jsonData) {
alert(jsonData);
});
whereas this one does not.
$.ajax({
type: 'POST',
url: '/Services/GetPatient',
data: { patientID: "1" },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('Error loading PatientID=' + id);
}
});
Both reach the action method, but the patientID value is null w/ the $.ajax call. I'd like to use the $.ajax call for some of the advanced callbacks.
Any thoughts appreciated.
Content-type
You don't need to specify that content-type on calls to MVC controller actions. The special "application/json; charset=utf-8" content-type is only necessary when calling ASP.NET AJAX "ScriptServices" and page methods. jQuery's default contentType of "application/x-www-form-urlencoded" is appropriate for requesting an MVC controller action.
More about that content-type here: JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks
Data
The data is correct as you have it. By passing jQuery a JSON object, as you have, it will be serialized as patientID=1 in the POST data. This standard form is how MVC expects the parameters.
You only have to enclose the parameters in quotes like "{ 'patientID' : 1 }" when you're using ASP.NET AJAX services. They expect a single string representing a JSON object to be parsed out, rather than the individual variables in the POST data.
JSON
It's not a problem in this specific case, but it's a good idea to get in the habit of quoting any string keys or values in your JSON object. If you inadvertently use a JavaScript reserved keyword as a key or value in the object, without quoting it, you'll run into a confusing-to-debug problem.
Conversely, you don't have to quote numeric or boolean values. It's always safe to use them directly in the object.
So, assuming you do want to POST instead of GET, your $.ajax() call might look like this:
$.ajax({
type: 'POST',
url: '/Services/GetPatient',
data: { 'patientID' : 1 },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('Error loading PatientID=' + id);
}
});
.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc
N.B .load, .get and .post are also simple wrappers around the .ajax method.
Replace
data: { patientID: "1" },
with
data: "{ 'patientID': '1' }",
Further reading: 3 mistakes to avoid when using jQuery with ASP.NET
There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.
$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.
Read More .. jquery-post-vs-get-vs-ajax
The only difference I see is that getJSON performs a GET request instead of a POST.
contentType: 'application/json; charset=utf-8'
Is not good. At least it doesnt work for me. The other syntax is ok. The parameter you supply is in the right format.
with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().

Resources