Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery POST fetching data on keyup

Tags:

jquery

ajax

php

What I want to do

When writing in the text field, I want the <div class="result"> to be filled with what PHP is echoing.

But it doesn't work!

Jquery

$(document).ready(function() {
    var search = $("#search");
    if (search.val() !== '') {
        search.keyup(function() {
            $.post("index.php", { search : search.val()}, function(data) {
                $(".result").html(data);
            });
        });
    }
});

php

    if (isset($_POST['search'])) {
        echo 'hello';
    }

html

<input type="text" name="search" id="search"/>
<br />
<div class="result"></div>

Problem

When filling the input, nothing happens, and it meant to POST the entered data on keyup (When entering a new character/or deleting.

What is stopping it from working? I am new to jQuery .

Thanks.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
like image 519
Jony Kale Avatar asked Mar 24 '23 08:03

Jony Kale


1 Answers

This is wrong.

if (search.val() !== '') {

The above line should be,

if (search.val() != '') {

EDIT:

Then wrap the if condition inside the keyup function.

$(document).ready(function() {
    var search = $("#search");

        search.keyup(function() {
            if (search.val() != '') {
                $.post("getInputs.php", { search : search.val()}, function(data) {
                    $(".result").html(data);
                });
            }
        });
});
like image 58
Edwin Alex Avatar answered Apr 02 '23 16:04

Edwin Alex