I'm running a $wpdb select query and getting it’s parameter from a textbox. Result shows as soon as I press the search button, but I want to do the same with Ajax without refreshing the page. I have tried everything but the page is still refreshed.

jQuery code:

jQuery(document).ready(function() {      
        jQuery.post(yes.ajaxurl,{action : 'doit'},
            function( response) {//start of funciton
                // alert(response);
                return false;
            } //end of function
    }); // click button function finishing here
}); //end of main loop 


<form action="" method="post">
    <div><input maxlength="200" name="secretcode" size="200" type="text" value="" placeholder="Type Here !" />
    <input id="Submityourskill" name="Submit" type="submit" value="Search Record" /></div>
<div id="result"></div>


function doit() {
    if(isset($_POST['secretcode'])!= ''){
        if($_POST['Submit']) {
            global $wpdb;
            $sql = "SELECT * FROM wp_store_locator WHERE sl_description='$secretcode'";
            $results = $wpdb->get_results($sql) or die(mysql_error());
            foreach( $results as $result ) {
                echo $result->sl_description;
add_action( 'wp_ajax_nopriv_doit', 'doit');
add_action( 'wp_ajax_doit', 'doit' );

function add_myjavascript(){  
    wp_register_script( 'globals', get_stylesheet_directory_uri() . "/js/ajax-implementationn.js", array( 'jquery' ) ); 
    wp_enqueue_script( 'globals' );
    // use wp_localize_script to pass PHP variables into javascript
    wp_localize_script( 'globals', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action( 'init', 'add_myjavascript' );

1 Answer 1


This is a javascript issue. You have to prevent form submission to stop the page from reloading. See event.preventDefault() in jQuery docs.

    // the rest of your code
  • Yes Mile thanks ... you are right we can prevent the page from reloading with the code you mentioned but as soon as I do this I start getting zero instead the result. I get 0 in result when implement your solution. What could be wrong.
    – Zeeshan
    Feb 21, 2015 at 18:17
  • Hi Mile I changed my code as per your advice like this
    – Zeeshan
    Feb 21, 2015 at 18:25
  • I am still getting zero in result
    – Zeeshan
    Feb 21, 2015 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.