jQuery $.post - do I have to encode the URL parameter? - url

I'm making an AJAX call with $.post(url, cb). The URL I'm passing in could potentially have weird characters like spaces, &, ? and so on.
Do I have to use $.post(encodeURIComponent(url), cb)?
url is something like /foo/weird-char§.

Do I have to use $.post(encodeURIComponent(url), cb)?
You will have to use encodeURIComponent() but not on the entire URI, only on the data part (weird and chars in your example). The URL and the ? & separating the parameters must stay intact. If you encode the entire URI, it will become unusable.
If you would add the data as POST data using the data parameter:
url = "/foo/possible";
$.post(url, { "weird": "f2(90§§$", "chars": "ß1028490" });
jQuery's Ajax functions would take care of URL encoding the data automatically.

Yes, you would need to encode the keys and values in the query string (but not the ? which separates the path from the query arguments and the & which separates the query arguments). This is built into jQuery if you use the data parameter of the $.post, like so:
$.post(url, { name: "John", time: "2pm" }, cb);

I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded.
I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});

Related

How can I escape " or ' when it is a variable in ruby or rails?

I'm building a js file on the backend for future use and need to convert macros into js code. My gsub in the method below was working fine until I had a url with double quotes. If I have a variable quote_type = "'", how can I interpolate that as an escaped quote? In other words..
"'" becomes "\'" and '"' becomes '\"'
Here's my existing method and I just added the quote_type variable to try this out.
def substitute_timestamp_macro!(string)
quote_type = string[0]
string.gsub('[timestamp]', '\' + new Date().getTime() + \'')
end
edit: example string would be "https://doesntmatter.com/stuff/123;time=[timestamp]?"
edit 2: Here is the expected result:
"https://doesntmatter.com/stuff/123;time=" + new Date().getTime() + "?"
here is the actual result
"https://doesntmatter.com/stuff/123;time=' + new Date().getTime() + '?"
notice in my gsub i hard coded an escaped single quote. I now want to use the variable to match the input quote so if it's single, use single, and if double, use double
Consider %() to wrap your string:
def substitute_timestamp_macro!(string)
%("#{string}").gsub("[timestamp]", %(" + new Date().getTime() + "))
end
Note that this will render a string with escaped double quotes:
substitute_timestamp_macro!("https://doesntmatter.com/stuff/123;time=[timestamp]")
=> "\"https://doesntmatter.com/stuff/123;time=\" + new Date().getTime() + \"?\""
Which will be interpreted properly when you render this to a buffer:
puts substitute_timestamp_macro!("https://doesntmatter.com/stuff/123;time=[timestamp]")
=> "https://doesntmatter.com/stuff/123;time=" + new Date().getTime() + "?"
The surrounding quote characters of the value determine the behavior of this function, this should fit the bill:
def substitute_timestamp_macro!(string)
quote_type = string[0]
string.gsub('[timestamp]', "\\#{quote_type} + new Date().getTime() + \\#{quote_type}")
end

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

Grails How to make address show in two line?

I've a student form which there's location inside the form, when I run the app and show the form it'll look like this
Location : Jl Excel Road Ring No.36 SINGAPORE, 10110
But I want to make the location in two line like this
Location : Jl Excel Road Ring No.36
SINGAPORE, 10110
here's the gsp
<td><g:message code="location.label"/></td>
<td>${studentInstance.location}</td>
and this is the service in def show
def loc = Location.findByTidAndDeleteFlag(params.tid, "N")
if(loc != null){
studentInstance.location = loc.address1 + " " + loc.city + ", " + loc.zipCode
}
else{
studentInstance.location = ""
}
Use the br tag
studentInstance.location = loc.address1 + "<br/> " + loc.city + ", " + loc.zipCode
Then you can render directly the HTML unescaped like this:
<%=studentInstance.location%>
The default codec is probably HTML in your configuration.
Check the value of grails.views.default.codec
For more information read this:
http://grails.org/doc/2.2.1/ref/Plug-ins/codecs.html
I believe that starting from Grails 2.3.x the default views codec is HTML with XML escaping in order to prevent XSS attacks.
This is a bad approach but you can try
studentInstance.location = loc.address1 + "<br> " + loc.city + ", " + loc.zipCode
Generally, I would have each of the element of address available in view so that the styling is flexible in view than in controller, something raw would look like:
<td><g:message code="location.label"/></td>
<td>${model.address1} <br> ${model.city}, ${model.zipCode}</td>

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