lbj-ub
lbj-ub

Reputation: 1423

Simple jQuery-Ajax-PHP example

I've been looking at a few introductory examples of how to use ajax with jQuery but when I try those examples on my server, they don't seem to work.

Here is the code I have in the html file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
    $(function(){
    $.get("ajax/json-statistics.php", function(data){
        alert("hello");});
});
    
</script>
</head>
<body>
</body>
</html>

Here's the code I have in the PHP file:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

Both files are located in the same directory. When I go to the html page, it's just blank but I'm expecting an alert box to appear containing the text hello.

Upvotes: -1

Views: 2529

Answers (3)

Pedro Lobito
Pedro Lobito

Reputation: 99081

Try:

<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

Upvotes: 0

Tadeck
Tadeck

Reputation: 137460

Check the paths - they are relative and thus the files they point browser to should be in correct location (maybe they already are - we do not have enough data).

If it still does not work, there may be other issues. Eg. maybe you have the JavaScript turned off?

The best way to check whether requests have been sent and whether there were any other problems is to use some debugging tools. I suggest Chrome's Developer Tools of Firefox's Firebug - check with them, whether the requests for files and for data are sent to correct locations and check whether there are any additional JavaScript errors.

Upvotes: 1

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

I found this working in my end

<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script LANGUAGE="JavaScript">
$(document).ready(function(){
$.get("ajax/json-statistics.php", function(data){
    alert("hello");}, "json");
});
</script>

Upvotes: 1

Related Questions