How to send a php variable from a js file to a php file using ajax?

I new with ajax and php. I have a file named as main.phpwhich contains a text box ,when the user scan a number using a scanner or just type the number with pressing the enter key ,then that number will stored by a jquery function which is located in test.js file.I would like to send that number in to a php file named fetch.phpfor processing.But it's not working as well as which is not showing any error messages.I added my snippet below.any useful help will get appreciated!!!

//==================test.js file=============================//

$('#custom-barcode').on({
    keypress: function() { typed_into = true; },
    change: function() {
        if (typed_into) {
            var php_val = $('#custom-barcode').val();
            alert('your-barcode-is' + php_val);
            $.ajax({
                method:"post",
                url:"fetch.php",
                data:{barcode:php_val}
            })
            clear();
            typed_into = false; //reset type listener
        } else {
            alert('not type');
            clear();
        }
    }
});

function clear(){
    $('#custom-barcode').val('');
}
<input id="custom-barcode" type="number" name="custom-barcode" autofocus/>

PHP File :- fetch.php

 <?php
     if (isset($_POST['barcode'])) {
     $bcode = $_POST['barcode'];
     echo $bcode;
     }
     else{
         echo "not set";
     }    ?>

1 answer

  • answered 2018-09-21 19:15 user9741470

    Try rewrite this part of the code in this way. According to the Jquerydocumentation, the .on() event expect as the first parameter an event handler, and as second, a callback function that will manage the related logics.

    From the doc:

    The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.

    $('#custom-barcode').on('keypress change', function(e){
      e.preventDefault();
    var php_val = $('#custom-barcode').val();
      if(php_val != ''){  
          alert('your-barcode-is' + php_val);
            $.ajax({
                method:"post",
                url:"fetch.php",
                data:{barcode:php_val},
                cache: false,
                success: function(response){
                   clear();
                }
            });     
       }
       else {
         alert('not type');
         clear();
       }
    });
    
    function clear(){
        $('#custom-barcode').val('');
    }