Javascript Truncating String During Concatenation
Solution 1:
If content
has especial characters, let's say it's something like You & I forever
, then your data
variable would look like this:
post_id=1&content=You & I forever&_token=bla
See the problem? Content is ending right after You
, because the ampersand isn't encoded. So you should do something like this:
var data = 'post_id=' + post_id + '&content=' + encodeURIComponent(content) + '&_token=' + $('#token').val();
With that, your data
variable would look like this:
post_id=1&content=You%20%26%20I%20forever&_token=bla
And it would all work smoothly
Solution 2:
Update
@Piyin's answer above is a better and cleaner way to do it! However I leave my long and boring method it may save for another purpose.
Older Solution (not cool :) )
Because I needed to fix this problem as quick as possible (in production lol) I used this work around! Until we get a better answer if you are in trouble you can use this :)
1) Create a hidden form
<form id="content-form">
<input type="hidden" name="post_id"id="content-post-id">
<input type="hidden" name="content"id="content">
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
2) Use JQuery (or whatever) to pass the data to this form
var post_id = $('#post-id').val(); //get post id
$('#content-post-id').val(post_id); //put in formvar content = CKEDITOR.instances.editor.getData(); //get content
$('#content').val(content); //put in form
3) Serialize the form with JQuery .serialize()
(Instead of "manually" doing it)
var data = $('#content-form').serialize();
If you are not using JQuery this may not be cool except you have a substitute for serialize in whatever you are using!
This may not be a good solution but it works! Am sure looking in depth (code) what the serialize() function does can help me(or maybe you) understand how to correctly serialize data in complex situations like the one I had.
Post a Comment for "Javascript Truncating String During Concatenation"