QUERY_STRING is not obtained in CGI (C code)

1.7k views Asked by At

I'm using lighttpd server. And trying to write a sample CGI in C and return an HTML to the server. My ajax call for CGI is

    <head>
            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <title>Watch TV</title>
            <script src="js/jquery.js"></script>
            <script type="text/javascript">
            function myTest(){
                    $.ajax({
        type: 'GET',
        url: "http://10.47.5.158:50080/htmldiag/cgi-bin/test.cgi",
        async: true,
        data: {'m':2, 'n':3},
        dataType: "html",

        success: function(data) {
            console.log("Entered success case------------------------", data);
        },
        error: (function(msg, url, ln) {
            console.log("Entered error case------------------------", msg, url, ln);
        })
    });
            }
            </script>
    </head>

and my CGI is

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *data;
long m,n;
printf("%s%c%c\n",
"Content-Type:text/html",13,10);
printf("Access-Control-Allow-Origin: *");
printf("<!DOCTYPE html><html>\n");
printf("<HEAD><TITLE>Multiplication results</TITLE></HEAD>\n");
printf("<BODY><H3>Multiplication results</H3>\n");
data = getenv("QUERY_STRING");
if(data == NULL)
  printf("<P>Error! Error in passing data from form to script.");
else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2)
  printf("<P>Error! Invalid data. Data must be numeric.");
else
  printf("<P>The product of %ld and %ld is %ld.",m,n,m*n);
printf("</BODY></HTML>\n");
return 0;
}

I've tried by giving arguments from URL too. I cant get the QUERY_STRING, or get the response in HTML format. All I get is the log that it entered in success case and the whole cgi file in the console.

1

There are 1 answers

0
Lewis Anesa On

Really easy,

The environment variable QUERY_STRING is set to the query string. You can fetch it by this call :

char *query = getenv("QUERY_STRING");

Notice the man page of getenv and take care that the returned string may be statically allocated. (Don't hesitate to use strdup and free).