Zeeshan
Zeeshan

Reputation: 321

wordpress search query with ajax

I am running a wpdb select query in wordpress 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.

Below is my code

//Jquery code

jQuery(document).ready(function() {  

   jQuery("#Submityourskill").click(function(){


   jQuery.post(yes.ajaxurl,{action : 'doit'},

    function( response) {//start of funciton


      // alert(response);
       //jQuery("#searchtextbox").val(response);
       jQuery("#result").append(response);
       jQuery("#textarea").html(response);
       return false;
    });//end of function


   }); // click button function finishing here


}); //end of main loop 

html

<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>
</form>
<div id="result"></div>

//php function

function doit() {
if(isset($_POST['secretcode'])!= ''){
if($_POST['Submit']) {

$secretcode=$_POST['secretcode'];
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;

    }
 exit();
}
  }

And below is other php code I have used with it

php code

add_action( 'wp_ajax_nopriv_doit', 'doit');
add_action( 'wp_ajax_doit', 'doit' );

Below is the code to enqueue the jquery page

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' )

Thanks everybody and regards ... !

Upvotes: 0

Views: 1097

Answers (1)

George
George

Reputation: 36794

Listen to the form's submit event, to make things easier on yourself. There are other ways of submitting a form than clicking the submit button.

What you are looking for is to prevent the default action with event.preventDefault():

jQuery(document).ready(function() {  

    jQuery("#myform").submit(function(e){
        e.preventDefault();
        jQuery.post(yes.ajaxurl,{action : 'doit'}, function( response) {
            // alert(response);
            //jQuery("#searchtextbox").val(response);
            jQuery("#result").append(response);
            jQuery("#textarea").html(response);
            return false;
        });//end of function
    }); // submit form function finishing here
}); //end of main loop

And give an id to your form so you can target it:

<form id="myform" action="" method="post">

Upvotes: 1

Related Questions