I'm implementing Google's Instant Search in my application. I'd like to fire off HTTP requests as the user types in the text input. The only problem I'm having is that when the user gets to a space in between first and last names, the space is not encoded as a +, thus breaking the search. How can I either replace the space with a +, or just safely URL Encode the string?
$("#search").keypress(function(){
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val();
var options = {};
$("#results").html(ajax_load).load(query);
});
Try encodeURIComponent.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Example:
var encoded = encodeURIComponent(str);
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Better way:
encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".
If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
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) {.......});
use jQuery.param().....
Description: Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.
try this one
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val().replace(/ /g, '+');
Related
I have a javascript code that generates emails with links in the body.
Some of the links have spaces within the link, so the link gets cut of.
I tried replacing the spaces with the asacii code but it didn't work.
var lineBreak = "%0D%0A";
function GetMailToInfo(attachment, body) {
attachment = attachment ? attachment.replace(" ","%0D%0A") + lineBreak + lineBreak : "";
body += attachment + signature;
window.location.href = "mailto:" + emailTo + "?subject=" + subject() + "&body=" + body;
}
Any idea on how to solve that?
Use encodeURIComponent to properly escape special characters in URLs:
window.location.href =
"mailto:" + encodeURIComponent(emailTo) +
"?subject=" + encodeURIComponent(subject()) +
"&body=" + encodeURIComponent(body);
Your problem is most likely because String.replace only replaces the first occurrence when using a string as the first parameter. See this MDN documentation.
I would suggest either looping:
while (attachment.indexOf(" ") >= 0) {
attachment = attachment.replace(" ", "%0A%0D");
}
Or using RegEx to perform a pattern-based replacement.
However, Quentin's solution is the proper way to go about encoding strings to be safe for URI use. My answer here is for the more general case where it may not be a URI string.
i am using inline editing in my form's text area where it works as it should be , but when the text are string contains & sign it is only saving up to the & sign. so how can i url encode in javascript the & sign so my php scripts gets it and save in mysql as & again.
this is my current code and desc is the string that might contain & sign occasionally
var field_userid = $(this).attr("id") ;
var desc = $(this).val() ;
$.post('includes/update-property-modal.php' , field_userid + "=" + desc, function(data){ });
If you want to do it the way you are currently do it, you need to encode it.
$.post('includes/update-property-modal.php' , field_userid + "=" + encodeURIComponent(desc), function(data){ });
Why not just use an object?
var self = this,
params = {};
params[self.id] = self.value;
$.post('includes/update-property-modal.php',params,function(data){
// whatever thine wish may be
});
This should manage the existence of the '&' internally, and really is the better way to send parameters with $.ajax().
Use encodeURIComponent() to escape all characters except the following: alphabetic, decimal digits, _ - . ~ ! * ' ( )
$.post('includes/update-property-modal.php', field_userid + "=" + encodeURIComponent(desc), function(data) {});
But in the case of jQuery's ajax() and your example, it is better to use it this way:
var params = {
$(this).attr('id'): $(this).val()
};
$.post('includes/update-property-modal.php', params, function(data) {});
I want to send http request using node.js. I do:
http = require('http');
var options = {
host: 'www.mainsms.ru',
path: '/api/mainsms/message/send?project='+project+'&sender='+sender+'&message='+message+'&recipients='+from+'&sign='+sign
};
http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
}).on('error', function(e) {
console.log('ERROR: ' + e.message);
});
When my path like this:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester_response&recipients=79089145***&sign=2c4135e0f84d2c535846db17b1cec3c6
Its work. But when message parameter contains any spaces for example tester response all broke. And in console i see that http use this url:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester
How to send spaces. Or i just can't use spaces in url?
What you are looking for is called URL component encoding.
path: '/api/mainsms/message/send?project=' + project +
'&sender=' + sender +
'&message=' + message +
'&recipients=' + from +
'&sign=' + sign
has to be changed to
path: '/api/mainsms/message/send?project=' + encodeURIComponent(project) +
'&sender=' + encodeURIComponent(sender) +
'&message=' + encodeURIComponent(message) +
'&recipients='+encodeURIComponent(from) +
'&sign=' + encodeURIComponent(sign)
Note:
There are two functions available. encodeURI and encodeURIComponent. You need to use encodeURI when you have to encode the entire URL and encodeURIComponent when the query string parameters have to be encoded, like in this case. Please read this answer for extensive explanation.
The question is for Node.js. encodeURIcomponent is not defined in Node.js. Use the querystring.escape() method instead.
var qs = require('querystring');
qs.escape(stringToBeEscaped);
The best way is to use the native module QueryString :
var qs = require('querystring');
console.log(qs.escape('Hello $ é " \' & ='));
// 'Hello%20%24%20%C3%A9%20%22%20\'%20%26%20%3D'
This is a native module, so you don't have to npm install anything.
TLDR: Use fixedEncodeURI() and fixedEncodeURIComponent()
MDN encodeURI() Documentation...
function fixedEncodeURI(str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
MDN encodeURIComponent() Documentation...
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
Why to Not Use encodeURI() and encodeURIComponent()
It is really not recommended to use encodeURI() and encodeURIComponent(), as they are insufficient to properly handle URI or URL encoding directly. Just like at this piece...
'&message=' + encodeURIComponent(message) +
Let's say that the message var is set to this: "Hello, world! (Really hello!)". So what is that evaluated to?
console.log('&message=' + encodeURIComponent("Hello, world! (Really hello!)"));
Output:
&message=Hello%2C%20world!%20(Really%20hello!)
That's not right! Why weren't ( and ) encoded? After all, according to RFC3986, Section 2.2: Reserved Characters...
If data for a URI component would conflict with a reserved character's purpose as a delimiter, then the conflicting data must be percent-encoded before the URI is formed.
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
Parens are a sub-delim, but they are not being escaped by encodeURI() or encodeURIComponent().
I have a url which looks like this:
I want to replace: 1034749-184e-3467-87e0-d7546df59896 with another ID, is there any regex or similar replace method which will allow me to replace the ID using JavaScript between the 'image/' and '?' characters?
You could make this approximation expression:
/[0-9a-z]+(?:-[0-9a-z]+){4}/i
Match a bunch of hexadecimals, followed by 4 sections, each starting with a dash followed by a bunch of hexadecimals.
> var s = 'http://url/images/1034749-184e-3467-87e0-d7546df59896?w=600&r=22036';
> console.log(s.replace(/[0-9a-z]+(?:-[0-9a-z]+){4}/i, 'something-else'));
http://url/images/something-else?w=600&r=22036
/images\/[^?]+/ would match, but it would replace images/ as well.
Fortunately you can pass a callback to .replace:
url.replace(/(images\/)[^?]+/, function($match, $1) {
// results in "images/<some-ID>"
return $1 + theNewId;
});
If you have a reference to the DOM element anyway, you can also just replace the last step of the path:
element.pathname =
element.pathname.substring(0, element.pathname.lastIndexOf('/') + 1) + newId;
Yes, just do this:
var url = document.getElementById("yoururlid").src;
url = url.split("/");
var newUrl = url[0] + url[1] + url[2] + url[3] + newURLID;
Why not just do this:
document.getElementById("yoururlid").src="http://url/images/" + newId + "?w=600&r=22036";
I need help in writing regular expression:
part of my string is fixed and another part of its variable.
only if fixed AND variable string exist i need to alter the string other wise no.
Fixed string:example: AA.BBB.COM
Variable string (may or mayn't exist ): US, but if exist it will be always two letter string with any combination of letter.
In below string if I have variable two letter string exist I want to append “.new”
1 ) https://XY**.US**.AA.BBB.COM
Output: https:// XYZ12**.US.NEW**.AA.BBB.COM
2 ) https://XY.UK.AA.BBB.COM
Output: https:// XYZ12.UK.NEW.AA.BBB.COM
3) https://XY.AA.BBB.COM (no variable string so no change)
Output: https:// XY.AA.BBB.COM
Thanks for your help .
Raghav
Something like the following should get you started, there are other methods. Splitting and parsing might suit better depending on your real requirements:
var s = 'https://XY.US.AA.BBB.COM';
var t = 'https://XY.UK.AA.BBB.COM';
var u = 'https://XY.AA.BBB.COM';
var re = /(\.)(UK|US)(\.)/;
alert(
s.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
t.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
u.replace(re, '$1' + '$2' + '.NEW' + '$3')
);