Support » Everything else WordPress » Problem in .js file on call custom ajax.php

  • I’m developping a custom plugin to wp and I upload the files to “/wp-content/plugins/myplugin/” folder and activated it on dashboard.

    I’m having problem with javascript file to refers my custom ajax.php file.

    My javascript file “ajax.js” is locatted in “/wp-content/plugins/myplugin/js/ajax.js” that starts like this:

    `$(document).ready(function(){
    var dataRecords = $(‘#recordListing’).DataTable({
    “lengthChange”: false,
    “processing”:true,
    “serverSide”:true,
    ‘processing’: true,
    ‘serverSide’: true,
    ‘serverMethod’: ‘post’,
    “order”:[],
    “ajax”:{
    url:’/wp-content/plugins/myplugin/ajax_action-myplugin.php’,
    type:”POST”,
    data:{action:’listRecords’},
    dataType:”json”…’

    Maybe the problem is at “url:” and I tried differents URL’s parameters but no one works.

    My custom ajax file “ajax_action-myplugin.php” is located in root folder “/wp-content/plugins/myplugin/”.

Viewing 1 replies (of 1 total)
  • Joy

    (@joyously)

    If you want your AJAX PHP code to use WP functions, you need to use the WP AJAX way.
    In your plugin’s main file, you should have

    add_action('wp_ajax_my_action', 'my_action_handler');
    add_action('wp_ajax_nopriv_my_action', 'my_nopriv_action_handler');

    and your action handler functions.
    https://developer.wordpress.org/reference/hooks/wp_ajax_action/

    As detailed at https://developer.wordpress.org/plugins/javascript/ajax/#url
    you also should output the location of the AJAX script from PHP, so your JS can get it. For WP way, that is admin_url( 'admin-ajax.php' ). If you aren’t using the WP way, you still want to load the script with the right URL using plugins_url( 'js/ajax.js', __FILE__ ).

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.