簡體   English   中英

將文本值onblur傳遞給同一頁面上的php函數,然后將值重新調整為另一個文本字段

[英]Passing a text value onblur to a php function on the same page and retuning a value to another text field

我正在尋找改進的形式,如果我使用提交按鈕和$ _POST(....),那不是問題。

我正努力添加新功能。 文本字段Code(fcode),我想使用onBlur = {this.codelookup}將此值傳遞給php函數,這將在mysql db中查找代碼,並返回一個name字段,我希望將此值添加到另一個文本字段名稱(fname)。

如果可以使用提交按鈕和$ _POST ['reset']語法,則可以使它正常工作,但是我試圖在退出(onblur)代碼文本字段時執行此操作,但是沒有任何麻煩。

下面的代碼塊中的功能“ codelookup”未完成,因為我不確定如何執行此操作。 其余代碼工作正常,沒有問題。 如果您刪除“ codelookup”,則php頁面的工作原理非常好,沒有任何問題。

任何幫助是極大的贊賞。

PS:我需要保持不變,可能選擇ajax。 我在這里提供了完整的頁面代碼,沒有密碼或用戶名,它們都包含在一個php文件中。

<!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <?php require ('header.php'); ?>
    <script>        
        function takemehome(){
            window.location.href = "./stock.php";           
        }
    </script>
</head> 
<body>
    <?php require ('nav.php'); ?>
    <main>
    <?php       
        if (!isset($_SESSION['username'])){
            echo "<div class=\"adminerror\" >";
            echo "You have not logged in.<br>"; 
            echo "You need to be logged in to use this page.<br>";              
            echo "</div>";
            echo '<script type="text/javascript">',
                     'setTimeout(function () {',
                     'window.location.href = "./stock.php";',
                     '}, 2000);',  
                     '</script>';
            exit();
        }
    ?>
    <div class="container">
    <!-- HTML Code amd data goes on here in theis section "container" -->
        <h2> Add a new stock to the list. </h2> 
        <!-- < ? php $_PHP_SELF ? >  
            <form action="< ? php $_PHP_SELF ?>" method="post" width="80%, align="left">
            <form action="projec_insert.php" method="post" width="80%, align="left">
        --> 

        <?php
            include 'mysqlinit.php';
            include 'functions.php';
            $fcode =  "";
            $fcodeErr = "";

            session_start();
            if (isset($_SESSION['username'])){
                $usercheck = $_SESSION['username'];             
            } else {
                $code = $name = $fullname = $qty = $brand = $cmmt = Null;
            }

            function codelookup(){
                // Create connection
                        $conn = mysqli_connect($servername, $username, $password, $dbname);


                        // Check connection
                        if (!$conn) {
                            die("Connection failed: " .  mysqli_connect_error());
                        } 
                        /*else {
                            echo "Connected to db <br><br>";    
                        }*/

                        $sql = "SELECT * FROM `stock` where `stock`.code = ' ????? ' ORDER BY `pt_brand` ASC";
                        $result = mysqli_query($conn, $sql);



                        if (mysqli_num_rows($result) > 0) {
                            // output data of each row
                            while($row = mysqli_fetch_assoc($result)) {
                                if ($brand == $row["pt_id"]) {
                                    echo "<option value=\"" . $row["pt_id"] . "\" selected=selected> " . $row["pt_brand"] . " </option>";
                                } else {
                                    echo "<option value=\"" . $row["pt_id"] . "\"> " . $row["pt_brand"] . " </option>";
                                }

                            }
                        } else {

                        }


                        mysqli_close($conn);    


            }


            if(isset($_POST['reset']))
            {                       
                $code = $name = $fullname = $qty = $brand = $cmmt = Null;
            }
            if(isset($_POST['submit']))
            {
                $code = $_POST['fcode'];
                $name = $_POST['fname'];
                $fullname = $_POST['ffullname'];
                $qty = $_POST['fqty'];
                $brand = $_POST['fbrand'];
                $cmmt = $_POST['fcmmt'];

                $errorflag = false;

                //clean the two text fields.
                $code = checkInput($code);  
                $code = strtoupper($code);              
                if (empty($name)){
                    $name="NOT DEFINED";
                    $name = strtoupper($name);
                } else {
                    $name = checkInput($name);
                    $name = strtoupper($name);
                }               
                if (empty($cmmt)){
                    $cmmt=NULL;
                } else {
                    $cmmt = checkInput($cmmt);
                    $cmmt = strtoupper($cmmt);
                }               
                $fullname = $code . " - " . $name;  
                if ($qty == ""){
                    $qty = 0;
                } else {
                    $qty = (int)$qty;
                }
                if ($brand == ""){
                    $brand = 1;                 
                } else {
                    $brand = (int)$brand;
                }

                if (empty($code)) {
                    $fcodeErr = " <== Required field";
                    echo "<div class=\"error\" >";
                    echo "Error: Stock Code field is required to be set. <br>";                                     
                    echo "</div>";
                    //echo "<script>alert('Errors xx have occured missing fields on form.')</script>";
                    //exit();   
                } else {

                    // Create connection
                    //$conn = mysqli_connect($servername, $username, $password, $dbname);
                    // Check connection
                    if (mysqli_connect_error()) {
                        echo "<div class=\"error\" >";
                        echo "Connection to DB has failed: " .  mysqli_connect_error() . "<br>";
                        echo "Details of coneection string <br>";
                        echo "Server:" . $servername  . "<br>";
                        echo "Username:" . $username  . "<br>";
                        echo "dbname:" . $dbname  . "<br>";
                        echo "</div>";
                        die("Connection to DB has failed: " .  mysqli_connect_error());
                    } else {

                        $sql = "INSERT INTO 
                                    `stock`(
                                            `username`,
                                            `Code`, 
                                            `Name`, 
                                            `Full-Name`, 
                                            `Qty`, 
                                            `Brand`, 
                                            `Comments`
                                    )
                                    VALUES(
                                        '$usercheck', '$code',";
                                    if ($name  == "")   {
                                        $sql = $sql . "'NOT DEFINED', ";
                                        $sql = $sql . "'$code - NOT DEFINED',";
                                    } else {
                                        $sql = $sql . "'$name',";                                       
                                        $sql = $sql . "'$code - $name',";
                                    }
                                    if ($qty == "" || $qty < 1)
                                    {
                                        $sql = $sql . "0, ";
                                    } else {
                                        $sql = $sql . "$qty, ";
                                    }
                                    if ($brand == "" || $brand < 2)
                                    {
                                        $sql = $sql . " 1, ";
                                    } else {
                                        $sql = $sql . "$brand, ";
                                    }
                                    if ($cmmt == "" )
                                    {
                                        $sql = $sql . "NULL )";
                                    } else {
                                        $sql = $sql . "'$cmmt') ";
                                    }


                        $result = mysqli_query($conn, $sql);
                        if (!result)
                        {
                            echo "<div class=\"error\" >";
                            echo "Connection to DB has failed: " .  mysqli_connect_error() . "<br>";
                            echo "</div>";
                            die("Connection to DB has failed: " .  mysqli_connect_error());
                        } else {
                            echo "<div class=\"sqlinst\" >";
                            echo "Record has been inserted.<br>";                               
                            //echo "SQL : " . $sql . "<br>";
                            echo "</div>"; 
                            $code = $name = $fullname = $qty = $brand = $cmmt = Null;
                        }
                        //$code = $name = $fullname = $qty = $brand = $cmmt = Null;;

                    }       
                } //if .. else from title field..

            } //end if isset isset($_POST['submit'])

            //close the mysql connection
            mysqli_close($conn);



        ?>
        <form method="post" id="add" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" width="80%, align="left">

            <table class="blueTableadd">
            <thead>
              <tr>
                <th class="ctr">Title</th>
                <th >Value</th>
              </tr>
              <thead>
              <tfoot>
                <tr>
                <td colspan="2">
                <span class="validx"> * Inidicates a Rrequired field </span> <br>
                <span class="validx"> Click <a href="./stock.php">here</a> to return to the projects list.</span>
                </td>
                </tr>
              </tfoot>
              <tbody>
              <tr>
                <td class="title" >Code:</td>
                <td class="inputval"><input type="text" maxlength=50 name="fcode" id="fcode" size="45" value="<?php echo htmlspecialchars($code);?>" placeholder="Paint Code eg Xf-1, H123 etc..">
                    <span class="validx">*<?php echo $stockErr;?></span>
                </td>
              </tr>                 
              <tr>
                <td class="title" >Name/Color:</td>
                <td class="inputval"><input type="text" maxlength=50 name="fname" id="fname" size="45" value="<?php echo htmlspecialchars($name);?>" placeholder="Paint Color Name">
                </td>
              </tr>                           
              <tr>
                <td class="title" >QTY OH:</td>
                <td class="inputval"><input type="text" maxlength=50 name="fqty" id="fqty" size="45" value="<?php echo htmlspecialchars($qty);?>" placeholder="Quantity On Hand: Number">
                </td>
              </tr>
              <tr>
                <td class="title" >Brand:</td>
                <td class="inputval">
                    <?php
                        include 'mysqlinit.php';    

                        // Create connection
                        $conn = mysqli_connect($servername, $username, $password, $dbname);


                        // Check connection
                        if (!$conn) {
                            die("Connection failed: " .  mysqli_connect_error());
                        } 
                        /*else {
                            echo "Connected to db <br><br>";    
                        }*/

                        $sql = "SELECT * FROM `PTBrand` ORDER BY `pt_brand` ASC";
                        $result = mysqli_query($conn, $sql);


                        echo "<select name=\"fbrand\"  style=\"width: 348px\" >";
                        echo "<option value=\"\">-- Select a Brand -- </option>";

                        if (mysqli_num_rows($result) > 0) {
                            // output data of each row
                            while($row = mysqli_fetch_assoc($result)) {
                                if ($brand == $row["pt_id"]) {
                                    echo "<option value=\"" . $row["pt_id"] . "\" selected=selected> " . $row["pt_brand"] . " </option>";
                                } else {
                                    echo "<option value=\"" . $row["pt_id"] . "\"> " . $row["pt_brand"] . " </option>";
                                }

                            }
                        } else {
                            echo "<option value=\"xxx\">-- No Brands Defined in DB -- </option>";
                        }
                        echo "</select>";

                        mysqli_close($conn);                    
                    ?>                                      
                </td>
              </tr>
              <tr>
                <td class="title" >Comments:</td>
                <td class="inputval">                   
                    <textarea name="fcmmt" rows="4" cols="50" maxlength=254 form="add"placeholder="Add your comments here."><?php echo htmlspecialchars($cmmt);?></textarea>
                </td>
              </tr>           
              </tbody>
            </table>

                <br>
                <br>
                <input type="submit" name="submit" class="btn btn-primary" value="Add New Record" />
                <input type="submit" name="reset" class="btn btn-default" value="Reset" >
                <input type="button" name="return" onclick="takemehome()" class="btn btn-default" value="Return/Back" />

        </form>
        <br>
        <br>

    </div>
    </main>
    <?php require ('footer.php'); ?>
</body>
</html>

我已經弄清楚了,現在正在工作。 同時使用ajax和php獲得我需要的功能。

<script>
    function getcodename(str) {
        if (str.length == 0) { 
            document.getElementById("fname").innerHTML = "";
            return;
        } else {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", "ajax_get_stock_name.php?code=" + str, true);
            xmlhttp.onreadystatechange = function() {
                if ((xmlhttp.readyState == 4 && xmlhttp.status == 200)) {
                    var rstr = xmlhttp.responseText;
                    rstr = rstr.replace(/\s+/g, ' ').trim();
                    /**document.getElementById("cname").innerHTML = rstr ;**/
                    document.getElementById("fname").value = rstr ;
                }
            }
          xmlhttp.send();
        }
    }
</script>

PHP代碼:

 <?php // Create connection //$message = "In funtion codelookup"; //echo "<script type='text/javascript'>alert('$message');</script>"; include 'mysqlinit.php'; // Check connection // get the q parameter from URL $code1 = ""; $name1 = "NOTFOUND"; if (isset($_GET['code'])) { $code1 = $_GET['code']; $sql = "SELECT * FROM `pcomp` where Code = '$code1'"; //$sql1 = 'SELECT * FROM `pcomp` WHERE `Code` = "H413"'; //echo "SQL = $sql"; //echo "code = $code1"; $result = mysqli_query($conn, $sql); //echo "result = $result1"; if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { $name1 = $row["Name"]; $name1 = trim ( $name1, [ string $character_mask = " \\t\\n\\r\\0\\x0B" ] ) } } else { $name1 = "NOTFOUND"; } mysqli_close($conn); if (empty($name1)){ $name1 = "NOTFOUND"; } } else { $name1 = "NOTFOUND"; } echo $name1; ?> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM