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']);
Related
I want to set a specific metatitle to a javascript hashed url. I want to set it via PHP so that when google crawls it the metatitle is already there.
An example of a page: https://weslaydragons.com/en/shop/#!/men+long+sleeve+shirts?q=P25
In this url /en/shop/ is the wordpress page, and #!/men+long+sleeve+shirts?q=P25 is set by javascript.
I have this code in the functions.php to try to set the title:
if (is_page(194) and (strpos($url, 'men+long+sleeve+shirts') !== false))
{$new_title = "long sleevetitle";};
return $new_title;
But how do I get 'men+long+sleeve+shirts' or '?q=P25' in the $url variable?
Is there a way to get the user-entered url in PHP?
You can use combination of strpos() and substr();
Like this:
$string = "https://weslaydragons.com/en/shop/#!/men+long+sleeve+shirts?q=P25";
var_dump(substr($string,strpos($string,'?'))); // output '?q=P25'
It will cut whole string and leave only the part from ? to end.
Explode method:
Or you can use alternate, explode method like this, which will ensure that it will target only last element with question mark.
$string= "https://weslaydragons.com/en/shop/#!/men+long+sleeve+shirts?q=P25";
$string2= explode('?',$string);
var_dump(end($string2)); // output 'q=P25'
Edit:Both methods would work with "#" also, just replace '?' with '#'.
Refs:
http://php.net/manual/bg/function.strpos.php
http://php.net/manual/bg/function.substr.php
http://php.net/manual/bg/function.end.php
http://php.net/manual/bg/function.explode.php
I am wondering if how am i able to change the element data by .replace() if i use handlebar js to generate html elements.
For instance i have this role of p tag which display a row of data by handlebar js:
<p id="pre-region">{{region}}</p>
and the result of it is
1,44
and i 'd like to change it to
1+44
If you haven't had any experience of handlebar js then consider the tag be
<p id="pre-region">1,44</p>
how should i change from 1,44 to 1 +44?
UPDATE 1
Here should be an extersion for my question. I am passing the HTML element inside pre-region into an href in order to update my website by Ajax.
After i have converted all the comma in to "+" the API retrieve special character "&B2" which equal to the symbol "+" and the API goes error.
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4
This is how may API looks like at the moment
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1+4
should be the solution
I haven't had any experience of handlebars.js but from my point of view, you can just put the code just before the </body>:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(',', '+');
</script>
I'll check out the handlebars js in case it does not work.
Update:
As you mentioned in the comment, if you need to use it in the HTTP request/URL, you may handle the string using decodeURIComponent(yourstring):
decodeURIComponent('1%2B44'); // you get '1+44'
Read more about decodeURIComponent() method from this. In URL, it should be encoded as region=1%2B44 in your case; while it should be decoded if you want to use it in your JavaScript code or display in the web page.
Update 1
You should encode your string when it's used as a part of parameter of HTTP request. Therefore, it looks good if the URL is:
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4
What you need to do is decode the string on your server side. I assume that you are in control of the server side. If you are using Node.js, you can just use decodeURIComponent() method to decode the parameter. If you're using Python or PHP as your server language, it should be something like decodeURIComponent() in that language.
Update 2
The solution above only replace the first occasion of comma to +. To solve that, simply use:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(/,/g, '+');
// Regular Expression is used here, 'g' for global search.
</script>
PHP has a replaceAll() method, so we can add that method to String.prototype like below if you want:
<script>
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
}
// Another method to replace all occasions using `split` and `join`.
</script>
Alright, so this is my first answer ever on stack overflow so I'm alien to this whole thing but here we go:
You could try this code in another js file that runs after handlebars:
var pre = $('#pre-region'); // defines a variabe for the element (same as
// document.getElementById('pre-region'))
var retrievedRegion = pre.innerHTML;
var splitten = retrievedRegion.split(',');
var concatenated = parseInt(split[0]) + parseInt(split[1])
retrievedRegion.innerHTML = "'" + concatenated) + "'";
or using replace():
retrievedRegion.replace(',','+')
I am trying to pass a text by parameter (with whitespaces) to the load function and it seems it doesn't work.
Currently i am doing this:
var text ="hello world this is an example";
$("#selector").load("http://"+ document.domain + "/myfunction/"+text);
Is there any way to do it?
If i call the function by URL directly, not with jQuery, it works well.
Thanks.
You should encode "text" with encodeURI:
var text = encodeURI('hello world this is an example');
This will ensure that your whitespaces are replaced with url compatible characters, which your browser does internally when you're directly accessing the url.
Calling the function by URL directly might works well in your browser. But it is not future proof. You must encode your url with encodeURI function. After appending user given data.
var text ="hello world this is an example",
url = encodeURI("http://"+ document.domain + "/myfunction/"+ text);
$("#selector").load(url);
And on server side you can do something like this to get back user entered data.
$data = urldecode($_SERVER['REQUEST_URI']);
// This will return
// /myfunction/hello world this is an example
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());
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.