Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string variable with spaces

In the following code:

    <script type="text/javascript">
        function updateView(set) {
            $.post("<?php echo base_url("/show_cards/load_page")."/"; ?>"+set, function( data ) {
                $( "#content" ).html( data );
            });
        }
    </script>

'set' is a string variable which can have spaces in it. I'm noticing when it has spaces it's not working correctly. How can I fix this?

EDIT: For clarity, I'd like to keep the spaces intact.

like image 214
rotaercz Avatar asked Dec 12 '22 10:12

rotaercz


1 Answers

NOTE: that $.trim() is now deprecated for .trim()

Use set.trim() to remove leading or trailing spaces and either

set.replace(/ /g,"+")  

or

encodeURI(set)

to keep the spaces inside the string
(refer When are you supposed to use escape instead of encodeURI / encodeURIComponent?)

To do both in one go just chain them

set.trim().replace(/ /g,"+")

Note you may use %20 instead of the plus if you prefer.

But is it not a parameter? If so, perhaps you want to pass it as

$.post("<?php echo base_url("/show_cards/load_page")."/"; ?>",
  {"set":set.trim().replace(/ /g,"+")},
like image 86
mplungjan Avatar answered Dec 28 '22 03:12

mplungjan