I spent a lot of time searching for a solution where I can pass the value of the JavaScript variable into PHP variable in the same file, same function (WordPress Widget, Form function). Is there a good way, as of 2017, to do so?
I have tried this method below. Although the Ajax part bring out the successful message, the php part failed.
repeat.php
<?php
echo $_POST['examplePHP']; //will cause undefined index here
?>
<script>
jQuery(document).ready(function($){
var exampleJS = "hi!";
$.ajax({
url: ajaxurl, //I have tried 'repeat.php' instead of ajaxurl, but not working.
type: 'POST',
data: {
examplePHP: exampleJS
},
success: function( response){
console.log("Successful!");
},
error: function(error){
console.log("error");
}
});
});
</script>