Reputation: 489
I am trying to load the output of a PHP script into a using JavaScript and JQuery. The JavaScript function I am using uses the $.get function in JQuery to call a php script, which I want to display in another division. The script I wrote is:
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
});
});
}
</script>
The PHP script (dbtest.php) uses a simple echo statement:
echo "hello, world!!!";
I am getting the first alert here, but not the second. What Can I be doing wrong here?
Upvotes: 0
Views: 2496
Reputation: 2188
Try add some error handling to your code to better see what´s happening.
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
}).fail(function () {
alert("failed");
});
});
}
</script>
Upvotes: 0
Reputation: 2188
Here you have a working example:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div id="uname"></div>
<script>
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("#uname").html(data);
});
});
}
on_load();
</script>
Beware of the same-origin-policy. The page loading dbtest.php must be from the same origin, unless you grant other origins by adding a header from dbtest.php.
Upvotes: 0
Reputation: 28845
I suppose uname
is a ID, in that case you should use:
$("#uname").html(data);
You can add this to your php for debugging:
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
Try also to remove http://
from your ajax call and use relative path instead.
Upvotes: 2
Reputation: 8565
You say you are trying to make ajax requests to your localhost from a Phonegap application. Phonegap prevents making ajax requests to other domains by default. You must add localhost
to whitelist. Here is more detail: http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html
Upvotes: 0
Reputation: 3286
I think the problem is the path to your dbtest.php
file. You are saying you seecond alert
will not be displayed so your request must be wrong.
Try to copy your page into the same folder like dbtest.php
open the page in your browser with http://localhost/yourfile.php
If this does not display both alert
-boxes try the same with an open developer console (Chrome/IE = F12) and look if there are errors.
Upvotes: 0
Reputation: 13549
The guys below pointed out that the selector is wrong. Indeed that's a problem, but I think that the real issue is that you don't get the second alert. Probably your php file localhost/dbtest.php is not accessible. What happen if you open localhost/dbtest.php in a new tab?
Upvotes: 0