#!/usr/bin/perl ############### ## Libraries ## ############### use strict; use warnings; use JSON; ################## ## User-defined ## ################## # This is a link to Google's publicly-available jQuery library my $jquery = "ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"; ################## ## Main Program ## ################## my $this_prog = $ENV{'REQUEST_URI'}; my $h_param = cgi_params(); if (exists $h_param->{'ajax'}) { # If 'ajax' was sent in the URL, it's the client communicating # with the Server via Ajax. See function ajax_query_server(), # which initiates this. You could also put '?ajax' in the URL # query to see the data results directly. ## server_side_ajax(); } else { # If the URL doesn't contain the key 'ajax', we display the HTML # page normally. ## print "Content-type: text/html\n\n"; print_javascript(); print_html_page(); } ################# ## Subroutines ## ################# sub cgi_params { my $query = $ENV{'QUERY_STRING'} || 0; $query or return { }; my $h_params = { }; foreach my $key (split('&', $query)) { my $val = ($key =~ s/=(.*)$//)? $1: undef; $h_params->{$key} = $val; } return $h_params; } sub server_side_ajax { # Calculate data somehow my $a_data = [ ]; my $npoints = 16; # For the sake of example, just randomize it for now for (my $i = 0; $i < $npoints; $i++) { my ($x, $y) = (int(rand(100)), int(rand(100))); push @$a_data, [ $x, $y ]; } my $h_json = { 'data' => $a_data }; # Print the JSON header and data print "Content-type: application/json\n\n"; print to_json($h_json); exit; } sub print_javascript { # Send the jQuery/Javascript code to the browser print qq{ }; } sub print_html_page { # Here's where the HTML body gets printed print qq{

Ajax Data Example


        
    };
}