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
Related
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']);
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 have the following code in my page.
<script>
var url = "http://localhost/login.aspx?returnUrl=/ABC/abc.aspx>_no=1234567&code=SC";
window.location.href = url;
</script>
when i load the page, it redirect to
http://localhost/login.aspx?returnUrl=/ABC/abc.aspx>_no=1234567&code=SC
the parameter >_no changed to >_no
Is there any method to keep >_no remain unchange after redirect?
It is not allow to use other parameter name insteand of >_no in my project.
The problem not just happen in localhost.
Thanks!
You have arrived at a situation where you have generated an HTML encoded value value even though you didn't mean to :)
> is the HTML encoded value for the greater than character - >. You could try make sure that your gt_no parameter is the first parameter. This way, it will not be next to the ampersand (&) character and won't be interpreted as a HTML encoded value.
You could try URL Encoding the ampersand that is causing the issue:
var url = "http://localhost/login.aspx?returnUrl=/%26gt_no=1234567&code=SC";
var url = "http://www.google.com/login.aspx?
returnUrl=/ABC/abc.aspx>_no=1234567&code=SC";
window.location.href = url;
I have a variable in javascript returned by AJAX which may contain a simple string or a href code like EXAMPLE. I have to detect whether it is a link or simple string and display accordingly.
i.e. if it is a link then a hyperLink is to be displayed with text as EXAMPLE or if it is a simple string then it has to be displayed as it is.
I can able to do it in angular using
<span ng-bind-html-unsafe="name_of_variable">
How can I do it in javascript code with javascript variable?
If the variable data contains the response from AJAX, do:
document.getElementById('where_to_put_it').innerHTML = data;
If data looks like a hyperlink, the HTML will be parsed and it will be clickable. If it's plain text, it will just be put into the document that way.
Maybe something like this is what you're looking for with your calendar plugin:
var match = data.match(/<a\s+href=['"](.*?)['"]\s*>(.*?)<\/a>/i);
if (match) {
event = { title: match[2],
url: match[1]
};
} else {
event = { title: data };
}
U need to check the string of data contains url , i believe think below url will help u out.. Check if a Javascript string is a url Regular Expression to find URLs in block of Text (Javascript) How to find if a text contains url string
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());