1

I am trying to pass data back to the server and then use the reply to update the browser page. My code for a SELECT input is as follows;

<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
                        <?php 
                            $MC = $_SESSION["MatchCapt"];
                            player_load($MC);
                        ?>
                        >
                </select>

The script code is as follows;

<script>
    function findTeleNo(that){
    alert("I am an alert box!" + that);
    var xhttp;
    if (window.XMLHttpRequest) {
        // code for modern browsers
        xhttp = new XMLHttpRequest();
        } else {
        // code for old IE browsers
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("TeleNo").value = this.responseText;
        }
      }
    };
    xhttp.open("GET", "findTeleNo.php?q=" + that, true);
    xhttp.send();
</script>

The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.

And the PHP file is as follows;

<?php
$MatchCaptain  = $_REQUEST["q"];
$teleNo = "";
  $db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
    $database = "matchmanagementDB";
    $db_found = mysqli_select_db($db_handle, $database);
    if ($db_found) {
    $SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
    $result = mysqli_query($db_handle, $SQL); 
    $ufullName = split_name($MatchCaptain);
    while ( $db_field = mysqli_fetch_assoc($result) ) {
        $uName = $db_field['FirstName'];
        $uName = trim($uName);
        $Surname = $db_field['Surname'];
        $Surname = trim($Surname);
        $fullName = $uName." ".$Surname;
        if ($fullName == $ufullName )
        {
            $teleNo = $db_field['TeleNo'];
            break;
        }
        }
}
echo $teleNo;

function split_name($name) {
    $name = trim($name);
    $last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
    $first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
    $ufullName = $first_name." ".$last_name;
    return $ufullName;
}
?>

The php file requests the q variable from the url and makes it $MatchCaptain. This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script. The field id I am trying to update is;

<p><b>Telephone Number:&nbsp;</b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>

The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that. Any help as to how I get this working would be grateful.

DaveTheGolfer
  • 39
  • 1
  • 8
  • For starters, **this.value** is probably not returning what you want. A select is a bit trickier than that. See [here](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript). – S. Imp Mar 01 '18 at 21:46
  • Secondly, just appending the value returned from the select (e.g., "Joe Bloggs") is also problematic -- what is this value has spaces or slashes or ampersands in it that break the resulting url? Consider using [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) function. – S. Imp Mar 01 '18 at 21:47
  • Third, your PHP script doesn't bother to check for errors with your mysqli statements. You should always check the result of mysqli_connect or mysqli_select_db for errors. – S. Imp Mar 01 '18 at 21:49
  • #S. Imp Thanks for the comments. The PHP script works okay in other parts of my code with out the need for checking for errors, so I am not certain this is stopping the code working. The PHP code also cleans up the select value to a first name and surname and then concatenates it back to a full name. I am aware from other code I have tried that the url is shown as http://localhost/MatchManagement/findTeleNo.php?q=Freddie%20Grove, so no problem there. I know from the alert I put in the script that the this.value is returning the correct value. – DaveTheGolfer Mar 01 '18 at 22:11
  • well that sounds encouraging. Perhaps try moving that alert statement further down in the function until you find out where the holdup is? Try checking the browser console for any JS errors. Also check and make sure the PHP request is returning 200 and not 4xx or 5xx – S. Imp Mar 01 '18 at 22:28
  • I add an alert to the IF condition and showed that the xhttp variant was created. When added to the xhttp.onreadystatechange function I got no result. So I am assuming that the xttp.open or .send did not work. Will try checking the readyState and status. – DaveTheGolfer Mar 02 '18 at 09:58

1 Answers1

0

I have changed my script to

<script>
    function findTeleNo(that){
        var xhttp;
        if (window.XMLHttpRequest) {
            // code for modern browsers
            xhttp = new XMLHttpRequest();
            } else {
            // code for old IE browsers
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
            xhttp.send();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState === 4) {
                if (xhttp.status === 200) {
                    // OK
                    alert('response:'+xhttp.responseText);
                    document.getElementById("TeleNo").innerHTML = this.responseText;
                    // here you can use the result (cli.responseText)
                } else {
                    // not OK
                    alert('failure!');
                }
            }
        };
    };

</script>

The response shown by alert('response:'+xhttp.responseText); is correct and the line of code

document.getElementById("TeleNo").innerHTML = this.responseText;

does print the response to the web page.

DaveTheGolfer
  • 39
  • 1
  • 8