PHP Question

How to create a button in WordPress that emails the URL of the current page?

How can I make a button that, when pressed, sends an e-mail link with current page on WordPress? I know there is a plugin, but I would like to know how to do it by myself.

Something like this:

$(function(){
$('button').click(function(){
$.ajax({
data: 'action',
url: '...'
}).done(function( response ){
$('button').html('Thank you');
})
})
})


And PHP:

if( $_POST['action'] =='action'){
mail("joecool@example.com", "My Subject", "text");
}

Answer

functions.php

wp_register_script( 'myscript', path/to/script.js, array( 'jquery' ));
wp_localize_script( 'myscript', 'ajaxobj', array('ajaxurl' => admin_url().'admin-ajax.php') );
wp_enqueue_script( 'myscript');

script.js

$(function(){
     $('button').click(function(){

     var admin_url = ajaxobj.ajaxurl;

     $.ajax({
         type:'POST',
         data: {action: 'mail_func', name: 'danish'},
         url: admin_url
     }).done(function( response ){
         $('button').html('Thank you');
     })
 })
})

And PHP (functions.php)

 add_action( 'wp_ajax_mail_func', 'mail_func_callback' );
 add_action( 'wp_ajax_nopriv_mail_func', 'mail_func_callback' );

 function mail_func_callback(){
     $Name= $_POST['name']; //danish
     wp_mail( $to, $subject, $message, $headers, $attachments );
     die();
 }