This is possible duplicate question but I couldn't make it work with this link "POST from jQuery to PHP" So please help me to achieve this. I am trying to pass jquery variables to php function and run it. I have freshdeskreply.js file and I have my php function in send_reply.php in theme folder.
On js file I am trying to pass this.name (which is ticket id) and textreply (which is textarea value) to my php function and run it. I've been trying to do this for a week already but couldn't make it work, please show it to me step by step. Thank you.
I am also able to alert the js values but can not post them to php function. js file is already registered and works on page load.
functions.php
/*Reply JS*/
add_action( 'wp_enqueue_scripts', 'my_scripts' );
function my_scripts() {
wp_enqueue_script( 'my_js_library', get_stylesheet_directory_uri() . '/freshdeskreply.js' );
wp_localize_script( 'my_js_library', 'my_local_var', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
/*END - Reply JS*/
freshdeskreply.js
jQuery(document).ready(function($) {
/*Ticket Reply button*/
$('[id^="send_reply"]').click(function() {
var textreply = $('textarea#replyarea' + this.name).val();
if(!textreply.trim()){
alert("Reply area can not be empty...");
}
else{
$.ajax({
url: my_local_var.ajax_url,
type: 'POST',
data:{
action: 'myaction',
textreply: textreply,
ticketid: this.name
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
alert(textreply);
alert(this.name);
location.reload();
}
});
});
send_reply.php
add_action( 'wp_ajax_myaction', 'post_note' );
add_action( 'wp_ajax_nopriv_myaction', 'post_note' );
/*Reply*/
function post_note() {
$api_key = "XXXXXXXXXXXXXXX";
$password = "x";
$yourdomain = "XXX";
$ticketid = $_POST['ticketid'];
$reply_body = $_POST['textreply'];
$notprivate = "false";
$note_payload = array(
'body' => $reply_body,
'private' => $notprivate,
'user_id' => $contact_id,
);
$url = "https://$yourdomain.freshdesk.com/api/v2/tickets/$ticketid/notes";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$api_key:$password");
curl_setopt($ch, CURLOPT_POSTFIELDS, $note_payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
$info = curl_getinfo($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($server_output, 0, $header_size);
$response = substr($server_output, $header_size);
if($info['http_code'] == 201) {
}
curl_close($ch);
}
/*End Reply*/