I am trying to fetch few data from database in my .js file of wordpress theme.
I tried with .post() of jquery but nothing is happening.
Please also suggest me any alternate.
code in .js file
jq.post("../abc.php",
{
name:"kumar",
accId:window.accommodationId
}, function(data,status)
{
alert("hello");
//alert("Data: " + data + "\nStatus: " + status);
}
);
code in abc.php file
<?php
global $wpdb;
$max_minAge = $wpdb->get_results( "SELECT price_per_day FROM wp_byt_accommodation_vacancies where accommodation_id='1741'" );
echo $max_minAge[0]->price_per_day;
?>
you can use wp_ajax hooks like this in your functions.php file
// script atyle add at frontend
add_action( 'wp_enqueue_scripts','my_scripts_style');
function my_scripts_style()
{
wp_enqueue_script( 'scriptid', PATH_TO . 'script.js', array('jquery') );
// localize the script
wp_localize_script( 'scriptid', 'myAjax', array( 'url' =>admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce( "ajax_call_nonce" )));
}
Then add the ajax hook
// action for execute ajax from frontend
add_action( 'wp_ajax_nopriv_execute_ajax','execute_ajax');
function execute_ajax()
{
$nonce = check_ajax_referer( 'ajax_call_nonce', 'nonce' );
if($nonce==true)
{
// here you will perform all the db communication get data from db and send it to the view area.
echo 'test this';
die();
}
}
then in your js file which you included via enque_script
above. use this
jQuery(function(){
jQuery('.click-onthis').live('click', function(){ // get data by click
var data = {
action: 'execute_ajax',
nonce: myAjax.nonce,
// anyother code etc
};
jQuery.post( myAjax.url, data, function(response)
{
if(response=='success')
{
}
});
});
});
jquery click-on-this
will work when click on a link you can coomunicate on load or any other event
You can use the jQuery AJAX get
shorthand:
$.get( "../abc.php", function( data ) {
alert( "Data Loaded: " + data );
});
Good to know: Since you're getting data from a file, you should use a GET
.