The data sent through the $.ajax POST request is being received as undefined in the server's response

My goal is to set up email functionality on my website. However, I am encountering an issue where the message returns as undefined when logged in the console. I am struggling to determine what information the server is receiving, as all attempts to log the data from the server also return as undefined. While I typically use XMLHttpRequest, I am now trying to implement $.ajax but unsure if I am doing it correctly. The front-end code looks like this:

$(function () {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function ($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function ($form, event) {
            event.preventDefault(); 
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; 

            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "mail",
                type: "POST",
                datatype: "json",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function () {
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Your message has been sent. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    $('#contactForm').trigger("reset");
                },
                error: function () {
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function () {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function (e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


$('#name').focus(function () {
    $('#success').html('');
});

The back-end code is as follows:

var express = require('express');
var mail = express.Router();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var mandrill = require('mandrill-api/mandrill');
var config = require('../mailkey.js');
var mandrill_client = new mandrill.Mandrill(config.key);

mail.post('/mail', jsonParser, function (req, res) {
    var message = {
        "html": "<p>" + req.body.message + "</p>",
        "subject": "*You have received a message from someone*",
        "from_email": config.from,
        "from_name": req.body.name,
        "to": [{
            "email": config.from,
            "name": config.name,
            "type": "to"
        }],
        "headers": {
            "Reply-To": req.body.email
        },
        "metadata": {
            "phone": req.body.phone
        }
    };

    console.log(message);
    var async = false;
    var ip_pool = null;
    var send_at = null;
    mandrill_client.messages.send({ "message": message, "async": async, "ip_pool": ip_pool, "send_at": send_at }, function (result) {
        res.sendStatus(200);
    }, function (e) {
        res.sendStatus(500);
        console.log('An error occurred sending the mail: ' + e.name + ' - ' + e.message);
        
    });
});


module.exports = mail;

Answer №1

After reviewing your ajax request, it appears that you have not assigned any parameter to the success handler.

success: function (response){
console.log(response);
}

Answer №2

After deciding not to use $.ajax and opting for XMLHttpRequest, I needed to specify the request header as json by:

xhr.setRequestHeader("Content-type", "application/json"); The adjustments made in the front end code were:

$(function () {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function ($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function ($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            var xhr = new XMLHttpRequest();
            xhr.open('post', '/mail', true);
            xhr.setRequestHeader("Content-type", "application/json");
            var data = {
                name: name,
                phone: phone,
                email: email,
                message: message
            };
            var jsonData = JSON.stringify(data);
            xhr.send(jsonData);
            xhr.onload = function () {
                var response = xhr.response;
                if (response === "OK") {
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Your message has been sent. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                } else {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                }
            };
        },
        filter: function () {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function (e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function () {
    $('#success').html('');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting the 403 error in Laravel 5.2 with AJAX POST requests

I'm experiencing difficulties with Laravel 5.2, specifically when attempting an AJAX POST request, I encounter a 403 error Here is the code for the AJAX POST request: $.ajax({ headers: { 'X-CSRF-Token': $('meta[ ...

Display detailed images upon hovering

Top of the morning to everyone. I'm in search of a way to display higher resolution images when hovering over lower resolution ones. I want to create a rule or function that can handle this dynamically without manually adding hover effects and changi ...

Learn how to trigger various servlets by clicking different buttons within an HTML form

I have an HTML form and I need to call two different servlets when two different buttons are clicked. How can I change the form action at runtime? <form> <input type="submit" value="Question Paper" style="height:25px; width:120px; background-colo ...

Incorporate a secondary (auxiliary) class into ReactJS

Looking to create a helper class similar to this: export default class A { constructor() { console.log(1); } test() { console.log(2); } } and utilize it within a component like so: import React, { Component } from "react"; import A from ...

Calculations in JavaScript determined by responses provided in the form

I have recently developed a web form that includes various input fields and radio buttons. The purpose of this form is to collect answers from users for cost calculation. However, I am uncertain about the JavaScript logic, especially regarding the radio bu ...

Exploring the analysis of JavaScript and CSS coverage throughout various pages or websites

The Chrome Dev Tools JavaScript and CSS Coverage Drawer is quite impressive, but there is one thing that could make it even better. It would be great if it could remain active without restarting its analysis every time you visit a new page. I wish I could ...

Implementing an Audio Notification System in PHP

When a certain value is violated, I want to display multiple alert boxes as well as an audio alert. Additionally, I need an option to close the audio alert. My current attempt looks like this: if( ($mark<=$minValue) || ($mark>= $maxValue)) { ...

Despite creating a new array, Vuetify 2 continues to display 10 in the pagination options

I am facing an issue in Vuetify 2 where I have set the pagination options of a data table to be [50,60,70], but on the page, it displays [10,50,60,70]. It seems to be combining the default 10 into the list. https://codepen.io/anon/pen/NQRRzY?&editable ...

Transmitting data via POST method within datatables ajax call

I am facing an issue while attempting to execute a simple ajax call in datatables that relies on a post array of IDs from a form on a previous page. The error I encounter is: Invalid JSON Response This indicates that the JSON array being returned may be ...

Navigating between sibling components in Angular 1.5 using the component router

Is there a way to use the new component router in Angular 1.5 to display the sibling component alongside the main one within the ng-outlet directive? I am looking to showcase both the Detail View and the List View at the same time. Based on my understandin ...

What is the best way to sequence the functions in an AJAX workflow?

I'm currently working on optimizing the execution order of my functions. There are 3 key functions in my workflow: function 1 - populates and selects options in a dropdown using JSON function 2 - does the same for a second dropdown function 3 - ...

Produce an additional page while remaining on the present one

I have a PHP-based invoice system that displays all customer invoices. I am interested in adding a feature that allows users to print an invoice directly from the list page without navigating away. While I am familiar with window.print() and media="print" ...

Loading JSON data into HTML elements using jQuery

I am currently grappling with coding a section where I integrate data from a JSON file into my HTML using jQuery. As a newbie to jQuery, I find myself at a standstill. https://jsfiddle.net/to53xxbd/ Here is the snippet of HTML: <ul id="list"> ...

Encountering a "Raphael is undefined" error message when working with Treant.js

I need help creating an organizational flow chart using treant.js. Below is my code snippet, but I'm encountering a 'Raphael is not defined' error that I can't seem to solve. Can someone please assist me with identifying the root cause ...

Uncovering the secrets: accessing hidden folder files in react-native-fs

I am encountering a problem when trying to access files from a hidden folder /WhatsApp/Media/.Statuses in react-native-fs. Despite granting the READ_EXTERNAL_STORAGE permission on Android, I only receive an empty array when attempting to access it using th ...

Scrolling an HTML element to a specific value within its content

Code: /* -------------------------------------NAV & BANNER------------------------ */ #logo{ height: 60px; width: 60px; } .nav-color{ transition: 0.5s; background-color: rgba(0, 0, 0, 0.75); } .nav-null-color{ transition: 0.5s; } .banner{ ...

The problem with THREE JS OcclusionComposer: encountering "Cannot read properties of undefined (reading 'x')" error

I am attempting to replicate the Volumetric Lighting demonstration created by JMSWRNR but I am encountering difficulties with the Occlusion Composer. Since I am not well-versed in GLSL, debugging has proven to be quite challenging, especially for someone l ...

What are some ways to implement AJAX with input from the user?

I'm currently working on a project to create a basic web page that will make use of AJAX for displaying results. Within main.py, I have a dictionary of words: words = { 'a': True, 'aah': True, 'aahed': True, ...

"Troubleshooting AmCharts: How to Resolve Missing Data on Graphs/Implementing AJAX for AmCharts Data Visualization/Querying a Database to Dynamically

After writing some HTML and JavaScript code, I'm trying to set up an amcharts plot. To do this, I fetch data from a database using PHP, convert it into JSON format, and then pass it to the graph for display. The issue arises when I try to assign the ...

Tips for addressing flickering issues when scrolling on your device

I am facing an issue with two elements that are set to a fixed position on the page. When these elements reach the bottom of the page, I want them to revert back to a static position using JavaScript. The problem occurs when trying to scroll by clicking a ...