Reputation: 319
I'm working with existing code which validates a user's submission by sending to a given URL via Ajax:
var url = '/foo/bar/' + valuea + '/' + valueb + '/' + valuec;
Which is then sent via ajax:
$.ajax({
type : 'GET',
url : url,
// data : data,
success : function(response)
{...
}
});
The issue lies when the user input contains a forward slash e.g.:
valuec = ABC/DEF
As then the url becomes defined as:
/far/bar/{valuea}/{valueb}/ABC/DEF
Which results in a whole different URL structure and 404s.
Is there a way I can escape this value to maintain the required URL structure?
I've tried the likes of replace(/\//, '\/');
and also encodeURIComponent()
but neither help.
My current thinking is a workaround to rewrite any '/' in the user submitted data to something else (e.g. |) so I can parse it to the URL, and then re-adjust it upon return, but that's a bit of a messy workaround imho.
Thanks in advance
Upvotes: 2
Views: 4956
Reputation: 319
Thanks for replies. Unfortunately due to prebuilt limitations I cannot amend the URL structure, and the encodeURIComponent doesn't work in:
$.ajax({
type : 'GET',
url : url,
So, instead I've gone for the replace method...!
valuec = valuec.replace(/\//g, '|||');
So it parses to the API correctly, and then at that end, I swap them back.
Cheers
Upvotes: 0
Reputation: 3233
encodeURIComponent
will work.FIDDLE
valuea = 1;
valueb = 2;
valuec = "ABC/DEF";
var url = '/foo/bar/' + valuea + '/' + valueb + '/' + encodeURIComponent(valuec);
document.write(url+'<br/>');
Upvotes: 4
Reputation: 1
You can pass the values as query string parameters
var url = "/foo/bar/?valuea=" + valuea + "&valueb=" + valueb + "&valuec=" + valuec;
Upvotes: 0