wordpressm
wordpressm

Reputation: 3267

ajax with Jquery can't make working in wordpress

I am writing a plugin for a wordpress, where I use jquery for AJAX.

Following code doesn't work. I expect to show the content in results div when I type in input box.

Here is the code I use for ajax request. It is located on my theme header file.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>


<script type="text/javascript" >
$(document).ready(function(){
//alert("sjsjs");

    $("#se").keypress(function(e){
       // e.preventDefault();
        var search_val=$("#se").val(); 
        $.ajax({
            type:"POST",
            url: "./wp-admin/admin-ajax.php",
            data: {
                action:'wpay_search', 
                search_string:search_val
            },
            success:function(data){
                $('#results').append(response);
            }
    });   
});
});
</script>

html content in template file

<form name="nn" action="" method="post"></br></br>
            <input id ="se" type="text" name="test" width="20" />
            <input type="submit" id="clicksubmit" value="Submit" />

        </form>
        <div id="results">val is: 


        </div>

Here is the code in plugin file

function wpay_search() {
    //global $wpdb; // this is how you get access to the database

    $whatever = $_POST['search_val'];

    $whatever += 10;

        echo $whatever;

    die(); // this is required to return a proper result
}

add_action('wp_ajax_wpay_search', 'wpay_search');
add_action('wp_ajax_nopriv_wpay_search', 'wpay_search');

I am new to wordpress plugin writing. Can anybody tell that where I have done the mistake?

Upvotes: 0

Views: 392

Answers (1)

Kylie
Kylie

Reputation: 11759

Well one thing that obviously jumps out to me is this...

        success:function(data){
            $('#results').append(response);
        }

Should be...

        success:function(data){
            $('#results').append(data);
        }

Because you have no variable called response, you passed the function data as a variable, so you have to use that.

Also, you're passing search_string as a paremeter, when infact in your php file, the $_POST is looking for search_val.

So you need to send search_val as parameter and give your JavaScript search_val variable another variable name in the JavaScript, just for less confusion. In this case I made it search.

                action:'wpay_search', 
                search_val:search

So overall it should look something like this...

$("#se").keypress(function(e){
   e.preventDefault();
    var search=$("#se").val(); 
    $.ajax({
        type:"POST",
        url: "./wp-admin/admin-ajax.php",
        data: {
            action:'wpay_search', 
            search_val:search
        },
        success:function(data){
            $('#results').append(data);
        }
    });   
  });

Upvotes: 2

Related Questions