Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use AJAX in WP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 280
    Comment on it

    If you are looking to use AJAX in WP. Please follow the below example.

    var stateName = $('#state').val();
    $.ajax({
          type: "POST",
          url: "<!--?php echo admin_url( 'admin-ajax.php' ); ?-->",
          data: { 'action':'custom_dropdown_city','stateName' : stateName}, 
      }).done(function(results) {
      $("#city_id").html(results);
      });
    

    OPEN function.php under your theme folder

    function custom_dropdown_city_callback(){    
        global $wpdb;  
        $userid = get_current_user_id();
        $state = $_REQUEST['stateName'];
        $sql = "SELECT `wa`.`city` from wp_connections wc join wp_connections_address wa on `wc`.`id` = `wa`.`entry_id` where `wc`.`owner` ='".$userid."' and `wc`.`deleted` = '0' and `wa`.`state` like'%".$state."%'"; 
        $results = $wpdb-&gt;get_results($sql);
        $num = count($results);
        if($num &gt; 0){
          $dd = "<select name="cityName" id="cityName" class="form-control">";
            for($i=0; $i&lt;$num; $i++){
                $dd.="<option value=".$results[$i]->city.">".$results[$i]-&gt;city."</option>";
            }
        }else{
            $dd.="<option></option>";
        }
        $dd.="</select>";
        echo $dd; 
        exit;
    }
    
    add_action('wp_ajax_custom_dropdown_city','custom_dropdown_city_callback');
    add_action('wp_ajax_nopriv_custom_dropdown_city','custom_dropdown_city_callback');
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: