Home > Software design >  Search by post title wordpress without reflesh
Search by post title wordpress without reflesh

Time:05-19

I want to create wordpress search by title without refleshing page. New results have to be shown when more than 3 symbols are typed in search. I've got input with form:

<form id="searchForm">
<input id="newsSearch" name="newsSearch" type="text" name="newsSearch" placeholder="Для отображения ленты по определенной компании введите ее название или тикер в это поле">
</form>

But when I'm typing - value of input is not changing. How can I search posts after typing 3 symbols if I cannot get input.value.length? Also how can I search without refreshing a page? I know that it can be done with ajax but I got this code and it does nothig, page is still reloading after submit:

<script>
    $('#searchForm').submit(function(e) {

        e.preventDefault(); // prevent from submitting form directly

        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            method: 'post',
            data: $("#searchForm").serializeArray() // convert all form data to array (key:value)
        })
            .done(function(response){
                alert('ok'); // show the response
                $("#searchForm").reset(); // reset the form
            })
            .fail(function(error){
                alert(error); // show the error.
            });
    })

</script>

CodePudding user response:

Your input value isn't changing because you are listening for 'submit' event on form. You should create a listener on input element on 'input' event.

$('#newsSearch').on('input', function(e) {...

Inside you should create yourself a check in which the function will return and do nothing if value is shorter than 3 symbols.

  • Related