0

Right now I have code that looks like this:

function search_ajax_fetch() {
?>
<script type="text/javascript">
  function searchFetch() {
    var keyword = $('#keyword').val();
    if ( keyword ) {
    $('#datafetch').show();
    $.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: {
          action: 'data_fetch',
          keyword: keyword
        },
        success: function(data) {
            $('#datafetch').html( data );
        }
    });
    } else {
      $('#datafetch').html( '' );
      $('#datafetch').hide();
    }
  }
</script>
<?php
}
add_action( 'wp_footer', 'search_ajax_fetch' );

But I am trying to move all the jQuery to an external file, and call this function instead. But I cannot make it work by moving it to an external file and doing it like this:

function search_ajax_fetch() {
?>
<script type="text/javascript">
  searchFetch();
</script>
<?php
}
add_action( 'wp_footer', 'search_ajax_fetch' );

Why isn't this working? The js file is loaded correctly!

  • 2
    You can't use PHP in a JS file like this: <?php echo admin_url('admin-ajax.php'); ?>. You need to use wp_localize_script() to make that value available in JS. See the documentation. – Jacob Peattie Nov 5 '18 at 10:48
  • Wow, I don't know how I forgot that part! That solved the problem. – joq3 Nov 5 '18 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.