6

I have a very simple plugin with a javascript file and a PHP file. I want to call the PHP file from my javascript code and get the output. The javascript functions is something like the following:

function img_upload(){

        var ajax = new XMLHttpRequest();           
        ajax.open('GET', 'http://My_Domain_Name.com/wp-content/plugins/My_Plugin/auth.php', false);
        ajax.send();

    if (ajax.status === 200) {

      console.log(ajax.responseText);

    }

and the PHP file which returns the results:

<?php
$token=Get_Token();
echo $token;
function Get_Token()
{
   //Do some stuff
   return $token;
}
?>

both files (auth.php and myjs.js) are in the root directory of the plugin.

/home/My_Username/public_html/wp-content/plugins/My_Plugin

If I use the domain name I can call the php file in ajax.open() and get the results, but I know this is not the right way to do that. How can I call the php file inside my javascrip code via ajax.open('path_to_php') in Wordpress properly without indicating the domain name?

0

1 Answer 1

1

Here's an example:

Use this sample JavaScript code:

jQuery(document).on('click', '.some-element', function(e){
    var ipc = jQuery(this).data('collection-id');
    jQuery('.some-other-element').show();

    jQuery.ajax({
        method: 'post',
        url: ipAjaxVar.ajaxurl,
        data: {
            collection_id: ipc,
            action: 'my_function',
        }
    }).done(function(msg) {
        // Do something when done
    });

    e.preventDefault();
});

PHP (include the function in your plugin, do not use a separate file):

// Include the JavaScript above in your plugin
wp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true);

wp_localize_script('main', 'ipAjaxVar', array(
    'ajaxurl' => admin_url('admin-ajax.php')
));

add_action('wp_ajax_my_function', 'my_function');

UPDATE:

Add the PHP code to your main plugin file. Create a JavaScript file - js/jquery.main.js - and add the code above. That should do the trick.

2
  • May you please describe your codes a little more? I am newbie to plugins world. I need just a simple code. Where should I add wp_enqueue_script, wp_localize_script? Commented Aug 1, 2018 at 15:42
  • I have updated my answer. Add the PHP code to your main plugin file. Create a JavaScript file - js/jquery.main.js - and add the code above. That should do the trick. Commented Aug 1, 2018 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.