Home > Software design >  PHP one line get input value and use in PHP ajax function
PHP one line get input value and use in PHP ajax function

Time:11-11

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,

CodePudding user response:

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>
  • Related