0

I'm struggling with calling a JS function firstLetterSearch() using PHP, and passing a variable $_POST['word'] to it. I can send an int as an argument but if I send this variable then it just shows up as {} when I log the value to the console.

function firstLetterSearch(firstLetter){
    console.log('First letter search function called');
    let abc = JSON.stringify(firstLetter);
    console.log(abc);
    if(firstLetter === 1){
        console.log('I will select word starting with A');
    } else if(firstLetter === 2){
        console.log('I will select word starting with B');
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Random Word Generator</title>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript"></script>
    <script language="javascript" src="update.js" type="text/javascript"></script>
    <script language="javascript" src="words.js" type="text/javascript"></script>
</head>
<body onload="updateChat();">

<p id=shownword></p>

    <form action="" method="post">
    <input type="submit" name="word"
                class="button" value="a" id="a"/> 
          
        <input type="submit" name="word"
                class="button" value="b" id="b"/> 
    </form>
    
    <?php
    //This function gets called when button is pushed
    function postword(){
        $fp = fopen('word.txt', 'w');
        fwrite($fp, $_POST['word']);
        fclose($fp);
        

        echo '<script type="text/javascript">',
        'firstLetterSearch(';
        echo $_POST['word'];
        echo ');',
        '</script>';
        
    }
    //When the button is pushed, the function will be called
    if (isset($_POST['word'])) {
        postword();
        //return;
    }
    ?>

</body>
</html>

1
  • 1
    What does I can send an int as an argument mean? Commented Jan 10, 2020 at 12:00

1 Answer 1

2

Your code nearly works.

The part that says

echo '<script type="text/javascript">',
        'firstLetterSearch(';
        echo $_POST['word'];
        echo ');',
        '</script>';

actually outputs firstLetterSearch(a); when you really want firstLetterSearch("a");

So just change it to this:

echo '<script type="text/javascript">',
        'firstLetterSearch("';
        echo $_POST['word'];
        echo '");',
        '</script>';
Sign up to request clarification or add additional context in comments.

Comments

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.