Javascript can't find my mod_rewrite query string! - javascript

I use the following javascript class to pull variables out of a query string:
getUrlVars : function() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
So this works: http://example.com/signinup.html?opt=login
I need http://www.example.com/login/ to work the same way. Using mod_rewrite:
RewriteRule ^login/? signinup.html?opt=login [QSA]
allows the page to load, the javascript to load, the css to load, but my javascript functions can't find the opt key (i.e., it's undefined). How do I get opt to my javascript?

Javascript is client-side. Mod_rewrite is server-side.
Therefore Javascript will never see the rewritten URL. As far as your browser is concerned, the URL that you entered is the finished address.
The only real solution is to change your Javascript so it looks at the URL it's got rather than the old version (or possibly parse for both alternatives, since the old URL will still work and people may still have old bookmarks).
The other possible solution would be to go to your server-side code (PHP? whatever?) where you can see the rewritten URL, and insert some javascript code there which you can parse on the client side. Not an ideal solution though. You'd be better of just going with option 1 and changing you Javascript to cope with the URLs it's actually going to be getting.

Your issue is that JavaScript runs on the client side, so it will never see the ?opt=login part to which the URL gets converted internally on the server.
Apart from changing your regular expression to match the new URL format, the easiest workaround might be to write a JavaScript statement on server side that introduces the value of the opt variable into JavaScript.

If you're using PHP, you can have the PHP create a JavaScript variable for you. For example:
$params = "?";
foreach($_GET as $key => $value) {
$params = $params . $key . "=" . $value . "&";
}
echo 'var urlParams = "' . $params . '"';
Now, you JavaScript will have access to a urlParams variable that looks like this
?opt=login&
Then, in your Javascript code, wherever you expected to use the URL parameters, use the urlParams instead.

If it's a special case, then put it as a special case in some way. If you rewrite generally, change your general regular expression. The way mod_rewrite works, the client never knows the rewritten URL. From the client, it's /login/ and /login/ only. Only the server ever knows that it's really signinup.html?opt=login. So there's no way your regular expression or location.href can know about it.

Unless you use the [R] flag in your RewriteRule, the browser (and thus javascript) will never know about the new URL. If you don't want to be redirecting people, you're going to have to add some code to your login page that GET parameters as javascript in the page.

Related

How to concatenate a variable in a document.location.href path?

I have a php $_SESSION passing the name of a target directory, that is different from situation to situation. I have a javascript function to execute a file with the same name but in several different directories, depending on the string passed with $_SESSION. My code is:
<?PHP
$where = $_SESSION["where"];
?>
<script>
var where = "<?php echo $where;?>";
function goToThere() {
document.location.href = where + "/file_to_execute.php";
}
</script>
<body>
<button class="buttongreen" onclick="goToThere()">proceed</button>
</body>
Say the content of $where is "dir_a". Then clicking on buttongreen might launch function goToThere, thus going to page "dir_a/file_to_execute.php". The problem is that the goToThere function simply does not do anything. I've tried different sequences to concatenate the variable and the string, with various combinations of quotation marks, without success.
What am I doing wrong?
As stated, your code is applicable to what you are trying to do. The issue lies in the "$_SESSION['where']"
Either...
(1) You have a forward slash at the end of $_SESSION['where'] and you are adding another forward slash when concatenating.
(2) You are not doing "session_start();"
(3) The script code is not being incorporated into the body nor header (I'm not quite sure about this, but as I see it, the script code really is in no man's land so maybe???)
(4) The $_SESSION['where'] is simply not being saved
(5) The $_SESSION['where'] is simply empty
As it stands though, your code is valid as a proof-of-concept for what you are aiming to do

How to correctly read encoded get varible

