Noben has asked for the wisdom of the Perl Monks concerning the following question:

Hello! I am very new to Perl and looking on how to use a JQuery AJAX call to execute my perl script. I would like the perl script to return a JSON object for my browser as well (in this case pulling from SQLite Database). I am receiving an error response on the AJAX catch. In response obj (responseText) I can see the text content of the perl file. So my first problem is why the perl script not executing? Every example I can find looks as similar as mine. Any pointers would be very appreciated!

function ajaxPerl() { $.ajax({ method: 'GET', url: `../cgi-bin/test-dbi.pl`, dataType: 'json', header: { "content-type": "application/json;charset=utf-8" } }).then((response) => { console.log('RESPONSE -> ', response); }).catch((error) => { console.log('ERROR -> ', error); }); }

My Perl is below - I am not sure it is returning a JSON file to the browser correctly at this point - but it does format it in the terminal with out errors.

#!/usr/bin/perl use strict; use warnings; use CGI; use DBI; use JSON; my $driver = "SQLite"; my $database = "../data/test.db"; my $dsn = "DBI:$driver:dbname=$database"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; # CREATE TABLE my $stmt = qq(CREATE TABLE MYTABLE (ID INT PRIMARY KEY NOT NULL, DATE TEXT NOT NULL, TIME TEXT NOT NULL, DESCRIPTION CHAR(250));); my $rv = $dbh->do($stmt); if($rv < 0) { print $DBI::errstr; } else { print "Table created successfully\n"; } $stmt = qq(INSERT INTO MYTABLE (ID, DATE, TIME, DESCRIPTION) VALUES (1, '2017-05-13', '07:55:00', 'The very first chicken') +;); $rv = $dbh->do($stmt) or die $DBI::errstr; print "Records created successfully\n"; # convert to JSON my @output; my $sth = $dbh->prepare('select DATE, TIME, DESCRIPTION from MYTABLE +'); $sth->execute; while ( my $row = $sth->fetchrow_hashref ){ push @output, $row; } my $cgi = CGI->new; print $cgi->header( 'application/json' ); print to_json( { myData => \@output } ); $dbh->disconnect();

Replies are listed 'Best First'.
Re: AJAX call to Perl script + return - error
by NetWallah (Canon) on May 08, 2017 at 01:03 UTC
    Take a look at your web server's access.log and error.log - to see if the correct URL to your script is being called.

    Perhaps the URL needs to be absolute, not relative, in your statement:

    method: 'GET', url: `../cgi-bin/test-dbi.pl`,
    Also - it would help if you posted the actual error you got.

            ...Disinformation is not as good as datinformation.               Don't document the program; program the document.

Re: AJAX call to Perl script + return - error
by Anonymous Monk on May 07, 2017 at 22:56 UTC