简体   繁体   中英

HTML input form - adding Javascript and PHP functions

This question will make you think :D. I have a HTML input form with as it seems too many functions. One function is there so when enter is pressed it submits data. Other function is there to check if certain keyword is entered so it can redirect people to other URL. It all works perfectly thx to people from stack overflov. Here is my code:

<script type="text/javascript"> 
<!-- 
function enter(e){ 
    if(e.keyCode == 13) 
    { 
        Login(); 
        return false; 
    } 
} 
//--> 
</script> 


    <script type="text/JavaScript"> 
     <!-- 
     function Login(){ 
     var keyword=document.getElementById("address").value; 
     var done=0; 
     keyword=keyword.toLowerCase(); 
     keyword=keyword.split(' ').join(''); 
     if (keyword=="example,example") { window.location="http://www.example.com"; done=1;} 
     if (keyword=="example1") { window.location="http://www.example1.com"; done=1;} 
     if (keyword=="example2") { window.location="http://www.example2"; done=1;} 
     if (done==0) { doSomethingElse(); } 
     } 
     //--> 
     </script>  

    <form name="enterkeyword" action="none"> 
        <input name="keyword" id="address" type="text" onkeypress="return enter(event);"/> 
        <div class="buttons"> 
        <button type="button" onclick="Login()">Submit</button> 
        </div> 
        </form> 

Here is where the problem is. I need to find a way to save every submitted query to excel or .CSV. I found a way that saves input data to .CSV file using PHP. I tested it and it works. BUT when i try to implement that with existing functions on my input form it messes up everything. Here is the code from "query saving function", this is HTML part:

<html>
<head>
    <title>My Form</title>
</head>

<body>
    <form action="save.php" method="post">
        <p>
            What is your favorite movie?<br>
            <input type="text" name="formMovie" maxlength="50" value="<?=$varMovie;?>" />
        </p>
        <p>
            What is your name?<br>
            <input type="text" name="formName" maxlength="50" value="<?=$varName;?>" />
        </p>                
        <input type="submit" name="formSubmit" value="Submit" />
    </form>
</body>
</html>

This is PHP part (save.php):

<?php
if($_POST['formSubmit'] == "Submit")
{
    $errorMessage = "";

    if(empty($_POST['formMovie']))
    {
        $errorMessage .= "<li>You forgot to enter a movie!</li>";
    }
    if(empty($_POST['formName']))
    {
        $errorMessage .= "<li>You forgot to enter a name!</li>";
    }

    $varMovie = $_POST['formMovie'];
    $varName = $_POST['formName'];

    if(empty($errorMessage)) 
    {
        $fs = fopen("mydata.csv","a");
        fwrite($fs,$varName . ", " . $varMovie . "\n");
        fclose($fs);

        exit;
    }
}
?>

    <?php
        if(!empty($errorMessage)) 
        {
            echo("<p>There was an error with your form:</p>\n");
            echo("<ul>" . $errorMessage . "</ul>\n");
        } 
    ?>

Both codes work great but i just dont know how to implement them so they can work togeather for same form... BTW this PHP function has 2 input fields, i need only 1, and i really dont need this error message if fields are left empty... I know its complicated but can someone who understands this better than me help?

Complete update

Hey again, I seperated the functionalities and made the code readable and maintainable.

Index.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles/index.css"/>
    </head>
    <body>
        <input type="text" id="txt" value="example1"/><br/>
        <input type="button" id="btn" value="doQuery()"/>

        <script src="scripts/index.js"></script>
    </body>
</html>

Index.js

function processValue() {

    var inputText = document.getElementById("txt").value.toLowerCase().split(' ').join('');

    // Export query
    exportQuery( inputText );
}

function exportQuery( query ) {

    var script = document.createElement("SCRIPT");

    script.setAttribute( 'type', 'text/javascript' );
    script.setAttribute( 'src', 'exportQuery.php?query=' + query );

    document.head.appendChild( script );
}

var urlMapper = {

    "example,example": "http://www.example.com",
    "example1": "http://www.example1.com",
    "example2": "http://www.example2.com"
}

/**
 * Should be called when the PHP has finished execution
 */
function onPhpReady( query ) {

    var url = urlMapper[ query ];

    if( url !== undefined ) {

        goToUrl( url );

    } else {

        codeAddress();
    }
}

function goToUrl( url ) {

    window.location = url;
}

function codeAddress() {

    alert( "Access Denied" );
}

( function() {

    // Selfexecuting code.

    function addButtonClickListener() {

        var btn = document.getElementById("btn");

        btn.addEventListener( "click", processValue, false );
    }

    function processKeyPress( e ) {

        if( e.keyCode == 13 ) {

            processValue();
        }
    }

    function addInputKeyPressListener() {

        var input = document.getElementById("txt");

        input.addEventListener( "keypress", processKeyPress, false );
    }

    addButtonClickListener();
    addInputKeyPressListener();

}() );

exportQuery.php

<?php
    // Get the request
    $query = $_GET['query'];

    if( !empty( $query ) ) 
    {
        writeToCSV( $query );
        notifyReady( $query );
    }

    function writeToCSV( $query ) {

        $fs = fopen( "storedQueries.csv", "a" );

        fwrite( $fs, $query . "\n" );

        fclose( $fs );
    }

    function notifyReady( $query ) {

        // print back as plain javascript
        print <<<ENDLINE
        onPhpReady( '$query' )
ENDLINE;
        // The ENDLINE ^ can't use spaces or it will give a parse error.
    }
?>

Sources: DaniWeb

Please not that I targeted Webkit, so for compatibility you'll have to change the way events are attached etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM