user2986042 user2986042 - 1 year ago 67
Ajax Question

Why file is not creating in CGI with Apache?

I want to write some contents to a file using CGI with Apache .

my HTML file :

using Ajax HTTP method to call CGI script . I am not passing any arguments to the CGI . Finally i am printing response text to a div.

<!DOCTYPE html>


var xhttp;

function loadDoc() {


xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {
document.getElementById("message").innerHTML = this.responseText;

}catch (exception){

alert("Request failed: " + exception.message);




<h2>sample ajax</h2>

<button type="button" onclick="loadDoc()">Change Content</button>

<div id ="message" />


and cgi.cpp file

Here i creating a file with write mode , write some contents to that file and successfully close . Send response text "successfully write " to HTML back .

#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>
#include <fstream>

using namespace std;
using namespace cgicc;

int main(int argc, char **argv)

Cgicc cgi;

try {

ofstream myfile; ("Newcgi.txt",ios::out);
cout<<"Content-Type: text/html\n\n";
myfile << "Writing this to a file.\n";
cout<<"Sucessfully write";

catch(exception& e) {


return 0;


But i can not see any file created in
or in
. Why this is happening ? Where should be a new file created ? is it in Apache directory ?

Any code problem ? I am writing to a file with write mode also . I think code is working fine . Any suggestions ?

Answer Source

Summary of previous comments:

  • Check privileges of your CGI file. Often there is a special user nobody which owns /var/www and which is used by Apache to execute scripts/processes.
  • Check if C++ CGI process is hit by Apache, does it return a response over HTTP.
  • Check what ofstream::is_open() returns, where it tries to create file. Good candidates to store created file by CGI process are /tmp and cgi-bin working directory (which is configured within httpd.conf), often it's /var/www/cgi-bin/
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download