1

I'm creating a social network and I wanna include the #hashtag feature...problem is posts are cut at the #. For example, if I wrote, "Hello #StackOverflow community!", the resulting string would be "Hello ". Below are the code and a debug screenshot.

$("#btnPostStatus").click(function () {
    var post = $("#txtNewStatus").val();
    $.post('/Logic/postStory?text=' + post.toString() + '', null, function(result) {
        alert(result);
        location.reload();
    });
});
coudy.one
  • 1,382
  • 12
  • 24
  • 4
    If you want to send actual POST data, you need `$.post('/Logic/postStory', { text: post }, function(result) { ... })` –  Sep 10 '18 at 10:16

3 Answers3

1

Encode them properly, via encodeURIComponent:

'/Logic/postStory?text=' + encodeURIComponent(post)

It's important to do that for any value you put in a URL query string. (In fact, keys should be done too, but encodeURIComponent("text") is "text" so you can get away with not doing it for that particular key, and any other that's just made up of letters and digits.)

Also note that both the .toString() on post and the + '' are unnecessary.


Note that you're including the text parameter in the URL (e.g., like a GET parameter), not as POST data. If that's really what you mean to do, that's fine, but if you meant to include it in the POST data, you need to provide it as the second argument: $.post('/Logic/postStory', {text: post}, ...). (And if you pass it that way, as an object, jQuery will handle doing the URI-encoding for you.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

This happens because the # sign in a URL is interpreted as a so called named anchor. Try encoding the URL like this:

$.post('/Logic/postStory?text=' +  encodeURIComponent(post.toString()), ...

BTW, the + '' is not necessary in your case.

Fabian Lauer
  • 8,891
  • 4
  • 26
  • 35
0

# should be replaced with %23

Please check HTML URL Encoding Reference for more details.

You can encode request using encodeURIComponent or simply by replacing # with %23 in your code.

I would suggest to encode whole URL.

Petr Lazarev
  • 3,102
  • 1
  • 21
  • 20