Ajax call to my WordPress website from an external application [duplicate]

You shouldn’t be sending your data as JSON:

dataType: "JSON"

For add_action("wp_ajax_nopriv_itempricingfunction" to work, WordPress needs to find the action parameter in your request, which you’re correctly setting here:

    data: {
        action : "itempricingfunction",
        ean : "EANTEST0101010"
    },

The problem is that it checks this using $_REQUEST['action'], but PHP doesn’t populate $_REQUEST with JSON. It only works with form data. So remove the dataType line and you should be fine:

jQuery.ajax(
    {
        type: 'POST',
        url: 'https://www.groupio.fr/wp-admin/admin-ajax.php',
        responseType: 'json',
        data: {
            action: 'itempricingfunction',
            ean: 'EANTEST0101010'
        },
        success: function( data ) {
            alert( data );
        },
        error: function( errorThrown ) {
            console.log( errorThrown );
        }
    }
);

There’s a couple of other things to consider too:

  • If the web app is on a different domain, you may run into CORS issues.
  • A custom REST API endpoint would be more appropriate for this sort of thing, and does support receiving data as JSON.

Leave a Comment