I have a little problem with calling a file in a WordPress plugin using ajax.I have this script:
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
alert('Setting the value to "' + val + '"')
jQuery.post('session.php', {value: val})
alert('Finished setting the value')
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
But when this function gets called, it shows an error in the console file not found. I want to know if this is the correct way to use ajax in WordPress. If not, how can I call a file which is in the root folder of site name session.php? I’m pretty new to WordPress.
I have solve my problem on my own.First i have define ajaxurl in my themes
function.php
like below:And I put the below script on the top of my plugin file.
and here’s the field, for which i am trying to do in my plugin.
and then I put my action which i m calling to my script in
function.php
.and then call my session value in to my function.That’s all i do and work for me and i hope this will helps someone else.
Note:
The
wp_ajax_your_action
action is for admin if you need to use it on the front end the action would bewp_ajax_nopriv_your_action
.In WordPress, Ajax requests should be made to
http://your-wordpress-site/wp-admin/admin-ajax.php
– which can be obtained usingadmin_url( 'admin-ajax.php' )
– and you should useaction
parameter to specify which function to call. You can pass theadmin-ajax
path to your javascript file via localization.Add to your plugin PHP file after you enqueue your script:
In your javascript:
Function to process the ajax in your plugin PHP file:
Read more: https://codex.wordpress.org/AJAX_in_Plugins
WordPress works on absolute paths, use a complete URL instead of the relative URL:
Use something like: