I have a PHP file myFile.php
that echoes a random string from an array of strings into the screen. I want to run that php file and have the output pop up in a javascript alert. I took a crack at the syntax with alert($.ajax({ url: 'getRejection.php' }));
But it is not quite right , it alerts [object Object]
.
How do I do this?
According to the jquery documentation for ajax
: http://api.jquery.com/jQuery.ajax/
You want to use the success
callback to run when the ajax call succeeds.
$.ajax({
url: 'getRejection.php',
success: function(data) { alert(data) }
});
Also, a note of advice: use full paths for urls, not relative url paths. Like this url: '/getRejection.php'
not like this url: 'getRejection.php'
You may use JSON by making your php file to echo its output in JSON format as follows:
echo "{
";
echo "\"txt\":";
echo $TheRandomText;
echo "
";
echo "}";
The previous step may be easily done as Joe Frambach suggestion like the following:
echo json_encode(array('txt' => $TheRandomText));
And then using Jquery do the following:
$(document).ready(function(){
$.getJSON('getRejection.php',{
format: "json"
}).done(function(data){
alert(data.txt);
});
});
However you have to get assured from the path to getRejection.php
. In this case it is supposed to be at the same directory with your file.
Also you have to be sured that getRejection.php
does not echo anything else text in JSON format to void the corruption of JSON query.