John Davidson

javascript - Ajax Search Form with multiple Inputs In Wordpress with PHP and JQuery | Data Fetch

0 comments
Message:


My code is working like charm but i need to add 2 dropdown into it:


this is where i input the value:


<form>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search..">
</form>

and i want it to look like this:


 <form>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search..">
<select>
<option>location category</option>
<option>option2</option>
</select>
<select>
<option>category</option>
<option>option2</option>
</select>
</form>

i put this code in functions.php its working fine



<script type="text/javascript">

function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data:{ action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});

}
</script>

<?php
}

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

$the_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => 'locations'
)
);

if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();

$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>

<div class="city-results">
<a href="<?php the_permalink();?>">
<h3>
<?php the_title();?>
</h3>
</a>

</div>

<?php }
endwhile;
wp_reset_postdata();
endif;

die();
}
?>

i guess we need to edit this area where fetching data


data:{ action: 'data_fetch', keyword: jQuery('#keyword').val() },

i tried using this Method but is not working :


data:{ action: 'data_fetch', keyword: jQuery('#keyword , #keyword2').val() },

but i'm noob in Jquery/Ajax


if anyone help me here with this Thanks in advance



My Answer:





Rate this post

5 of 5 based on 2567 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us