0

I'm using the code below to trim data to be sent to an SQL on a PHP page.

<script>$(function() { 
                $("#nameselect").change(function() {
                $("#jobnoselect").load("getter.php?choice=" + $.trim($("#nameselect").val()).replace(' ', '+'));
                $("#pagetable").empty();
                });

            });
   </script>

Now it does work if the choice made is "Two Words" but if it is "Three Words Here" it does not and returns blank results. I'm not familiar with this language and another developer gave me this snippet a long time ago. Can anyone offer any help with it?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Des Hutch
  • 293
  • 1
  • 3
  • 13

4 Answers4

1

Replace using string as pattern is not global.

Change the code

$.trim($("#nameselect").val()).replace(' ', '+')

to

$.trim($("#nameselect").val()).replace(/\s/g, '+')
Michal Brašna
  • 2,293
  • 13
  • 17
0

If you use php instead of javascript:

$foo = preg_replace( '/\s+/', ' ', $foo );
Ana Claudia
  • 501
  • 6
  • 16
0

Use encodeURIComponent so that the space will be converted and sent.

<script>
$(function() { 
    $("#nameselect").change(function() {
        $("#jobnoselect").load("getter.php?choice=" + encodeURIComponent($("#nameselect").val()));
        $("#pagetable").empty();
    });
});
</script>

And in your php page use urldecode to retrieve the content.

Karthick Kumar
  • 2,349
  • 1
  • 17
  • 30
0

You're better off serializing the value than actually replacing spaces with plus-signs. This is a better way:

<script type="text/javascript">
   $(function() { 
   $("#nameselect").change(function() {
      $("#jobnoselect").load("getter.php?choice=" + $("#nameselect").serialize());
      $("#pagetable").empty();
   });
});
</script>
Tularis
  • 1,506
  • 1
  • 8
  • 17