sending string with & sign in ajax jquery post - javascript

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) {});

Related

Search and remove a parameter with optional character from URL

I'm looking to remove a parameter from a URL with a click event. The issue is that the parameter can either have an & before it or not. So the form is either search=MYSEARCHTERM or &search=MYSEARCHTERM.
I have the following which appears to work fine for one or other but not both. I was thinking that I could have an if / else statement one of which contains something like this. (Excuse the crappy regex but I've never written it before)
var searchKeywordRegx = new RegExp(/(?:&)/ + 'search=' + searchKeyword);
$('.searchKeyword').click(function() {
$(this).remove();
var searchKeywordRegx = new RegExp('search=' + searchKeyword);
console.log(searchKeywordRegx);
document.location.href = String( document.location.href ).replace(searchKeywordRegx , "" );
});
Am I way off base here?
Use ? to make something optional in a regexp:
var searchKeywordRegx = new RegExp('&?search=' + searchKeyword);
Seems you can do this without regular expressions. If you simply remove that portion of the document location's "search":
document.location.search = document.location.search
.replace('search=' + encodeURI(searchKeyword), '');

Removing Url and Include Id using Regex and Jquery

I am new to Regex and my question is how can i include the ID from the url and remove it using Regex? because as of now , It only removes the actionMe=reload&Id= but the Id still return so after removing it and replacing with new Url, the old id is still included plus the new ID,
Example, Before removing and replacing the Url:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=15
And After Removing and replacing the url , it goes like this:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=1615
This is my Code Snippet:
var sss = $("#Id").val();
if (window.location.href.indexOf("&actionMe=reload&Id=") > -1) {
var regex = /(\&|&)actionMe=reload&Id=/;
var location = window.location.href;
if (regex.test(location)) {
window.location = location.replace(regex, "&actionMe=reload&Id=" + sss)
}
}
Thanks for Answering guys:)
you can use this code to update url parameters
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
I got it here
Now, in your case, you can use it like this
var url = window.location.href;
var sss = $("#Id").val();
var newUrl = updateQueryStringParameter(url, "id", sss);
//do whatever you want to newUrl
//to redirect to new url
window.location = newUrl;
Pretty sure all you need is /&Id=\d+/ as your RegExp. Don't need to select any of actionMe=reload unless you need that for specification (in that case, just add it back). The rest of your code works as intended, just your regex not selecting the precise part you were wanting.
Explanation:
The (\&|&) part of your regex is redundant, as & does not need to be escaped to work. As a matter of fact, since it's in parenthesis, you would end up capturing that & character, if you REALLY need that part, try (?:\&|&) to ignore the capture group. Your code replaced the matched regex, but did not include the number "15" after Id=, which is why it appended 15 after your edited version due to it not being matched and therefore not being replaced. Adding \d+ will select any trailing digits. This should give you the result you wanted.

Decoding URL parameters with JavaScript

This should be a simple task, but I can't seem to find a solution.
I have a basic string that is being passed through as a query string parameter like this one: This+is+a+message+with+spaces. I would like to decode that parameter using JavaScript to This is a message with spaces, but I cannot seem to get it to decode.
I've tried decodeURI('This+is+a+message+with+spaces') but the result still contains the + signs.
Yes it is true that decodeURIComponent function doesn't convert + to space. So you have to replace the + using replace function.
Ideally the below solution works.
var str_name = 'This+is+a+message+with+spaces';
decodeURIComponent((str_name + '').replace(/\+/g, '%20'));
Like it was pointed out already, decodeURI function doesn't convert + to space, but there are some things worth to realize here:
decodeURI is meant to be used for whole URI, i.e. it doesn't decode separators like ?, &, =, +, etc.
for decoding parameters decodeURIComponent should be used
(worth to have a look at: What is the difference between decodeURIComponent and decodeURI? )
string that you are trying to decode might actually contain + encoded as %2B, thus you should not replace + after the conversion since you might lost + signs that you actually want there, e.g. something?num=%2B632+905+123+4567 should become:
something?num=+632 905 123 4567
since you are probably going to extract the number: +632 905 123 4567
So the correct way to do this is:
var str = 'something?num=%2B632+905+123+4567';
decodeURIComponent( str.replace(/\+/g, '%20') );
The plus sign is not encoded/decoded. To see the decode function working, you need to pass a encoded URI first. Take a look:
encodeURI( "http://www.foo.com/bar?foo=foo bar jar" )
Will generate: http://www.foo.com/bar?foo=foo%20bar%20jar, i.e., the encoded URI.
decodeURI( "http://www.foo.com/bar?foo=foo%20bar%20jar" )
Will generate: http://www.foo.com/bar?foo=foo bar jar, i.e., the decoded URI.
The below code will decode and gives you the params in form of objects
export function getParamsFromUrl(url) {
url = decodeURI(url);
if (typeof url === 'string') {
let params = url.split('?');
let eachParamsArr = params[1].split('&');
let obj = {};
if (eachParamsArr && eachParamsArr.length) {
eachParamsArr.map(param => {
let keyValuePair = param.split('=')
let key = keyValuePair[0];
let value = keyValuePair[1];
obj[key] = value;
})
}
return obj;
}
}
I created my own string methods to support the needed encoding/decoding. These methods will handle the + encoding and decoding properly, allowing you to have plusses (+) in your string and still have the original spaces be encoded as +'s.
String.prototype.plusEncode = function() {
return encodeURIComponent(this).replace(/\%20/gm,"+");
}
String.prototype.plusDecode = function() {
return decodeURIComponent(this.replace(/\+/gm,"%20"));
}

