0

About the example from W3SCHOOL AJAX Database (my environment CentOS 7, PHP 7.4) - the one is simple but based on dropdown select onchange

<select name="customers" onchange="showCustomer(this.value)">

I'm trying to do the same but get value from an input field - but something is wrong with syntax or logic. I've tried HTML

<div style="float: left; text-align: center;"><input type="text" placeholder="Type something..." name="myInput" id="myInput"><button type="submit" onclick="showCustomer(<?php echo $_GET['myInput'] ?>)">Test from myInput HTML</button></div><div id="txtCustomer"> </div>

PHP

echo "<div style=\"float: left; text-align: center;\"><input type=\"text\" placeholder=\"Type something...\" name=\"myInput\" id=\"myInput\"><button type=\"submit\" onclick=\"showCustomer(".$_GET['myInput'].")\">Test from myInput PHP</button></div><div id=\"txtCustomer\" style=\"text-align: left; font-size: 14pt;\"> </div>";

but no success. If I use STATIC predefined value inside showCustomer function like

showCustomer('active')

everything works, but no one of above variations

onclick=\"showCustomer(".$_GET['myInput'].")\">

or

onclick="showCustomer(<?php echo $_GET['myInput'] ?>)">

Thx for any ideas or hints to try,

3
  • You can't use <?php echo there, since that runs when the page is being created, not while the user is editing the form. Commented Nov 10, 2022 at 20:45
  • Use document.getElementById('myInput').value Commented Nov 10, 2022 at 20:45
  • I would advise you to use different quotation marks inside echo statements. You can use' for beginning and ending echo and " inside of it Commented Nov 10, 2022 at 20:59

1 Answer 1

2

You have to use JavaScript in the argument, not PHP, since PHP doesn't run until after the form is submitted. Your code will use the value of $_GET['myInput'] that existed when the page was being created, not whatthe user entered now.

<button type="submit" onclick="showCustomer(document.getElementById('myInput').value)">Test from myInput HTML</button>
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, already tested and works ! Thx ! Very clear and useful solution.

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.