0
votes

I'm new to AJAX and I have some problems with passing variables back to the HTML script.

I am using a XAMPP webserver, JavaScript and jQuery for the HTML script and a Perl cgi script as backend.

I need to take an input string, pass it to the CGI script where it will be used in a Perl function. The resulting string variable from the Perl cgi script needs to be passed back to the HTML frontend and be used for a function inside the $(document).ready(function(){}).

As of now, I am able to pass a user defined input to the cgi script and display the result as a simple HTML text. But how can I use the cgi output as a variable for further JavaScript/jQuery functions?

Any help would be greatly appreciated.

This is my HTML and JavaScript code:

<!doctype html>
<html>
<head>
    <title>AJAX example</title>

    <script type="text/javascript" src="_lib/jquery.js"></script>
    <script type="text/javascript" src="jquery.jstree.js"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            /*
            I need to use the string variable "#searchtext" in this example function:

            $("#filter").click(function () {
                $("#testtree").jstree("search",$("#searchtext").val());
            });
            */

        });

    </script>

    <script language="Javascript">

        function xmlhttpPost(strURL) {
            var xmlHttpReq = false;
            var self = this;
            // Mozilla/Safari
            if (window.XMLHttpRequest) {
                self.xmlHttpReq = new XMLHttpRequest();
            }
            // IE
            else if (window.ActiveXObject) {
                self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
            }
            self.xmlHttpReq.open('POST', strURL, true);
            self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            self.xmlHttpReq.onreadystatechange = function() {
                if (self.xmlHttpReq.readyState == 4) {
                    updatepage(self.xmlHttpReq.responseText);
                }
            }
            self.xmlHttpReq.send(getquerystring());
        }

        function getquerystring() {
            var form     = document.forms['f1'];
            var word = form.word.value;
            qstr = 'w=' + escape(word);
            return qstr;
        }

        function updatepage(str){
            document.getElementById("result").innerHTML = str;
        }
    </script>
</head>

<body>      
    <form name="f1">
        <p>word: <input name="word" type="text">  
        <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/cgi-bin/ajax_test.cgi")'></p>
        <div id="result"></div>
    </form>

</body>
</html>

This is my Perl script ajax_test.cgi:

#!/usr/bin/perl -w

use strict;
use warnings;
use CGI;

my $query = new CGI;

my $word = $query->param('w');

print $query->header;
print "<p>You are searching for: <b>$word</b>.</p>";

Update:

I tried to use the first solution suggested by collapsar but I'm still not sure where to put the js vars because I need to be able to call them inside the $(document).ready(function(){}):

<script language="Javascript">

function xmlhttpPost(strURL) {
    //...//
}

function getquerystring() {
    //..//
}

function updatepage(str){
    //...//
}

var resp_html = self.xmlHttpReq.responseText;
var resp_dom  = jQuery.parseHTML(resp_html );
var mydata1 = $('#<custom-id-1>', resp_dom).text();

// the alert doesn't work
$("#alertbutton").click(function () {

    alert( "You entered: " + mydata1);

});

1

1 Answers

1
votes

option 1: content processing

you have to parse the content from the server on the client if you transmit (semi-)structured data, ie. html or xml. to simplify access to the data of interest, issue id attributes to the tags/elements you will be generating server-side.

server-side code (augmenting you sample):

print "<p>You are searching for: <b id="<custom-id-1>">$word</b>.</p>";

client-side retrieval and processing:

var resp_html = self.xmlHttpReq.responseText;
var resp_dom  = jQuery.parseHTML(resp_html );

var mydata1 = $('#<custom-id-1>', resp_dom).text();

the code snippet presumes, based on tha tags on your questions, that you use jquery (in case you don't why not?). you can also resort to plain dom methods, see the applicable documentation on mdn.

if you resort to a plain text response, there will be no need for markup and thus no need to parse the response and extract the relevant data with dom methods. you would get the desired data by text search & replace operations. which way to go depends on the complexity and intended use of your data.

caveat: what you best avoid is using html/xml and extract the information using search & replace. while technically feasible in many settings, it's usually a nightmare in maintainability and quite often breaks down during the evolution (read: integration of new features) of the software.

option 2: http headers (not recommended)

you have the alternative option to send your information in custom http headers. while this method will circumvent potential problems the parsing the content and the content's encoding, you will most certainly violate the recommendation in rfc 6648 (for a discussion see this SO thread).

having said that, the method is technically viable. in your perl script use

print $query->header(
    { 
        '<custom-header-1-name>' => '<custom-header-1-value>'
      , '<custom-header-2-name>' => '<custom-header-2-value>'
# ...          
    }
);

for client-side retrieval, use:

var mydata1 = self.xmlHttpReq.getResponseHeader('<custom-header-1-name>')
var mydata2 = self.xmlHttpReq.getResponseHeader('<custom-header-2-name>')
// ...

the tags to your question suggest that you're using jquery anyway (in case you don't, why not? ;-)), so while you're at it have a look at the jquery ajax api.