How to get input from form using PHP/Jquery live?

Tags: , , , ,



I have a simple HTML form that includes an input field and a submit button.

How can I use JQuery to get the text from the input field live and then send that data to a PHP file that evaluates the data?

Form:

<form action='file_that_will_process_data.php' method='POST'>
<input id='text' type='text' name='txt'>
<button type='submit'>Submit</button>
</form>

Edit: here’s what I want it to look like

    echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>';
    echo "<script>$(function() {
        $('button').on('click', function() {
          var txt = $('#txt').val();
        sendTextTo_file_that_will_process_data_AndReturnTheValueThat_file_that_will_process_dataReturns(txt)
      })</script>";

Answer

Your current code doesn’t need jquery to get the text from the input field in PHP.
When the user clicks on the Submit button, you can retrieve the text from the input with this code that you’ve to put in the file_that_will_process_data.php file

<?php 
if (isset($_POST['txt'])) {
    var_dump($_POST['txt']); // $_POST['txt'] contains the text from the input field
    // TODO: make your treatment here...
}

But if what you’re looking for is to allow users to make something like a live search, you don’t need the submit anymore. Then you can do something like this using jquery:

$(function() {
  $('input[name="txt"').on('keyup', function() {
    const $form = $(this).closest('form');
    $.ajax({
      type: "POST",
      url: $form.attr('action'),
      data: {
        txt: $(this).val()
      },
      success: function (data) {
        // data contains the result of your treatment in the file_that_will_process_data.php file. Do whatever you want with it here
      }
    })
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action='file_that_will_process_data.php' method='POST'>
    <input type='text' name='txt'>
    <button type='submit'>Submit</button>
</form>


Source: stackoverflow