So I want to pass a value between javascript file and php file when I click a button. But when I click the button, I dont see the echo, does anyone see the problem? Here are 2 snippets of my code:
test.php:
<script type="text/javascript" src="/functions/js/test.js"></script>
<button type="button" class="btn btn-success" onclick=" myAjax();">Test</button>
<?php
if($_POST['action'] == 'go')
{
echo "worked";
}
?>
and test.js
function myAjax() {
$.ajax({
type: "POST",
url: 'test.php',
data:{action:'go'},
success:function() {
}
});
}
First at all you need to include jQuery library
Second, load your path to file test.js
you should use a class and no call the function myAjax().
Use a class in button such as: Test
Well, in your test.js file use this:
$(document).on('click', '.Test', function(e) {
$.ajax({
type: "POST",
url: 'test.php',
data:{action:'go'},
success:function(data) {
console.log('worked');
}
});
});
ot if just only need send one parameter, use this code, it's easier:
$(document).on('click', '.Test', function(e){
var vars = 'go';
var params='go='+vars;
location.href = 'test.php'+params;
});
then in your php file you can use $_POSt or $_REQUEST to get vars
<?php
if($_POST['action'] == 'go')
{
echo "worked";
}
?>
Have a nice day
Your problem is that you receive the response, but don't output it.
Use console.log
to output to the console:
$.ajax({
type: "POST",
url: 'test.php',
data:{action:'go'},
success: function(data) {
console.log(data);
}
});
You'll get worked inside of success function
function myAjax() {
$.ajax({
type: "POST",
url: 'test.php',
data:{action:'go'},
success:function(data) {
alert(data);//or console.log(data);
}
});
}