Ajax Not Executed

I am beginner to ajax world and trying to call contents from php page using $.ajax() function and the code couldn't executed. the html page i used:

<!DOCTYPE html>
<html>
<head>
    <title>AJAX</title>    
</head>
<body>

<div >    
    <input type="text" name="search" id="search">       
    <br>
    <br>
    <h2 id="result"></h2>
</div>    
<script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>
<script src="js/script.js"></script>
</body>
</html>

the JQuery code i used in the script.js:

$(document).ready(function() {

    $('#search').keyup(function () {
        var search = $('#search').val();

        $.ajax({

            url:'search.php',
            //the page to which the request will go to

            data:{search: search},

            type: 'POST',
            success:function(data) {
                if(!data.error){
                    $('#result').html(data);//the h2 we want to echo it uing the ajax
                }
            }

        });

    });

});

the search.php page contain:

$search = $_POST['search'];
echo $search;

the code not executed. What should I do.

Upvotes: -1

Views: 618

Answers (2)

Haresh Vidja
Haresh Vidja

Reputation: 8496

I see some issue in your response from PHP code and in ajax side success code.

You are not sending in response JSON format so data.error is meaningless. so in your success callback code should be like this.

success:function(data) {
    $('#result').html(data);//the h2 we want to echo it uing the ajax
}

Upvotes: 1

Mandeep Gill
Mandeep Gill

Reputation: 4907

Follow jQuery Ajax Document :

An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0

type: 'POST'

But you are using 2.0 so i think this will work :

method: 'POST'

jQuery Documents

Upvotes: 0

Related Questions