I have a search engine that does the following things:
Read an input value and encode it using js, then redirect.
//read and save into `query` var
window.location.href = "/search/" + encodeURIComponent(query);
So if user enters
What is the meaning of & sign ?
The ulrl can't end up like this;
expample.com/search/What%20is%the%meaning%20of%20&this%20sign?
And instead get:
expample.com/search/What%20is%the%meaning%20of%20&26this%20sign%3F
Now when I dump the $_GET['parameters'] i get
string() "search/What is the meaning of "
I expect to get:
What is the meaning of & sign ?
I have tried:
$val = urldecode($_GET['parameters']);
But I have had no luck, Maybe I should change the way javascript encodes the url, what are your suggestions?
PHP decodes URL paramaters automatically into the $_GET superglobal as long as you're using the standard query string syntax. If you use your own syntax, you have to roll your own code (you already have custom code in the input form).
The raw URL can be fetched from $_SERVER['REQUEST_URI'] and parsed with the text manipulation tool of your choice. It's worth noting that this isn't an uncommon set up (many PHP frameworks do things this way).
You've mentioned that you're calling the following to obtain the value of the user's query:
$val = urldecode($_GET['parameters']);
This implies that a URL calling your PHP page would have a shape similar to the following:
http://foo.bar/?parameters=<the query here>
The important thing to include in the URL is ?; when a URL is parsed, the ? signals that whatever comes afterward is a URL-encoded query.
Thus, in your javascript:
window.location.href = "/search/?parameters=" + encodeURIComponent(query);
Then your existing code should work.
Just do
on client-side
window.location.href = "/search/" + query;
and on server-side
$val = urldecode($_GET['parameters']);

taking unset() and rewriting this function in javascript

I have a PHP function on my website as follows:
$url = $_SERVER["REQUEST_URI"];
$x = $url;
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['page']);
$string = http_build_query($params);
which removes the 'page' parameter from the current URL.
What I need to do now however is write the same function but in javascript, to use in an onclick. I have searched and come up with the following solution:
$('#localtab').click(function() {
return location.href=location.href.replace(/&?page=([^&]$|[^&]*)/i, "");
});
this is working but as this is the first ever time I've coded regex, am I doing this page reload in the best possible way? I don't wanna risk knocking off any other parameters, although there are none others containing the phrase 'page'.
For example, is it best to check first if the page parameter is present in the URL (because sometimes it isn't in fact) and how would I do that?
Thanks.
The thing is RegExp is supposed to be used for patterns. And it will only work if the pattern matches. No you don't need to check if page exists before clearing it.

quick Jquery .load chat not working

I have the following jquery:
var msg = $("#newmessage").val();
var user = $("#userchat").val();
var filename = "/inc/chat.php?msg="+msg+"&user="+user;
alert(filename);
$("#chatData").load(filename);
when 'msg' does not have a space in it, the #chatData loads fine and posts the variable.
When it does have a space in it, I just get a blank div. With no information in it whatsoever.
if I load up the php file that inserts the data into the DB, and manually type the same GET data, it works fine.
Whats going on?
Try using
encodeURIComponent(msg)
Also consider:
$("#chatData").load('/inc/chat.php',
{ 'msg' : $("#newmessage").val(), 'user' : $("#userchat").val() }
);
URI encoding is done, if needed, by jQuery.
You don't have to worry about URI encoding as the POST method is used since data is provided as an object (source).
In this case POST may be better than GET anyways.
If you were using $_GET in your php file you will need to use either $_REQUEST or $_POST.
you have to encode your message before sending using encodeURIComponent() and decode on server-site using urldecode().
doing this will escape/encode special characters that aren't allowed in an url or that will break your query-string otherwise (like a & in your message that would otherwise start a new argument).
You can use either escape, encodeURI or encodeURIComponent, but escape is the only method supported by every browser, although most modern browsers support the latter.
Reference
Take a look at this document, which does a good job of explaining all three.
The space could be causing an issue - try javascript's encodeURIComponent():
var msg = encodeURIComponent($("#newmessage").val());
var user = encodeURIComponent($("#userchat").val());

Add more GET data for Javascript

I am using the javascript below to send information from one website to another, but I don't know how to add more data. ?url is fine. I'm not sure how to add more data to the javascript. I would like to add an ?img, a ?title ... i tried a few times but no luck. Help please.
JavaScript
onclick="window.open('http://mysite.com/submit.?url='+(document.location.href));return false;"
PHP
$url = $_GET['url'];
Separate the parameters with &.
http://mysite.com/submit?param1=value1&param2=value2&param3=value3
You should also encode your values with encodeURI().
You wouldn't add ?moreParm...etc, you use an ampersand (&) to add additional parameters.
var url = `http://mysite.com/submit.?url=' + document.location.href;
url += '&anotherParam=foo`;
// etc.
You need to escape all parameter values accordingly.
I'd also recommend moving it into a function so your embedded JS doesn't become impossible to read.

Categories