Reputation: 79
I am trying to show an alert as a test but i can't make it work. On the HTML page i have:
<body onload="DBReadNews()">
...code
<script src="jquery.js"></script>
<script src="myJs.js"></script>
Javascript:
function DBReadNews(){
$.ajax({
type: "POST",
url: "newsPhpRead.php",
datatype: "text",
success: function() {
}
});
}
PHP:
<?php
echo "<script language='javascript'>alert('test!');</script>";
?>
Upvotes: 0
Views: 88
Reputation: 12058
The provided answers work only if you return a pure content from the AJAX call. With my solution you can execute any JavaScript code returned in the response.
The problem is that the response from the server is not used. Instead it should be injected it in the DOM like this:
file: index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="DBReadNews()">
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="myjs.js"></script>
</body>
file: myjs.js
function DBReadNews(){
$.ajax({
type: "POST",
url: "newsphpread.php",
datatype: "text",
success: function(response) {
$('body').prepend(response);
}
});
}
file: newsphpread.php
<?php echo "<script>alert('test!');</script>"; ?>
When index.html is opened in the browser, an AJAX request is sent to newsphpread.php. The response of this request is injected in the and the alert() (or other javascript code) is executed.
Note: This should be run on a web server to work i.e. the index file should be accessed via http http://localhost/index.html and not as a file file:///var/www/alert.html. If index.html is opened with file:// you will get an error in the console "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https."
Upvotes: 0
Reputation: 66
It's because you don't deal with the response from the server. Try it this way:
function DBReadNews(){
$.ajax({
type: "POST",
url: "newsPhpRead.php",
datatype: "text",
success: function(server_response){
alert(server_response);
}
});
}
and change your php script to:
<?php
echo "test";
?>
Upvotes: 2
Reputation: 1832
You can't echo an alert like that. You will have to put it inside your success handler like this.
function DBReadNews(){
$.ajax({
type: "POST",
url: "newsPhpRead.php",
datatype: "text",
success: function() {
alert('Test!');
}
});
}
Upvotes: 0