user2986042 user2986042 - 2 months ago 33
Apache Configuration Question

How to get back values from cgi Cpp to HTML using XMLHttpRequest ajax?

I have HTML page with ajax XMLHttpRequest to acess C++ .cgi file . I am getting values from HTML passing to .cgi and i need to get "sucess" or "failed" message back . This is my aim .

My HTML code :

<!DOCTYPE html>
<html>
<head>

<script type = "text/javascript">

var XMLHttp;

if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");

} else {
XMLHttp = new XMLHttpRequest();
}


function getresponse () {

var fanme = document.getElementById('fname').value ;

var postData;

postData += fname;

XMLHttp.open("POST", "ajaxtry.cgi", true);

XMLHttp.onreadystatechange = function() {
document.getElementById('response_area').innerHTML = XMLHttp.responseText;
}

// Set the appropriate HTTP request headers
XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttp.setRequestHeader("Content-length", postData.length);

// Make request
XMLHttp.send(postData);



}
</script>

<h1>Sample application</h1>

First Names(s)<input onkeyup = "javascript: getresponse ()" id="fname">

<div id = "response_area">
</div>


</body>
</html>


and the cpp .cgi file :

#include <unistd.h>
#include <iostream>
#include <vector>
#include <string>

#include "cgicc/Cgicc.h"
#include "cgicc/HTTPHTMLHeader.h"
#include "cgicc/HTMLClasses.h"

#include <stdio.h>
#include <string.h>

using namespace std;
using namespace cgicc;

int main(int argc, char **argv)
{

Cgicc cgi;

try {

form_iterator fname = cgi.getElement("fname");
form_iterator sname = cgi.getElement("sname");

if(null != **fname)
{
cout<<"sucess";
}
else
cout<<"failed";

}
catch(exception& e) { }

return 0 ;

}


I am getting output like : some encode values :

ELF>�@@@1@8 @ @@@@@��88@8@@@�� ��`�`�@ ��`�`TT@T@DDP�td��@�@LLQ�tdR�td��`�`((/lib64/ld-linux-x86-64.so.2GNU GNUMh���N��N틟����~��0!P


why i cannot get success or failed message back to inner HTML of Div ? Anything missing ? Any suggestions ?

Answer

The output you are getting appears to be the compiled binary of your C code itself.

You need to configure your server to execute the program and return the response instead of serving it up as a static file.

Generally, you'll need something along the lines of:

<Directory "/usr/local/apache2/htdocs/somedir">
    Options +ExecCGI
    AddHandler cgi-script .cgi
</Directory>

A detailed guide is in the manual.