Reputation: 155
I have some button and on click JS for it:
<button id="trigger">Send</button>
and JS to invoke simple action
$('#trigger').on("click", function(event){
jQuery.ajax({
type: "POST",
url: 'functions.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
alert('test success');
},
complete: function (obj, textstatus) {
alert('test complete');
}
});
});
In above ajax I put functions.php with other simple function:
<?php
$message = "PHP Funtion Alert";
echo "<script type='text/javascript'>alert('$message');</script>";
?>
But, I got only alert invoked from alert('test complete'); How invoke alert from PHP file?
PS. this is only example. In PHP file will be some DB functions.
Upvotes: 0
Views: 100
Reputation: 318182
You're expecting JSON, hence the
dataType: 'json',
Yet, you're returning a script tag?
echo "<script type='text/javascript'>alert('$message');</script>";
And that's an error. What you want is to return valid JSON
$message = array("message" => "PHP Funtion Alert");
echo json_encode($message);
Then catch in the ajax function
jQuery.ajax({
type : "POST",
url : 'functions.php',
dataType : 'json',
data : {
data : 'to be sent'
}
}).done(function(data) {
console.log(data.message);
}).fail(function() {
console.log(arguments);
});
Upvotes: 1