How to make ajax queries from a js file in a Wordpress widget?

0

I'm making a widget for wordpress and I need to make ajax queries to a file that is in the same folder. If I just put the name of the file look for it in the link where I put the widget, for example, if the widget I put it on the page

www.midominio.com/buscador/ 

and the file I request is called test.php so what this request does is:

www.midominio.com/buscador/prueba.php

and I need you to look in the same folder (relative path) because I think it should be slower with an external query of type www.

I solved it provisionally with:

plugin_dir_url( __FILE__ )

but the reference I want to make from a file js and also I think it is not the most optimal. I hope you can help me and thanks in advance.

    
asked by Patricio 23.08.2018 в 20:09
source

1 answer

1

The CORRECT way to handle ajax calls in Wordpress is this

Main php file of your plugin

<?php //Define los archivos js que se van a encolar. En este caso el archivo que contiene el codigo js para el ajax.
function miplugin_encolar_scripts()
{
    wp_enqueue_script('miplugin-', plugin_dir_url(__FILE__) . 'main.js', array('jquery'), '1.0.0', false);
}

//Ejecuta la funcioon miplugin_encolar_scripts()
add_action('wp_enqueue_scripts', 'miplugin_encolar_scripts');

//Estas funciones (HO0Ks) hacen que la funcion prueba_funcion() este disponible cuando se hagan llamas al /admin-ajax.php
add_action( 'wp_ajax_nopriv_prueba_funcion', 'prueba_funcion' );
add_action( 'wp_ajax_prueba_funcion', 'prueba_funcion' );

function prueba_funcion() {
    //Incluimos el archivo prueba.php que contiene los codigos a ejecutarse durante la peticion
    require_once plugin_dir_path( __FILE__ ) . 'prueba.php';
    exit();
}


function miplugin_ajax_enqueue() {
    //Con esta funcion se crea la variable ajaxurl de javascript que es la que usaremos como url para las peticiones del ajax.
    wp_localize_script(
        'miplugin-ajax-script',
        'miplugin',
        array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
    );
}

//Con este codigo se ejecuta la funcion miplugin_ajax_enqueue() en el momento correcto
add_action( 'wp_enqueue_scripts', 'miplugin_ajax_enqueue' );

In the file where you have the code that makes the call ajax (which in my example is called main.js) used as the address for the request miplugin.ajaxurl and between the data sent adds a field called action and as value , the name of the function that must be executed (in our case prueba_funcion ).

Example:

jQuery(document).ready(function($) {
    // This does the ajax request
    $.ajax({
        url: miplugin.ajaxurl,
        data: {
            'action': 'prueba_funcion',
            'unadata' : 123456
        },
        success:function(data) {
            // This outputs the result of the ajax request
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });  

});
    
answered by 23.08.2018 в 20:28