Getting cookie stored in Javascript in Ruby on Rails - ruby-on-rails

Is there a way to get the cookie,set in JavaScript code, inside a controller method in Ruby on Rails v 4.0 ?

In a controller, you can set a cookie with:
cookies['foo'] = 'bar'
To set a cookie in Javascript, I wrote a short function in Coffeescript:
set_cookie: ( name, value, expiredays = 0 ) ->
expiredate = new Date()
expiredate.setDate expiredate.getDate() + expiredays
expire = '; expires=' + expiredate.toUTCString()
value = escape( value ) + expire
document.cookie = name + '=' + value + '; path=/'

Related

403 Invalid token error on GET user info

UPDATE: I thought I had to pass the parameters as a JSON string in the request body, but actually I need to put them on the URL (the endpoint string), so it's working now.
I'm new to Valence. I have some Salesforce Apex code (written by someone else) that creates a D2L user. The code is working fine.
I want to add an Apex method to retrieve info for an existing D2L user using the userName parameter. I've copied the existing method, changed to a GET, set the query parameter to userName, and kept everything else the same.
When I call my method, I get a 403 Invalid Token error.
Do I need to use different authorization parameters for a GET? For example, do I still need to include a timestamp?
Here's a portion of the Salesforce Apex code:
public static final String USERS = '/d2l/api/lp/1.0/users/';
String TIMESTAMP_PARAM_VALUE = String.valueOf(Datetime.now().getTime()).substring(0,10);
String method = GETMETHOD;
String action = USERS;
String signData = method + '&' + action + '&' + TIMESTAMP_PARAM_VALUE;
String userSignature = sign(signData,USER_KEY);
String appSignature = sign(signData,APP_KEY);
String SIGNED_USER_PARAM_VALUE = userSignature;
String SIGNED_APP_PARAM_VALUE = appSignature;
String endPoint = DOMAIN + action + '?' +
APP_ID_PARAM + '=' + APP_ID + '&' +
USER_ID_PARAM + '=' + USER_ID + '&' +
SIGNED_USER_PARAM + '=' + SIGNED_USER_PARAM_VALUE + '&' +
SIGNED_APP_PARAM + '=' + SIGNED_APP_PARAM_VALUE + '&' +
TIMESTAMP_PARAM + '=' + TIMESTAMP_PARAM_VALUE;
HttpRequest req = new HttpRequest();
req.setMethod(method);
req.setTimeout(30000);
req.setEndpoint(endPoint);
req.setBody('{ "orgDefinedId"' + ':' + '"' + person.Id + '" }');
I thought I had to pass the parameters as a JSON string in the request body, but actually I need to put them on the URL (the endpoint string), so it's working now

DustJs - Helpers rendering

I start with DustJs in KrakenJs environment and i have some troubles with Dust helpers.
In fact, i want to create a helper that can create for me a simple bootstrap button.
Here is my code :
var dust = require('dustjs-linkedin');
if (!dust.helpers)
dust.helpers = {};
dust.helpers.bootstrapButton = function (chunk, context, bodies, params) {
var body = bodies.block || '',
options = params || {},
btnStyle = options.style || 'default',
btnClass = options.class || '',
btnSize = options.size || '';
btnStyle = 'btn btn-' + btnStyle;
if (btnSize)
btnSize = 'btn-' + btnSize;
return chunk.write('<button class="' + btnClass + btnStyle + btnSize + '">' + body + '</button>');
};
And when i call this helper i have the render function for body instead of the final text for body (button content : "function body_3(chk,ctx){ctx=ctx.shiftBlocks(blocks);return chk.write("test");}")
I tried to user chunk.render but i have an error because my final html is not a function like body.
Do you have any idea ?
Regards,
Guillaume
The body is an unevaluated chunk which you need to evaluate before you can concatenate it with your strings.
var curChunk = chunk.data.join(); // Capture anything in chunk prior to this helper
chunk.data = []; // Empty current chunk
var body = bodies.block(chunk).data.join() || '', // Evaluate block and make a string of it
.......
return chunk.write(curChunk + '<button class="' + btnClass + btnStyle + btnSize + '">' + body + '</button>'); // Prefix output with any earlier chunk contents and then build your tag.