How do I extract data from this URL using javascript?

I need to build a string from the data contained in this url using javascript/jQuery:
http://www.example.com/members/admin/projects/?projectid=41
The string returned should look as follows:
/ajax/projects.php?projectid=41
Obviously if there is no query string present, the method should still return a string of the same format minus the query string. e.g.
http://www.example.com/members/admin/messages/
should return...
/ajax/messages.php
I've made numerous attempts, all met without success due to my poor grasp of regular expressions, and it feels as though the ore I rad on the subject the more I am confusing myself.
If someone could help it would be greatly appreciated.
EDIT: The 'admin' portion of the url is a users 'username' and could be anything.
Here's a function that will take your URL and return a new one according to the rules you've listed above:
function processURL(url) {
var base = "", query = "";
var matches = url.match(/([^\/\?]+)(\/$|$|\?|\/\?)/);
if (matches) {
base = matches[1];
matches = url.match(/\?[^\?]+$/);
if (matches) {
query = matches[0];
}
}
return("/ajax/" + base + ".php" + query);
}
And, a test app that shows it working on a bunch of URLs: http://jsfiddle.net/jfriend00/UbDfn/
Input URLs:
var urls = [
"http://www.example.com/members/admin/projects/?projectid=41",
"http://www.example.com/members/bob/messages/",
"http://www.example.com/members/jill/projects/",
"http://www.example.com/members/alice/projects?testid=99",
"http://www.example.com/members/admin/projects/?testid=99"
];
Output results:
/ajax/projects.php?projectid=41
/ajax/messages.php
/ajax/projects.php
/ajax/projects.php?testid=99
/ajax/projects.php?testid=99
To explain, the first regular expression looks for:
a slash
followed by one or more characters that is not a slash and not a question mark
followed by one of the four sequences
/$ a slash at the end of the string
$ end of the string
? a question mark
/? a slash followed by a question mark
The point of this regex is to get the last segment of the path that comes before either the end of the string or the query parameters and it's tolerant of whether the last trailing slash is there or not and whether there are any query parameters.
I know exactly what you are trying to do. In order to do it your way just split your string on question mark and then use last item form your array.
var data = your_url.split('?');
var newUrl = '/ajax/projects.php' + (data.length > 1 ? data[length-1] : "");
and you will have your url.
But what you can do is execute same url using your Script just add one parameter IsAjax=true and then check it in codebehind and execute your ajax logic.
e.g.
$('#somelink').onclick(function(){
$.ajax({ url: $(this).href, data { IsAjax: true } .... }
});
Using this way you will have more robust app.
I'll assume that by
http://www.example.com/members/admin/messages/
should return...
/ajax/members.php
you meant - should return...
/ajax/messages.php
If that is the case try
var query = url.split('?');
var paths = query[0].split('/');
var path = paths.pop();
if (path == '') //when there is trailing slash
path = paths.pop();
if (query.length == 1) //no query string
newurl = '/ajax/' + path + '.php';
else //query string
newurl = '/ajax/' + path + '.php?' + query[1];
I'm sure it can be made simpler and better, but that might give you a start.
var str = "http://www.example.com/members/admin/projects/?projectid=41";
var newStr = "/ajax/" + str.split("/").slice(-2).join(".php");
console.log(newStr);

URL Encode a string in jQuery for an AJAX request

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, '+');

Categories

Resources