Hello
I want to send an email from a view wich list my quotation cpt, i will include a link in the body message of this kind
[wpv-post-url]?pdf=[wpv-post-id]
I'm completely newbie to ajax and went to send "Post_ID" and "Post_URL"
I have add a button :
<input type='button' id="sendmailbtn" value='Send email'>
and some js to the view :
$j("#sendmailbtn").click(function(e) {
var id_post = $j(this).attr('id');
e.preventDefault();
$j.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
datatype: "html",
data: {'action': 'fahadsending_mail', 'post_id': id_post},
success: function(response) {
alert("success is " + response);
},error:function(response){
alert("error is " + response);
}
});
});
and in my functions.php the code below
add_action('wp_ajax_nopriv_fahadsending_mail', 'fahadsending_mail');
add_action('wp_ajax_fahadsending_mail', 'fahadsending_mail');
function fahadsending_mail(){
$to = "test@gmail.com";
$subject = "TEST AJAX FORM";
$post_id = $_POST['post_id'];
$message = 'message ' . $post_id;
if( wp_mail($to, $subject, $message) ){
echo "mail sent";
} else {
echo "mail not sent";
}
die(); // never forget to die() your AJAX reuqests
}
The email is sent correctly, just in my button tage "id", i have "sendmailbtn", how can I pass "Post_ID" and "Post_URL" ?
Thank you in advance
Hello,
It is a custom codes problem, I suggest you setup the codes by following the WordPress document:
https://codex.wordpress.org/AJAX_in_Plugins
I have tried it in my localhost, by below steps, it works fine:
1) Create a content template, setup the button:
<input type='button' id="sendmailbtn" value='Send email' post_id=[wpv-post-id]>
It will setup attribute post_id as current post ID
2) Add JS codes to above content template:
jQuery(document).ready(function($) {
$("#sendmailbtn").click(function(e) {
var ajaxurl = '/wp-admin/admin-ajax.php';
var data = {
'action': 'fahadsending_mail',
'post_id': $(this).attr('post_id')
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
3) Use same PHP codes as you mentioned above, in your PHP codes, you can get the post ID with:
$post_id = $_POST['post_id'];
With post ID, you can get it's post URL, like this:
$post_url = get_permalink($post_id);
More help:
https://developer.wordpress.org/reference/functions/get_permalink/