1

Explanation

I have the following code in PHP that allows the user to select a name from a drop-down, then pass that name as a string over to a JavaScript function:

<?php
                include('./db.php');
                $PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
                ?>
                <select class="navbar-inverse" placeholder="PM Name" name="PMName" onchange="showUser(this.value)">
                <?php
                while ($row = mysqli_fetch_row($PM)) {
                $selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
                printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
                }
                ?>

The JavaScript function then reads the string:

function showUser(str) {
  if (str !==".PM") {
    if (str=="") {
      document.getElementById("txtHint").innerHTML="";
      return;
    } 
  }
  $("#txtHint").load( "getuser.php?q="+str );
    console.log(str);
}

and is supposed to place the output of getuser.php?q=John%Doe into the txtHint DIV.

Issue

the str value does not APPEAR to be fully passing into the $("#txtHint").load( "getuser.php?q="+str ); line of code.

When I look at my console, I see the following once the JavaScript function fires:

HR finished loading: GET "http://localhost/getuser.php?q=John"
John Doe

If I change the code to read just $("#txtHint").load( "getuser.php?q=");, (without passing the str variable,) it works fine and loads the getuser.php page into the DIV, (of course, without a name I don't get back any info, but it works...)

What am I doing wrong here? If the console.log(str) is outputting John Doe, then obviously the entire string is John Doe, so why is my console outputting ?q=John? and causing getuser.php not to load into the DIV?

I'm very confused here....

1
  • Always read the documentation, if you had, you would notice that there is a data argument for load, and you can just do $("#txtHint").load( "getuser.php", {q : str} ); Commented Oct 30, 2014 at 21:26

1 Answer 1

3

You need to encode your string if you want to send it as a query variable:

$("#txtHint").load( "getuser.php?q="+encodeURIComponent(str));
Sign up to request clarification or add additional context in comments.

1 Comment

Beauty. Thank you! I figured it had something to do with encoding the actual string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.