Geting DataTime from database through Javascript

I have a MVC Web Application Im trying to Ajax call an action method to retrieve some datetime from the database, the problem is the value comes as "/Date(386028000000)/"
its a DateOfBirth actually which I m using a java script function to calculate the age:
function (DOB) {
var birthday = +new Date(DOB);
return ~~((Date.now() - birthday) / (31557600000));
}
Anyway i can fix the Date Format and get only the date in a proper format or change the Java-Script method to accept the current format of the date value ?
I got it
var FixedDate = new Date();
FixedDate .setTime(DOB.replace("/Date(", "").replace(")/", ""));
return ~~((Date.now() - FixedDate) / (31557600000));
Click here to check the Demo
Sample Javascript/JQuery
var = MyDate_String_Value = "/Date(386028000000)/"
var value = new Date
(
parseInt(MyDate_String_Value.replace(/(^.*\()|([+-].*$)/g, ''))
);
var dat = value.getMonth() +
1 +
"/" +
value.getDate() +
"/" +
value.getFullYear();
Result - "3/27/1982"

Use string format in razor view to concat javascript variables

How can I write
var releaseName = $('#SelectedReleaseId option:selected').text()
var templateName = $('#SelectedTemplateId option:selected').text()
this:
$("#TestplanName").text(releaseName + '-' + templateName + '-' + '#Model.UserId' + '-' + '#Model.CreatedAt');
into:
$("#TestplanName").text( '#string.Format("{0}-{1}-{2}-{3}",releaseName,templateName,#Model.UserId,#Model.CreatedAt)');
The releaseName and templateName are unknown...
You can't.
You're trying to mix client-side variables – which only exist in Javascript on the client – with server-side code.
Instead, you can use a Javascript equivalent of string.Format.

JQUERY call to Controller Action: String Parameter truncated if containing 'space' character

I have a view that accepts 2 string parameters and 2 date values. User hits search button and they get filtered output to the screen. This all works perfectly well until a user inputs a string with a space. i.e. they can search for 'waste' but not 'waste oil'.
Interestingly, in the latter, the parameter is ok from Javascript before the call is made. But on entering the controller code it goes form being 'waste oil' on client to 'waste'. When this happens the other parameters get set to NULL crashing the system.
I've tried replacing the spaces if present with '#' character then stripping out and putting back in ' ' on the controller side. This is a messy fudge and only appears to work with one parameter.
There must be a simple explanation for this parameter data loss, any comments much appreciated
Not sure a code example is needed but here it is anyway if it help:
My controller header :
public ActionResult IndexSearch(int? page, string searchText,string searchTextSite,string StartDate,string EndDate)
{
My HTML Javascript :
function Search(sSearchText,sSite) {
sSearchText = sSearchText.toString().replace(" ", "#");
sSite = sSite.toString().replace(" ", "#");
debugger;
alert($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val());
$("#ResultsList").load($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val(),
function() {
$('#LoadingGif').empty();
});
$('#LoadingGif').empty().html('<img src="' + $("#AbsolutePath").val() + 'Content/images/ajax-loader.gif" alt="Loading image" />');
}
You are not URL encoding your parameters when sending the AJAX request because you are using string concatenations when building the url. You could use the following technique in order to have properly encoded values:
var url = $('#AbsolutePath').val() + 'Waste.mvc/IndexSearch';
var data = {
searchText: sSearchText,
searchTextSite: sSite ,
StartDate: $('#StartDate').val(),
EndDate: $('#EndDate').val()
};
$('#ResultsList').load(url, data, function() {
$('#LoadingGif').empty();
});
Now you will get correct values on the server.

Resources