user3920709
user3920709

Reputation: 111

Ajax with form method as post in node.js

I have an issue with Ajax in a form with node.js, I'm developing a simple node.js currency converter application and populating the data on the frontend (HTML) using Ajax. However it's not working, any help is seriously appreciated. Thanks.

Upvotes: 0

Views: 69

Answers (1)

Ali Yousuf
Ali Yousuf

Reputation: 702

1. Frontend

Change this

xmlhttp.open("GET","http://localhost:9099/", true); 

to

xmlhttp.open("POST","http://localhost:9099/", true); 

as your backend server accepts POST for getting the answer.

2. Backend

Remove response.end and response.writeHead from bottom, and move it to where you are calculating store.

Your final code:

http.createServer(function(request, response) {
  switch (request.method) {
    case 'POST':
      if (request.url === "/") {
        var requestBody = '';
        request.on('data', function(data) {
          requestBody += data;
          if (requestBody.length > 1e7) {
            response.writeHead(413, {
              'Content-Type': 'text/plain'
            });
            response.end('Request Entity is too large');
          }
        });

        request.on('end', function(data) {
          console.log(requestBody);
          var formData = qs.parse(requestBody);

          var requestBofy = '';

          // I renamed the callback parameter to response2
          https.get('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml?8f65cd5d1af1727c40d2a89a31c6a0f1', function(response2) {
            if (response2.statusCode >= 200 && response2.statusCode < 400) {
              response2.on('data', function(data_) {
                requestBofy += data_.toString();
              });
              response2.on('end', function() {
                console.log(requestBofy);
                parser.parseString(requestBofy, function(err, result) {
                  console.log('FINISHED', err, result);

                  var xml = requestBofy;

                  var parseString = require('xml2js').parseString;
                  parseString(xml, function(err, result) {
                    var jFile = JSON.stringify(result);

                    var parsedResponse = JSON.parse(jFile);
                    var rateHUF = parsedResponse['gesmes:Envelope']['Cube'][0]['Cube'][0]['Cube'][6]['$'].rate;
                    var rateINR = parsedResponse['gesmes:Envelope']['Cube'][0]['Cube'][0]['Cube'][22]['$'].rate;
                    var store = 'No value';
                    if (formData.vSelectedValue == 'HUF' && formData.vSelectedValue2 == 'INR') {
                      store = Math.round(formData.vFirstNo * (rateINR / rateHUF));
                    } else {
                      store = Math.round(formData.vFirstNo * (rateHUF / rateINR));
                    }

                    // Your response should end here
                    response.writeHead(200, {
                      "Content-Type": "text/html"
                    });
                    response.end('Your Answer: ' + store);

                  });

                });
              });
            }
          });

        });
      } else {
        response.writeHead(404, {
          'Content-Type': 'text/plain'
        });
        response.end('404 - Page not found');
      }

      break;
    case 'GET':
      if (request.url === "/") {

        getFileContent(response, 'public/home.html', 'text/html');

      } else {
        response.writeHead(404, {
          'Content-Type': 'text/plain'
        });
        response.end('404 - Page not found');

      }
      break;

    default:
      response.writeHead(404, {
        'Content-Type': 'text/plain'
      });
      response.end('404 - Page not found');

  }

}).listen(9099);

Upvotes: 1

Related Questions