Unable to send JSON data from server to client following a successful file upload operation

I'm currently working on a project that involves NodeJS, Express, JQuery, and Typescript. The issue I'm facing is related to uploading a file from the front end, which is successful. However, I'm encountering difficulties in returning a JSON object from the server to the client, specifically containing the location of the uploaded file on the server. Instead of being received by the "success: function (response)" function on the client side, the JSON data is rendering on the screen.

Below is the client-side code snippet:

function sendFile() {

    $(new ID().setAsRoot().selectId()).append(
        "<form id=\"fileUploadForm\" accept-charset=\"utf-8\" method=\"post\" action=\"/upload\" enctype=\"multipart/form-data\">" +
            "<input id = \"filename\" type=\"file\" name=\"userfile\" multiple=\"multiple\" />" +
            "<button type=\"submit\"> Upload </button></form>");

    var $form = $("#fileUploadForm");
    $form.submit(function (e) {

        alert("Upload Started");
        // perform client side validations if any

        this.ajaxSubmit({
            error: function () {
                alert("Error");
            },

            success: function (response) {
                alert("Success " + JSON.parse(response));
            }
        });

        // Important: stop event propagation
        return false;
    });
}

And here is the server-side code snippet:

app.post('/upload', function(request, response){
    var upload = new uploadModule.Upload();
    upload.upload(request, response);
});


    public upload(req:express.Request, res) {
        var form = new formidable.IncomingForm();
        var originalFileName:String;
        var filePath:String;
        form.uploadDir = this.directory;
        form.keepExtensions = true;
        form.type = 'multipart';
        var fields = [];
        form
            .on("error", function (err) {
                //res.writeHead(200, {'content-type': 'text/plain'});
                //res.end('error:\n\n' + util.inspect(err));
            })
            .on("field", function (field, value) {
                //console.log(field, value);
                //fields.push([field, value]);
            })
            .on("end", function () {
                //console.log('-> post done');
                //res.writeHead(200, {'content-type': 'text/plain'});
                //res.end('received fields:\n\n ' + util.inspect(fields));
                res.send({
                    path : filePath,
                    name : originalFileName
                });
            })
            .on("file", function(name, file:formidable.File){
                originalFileName = file.name;
                filePath = file.path;
            });
        form.parse(req);
        return;
    }

--- Update ---

I've come across some errors in the Chrome console:

Uncaught SyntaxError: Unexpected token : shortcut_manager.js:123
(anonymous function) shortcut_manager.js:123
(anonymous function) extensions::messaging:327
Event.dispatchToListener extensions::event_bindings:386
Event.dispatch_ extensions::event_bindings:371
Event.dispatch extensions::event_bindings:392
dispatchOnMessage extensions::messaging:294
Uncaught SyntaxError: Unexpected token o Server.ts:21
$.ajax.success Server.ts:21
c jquery.js:3048
p.fireWith jquery.js:3160
k jquery.js:8235
r jquery.js:8778

I am utilizing the JQuery form plugin for file uploads, and it seems that the plugin's js file is not being downloaded in Chrome. Additionally, I am using require JS, where the form plugin has been included.

require(["//malsup.github.io/min/jquery.form.min.js"]);

Answer №1

Based on the information provided, it appears that an AJAX request is not being made when the form is submitted. It seems like the function ajaxSubmit() is being used, but it is not a standard jQuery function. Could it be part of a jQuery plugin that may not be properly loaded?

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

How to clean a string from PHP code using jQuery

Looking for a solution to extract PHP code from a string. The string I have contains PHP code that needs to be removed. text = '<?php // This is a test sample ?> This is a description'; text.replace(/\<\?.*\?\?\ ...

show information from json onto an html page with the help of jquery

I'm looking to showcase buttons from a JSON file within a simple block. Here's the JSON data for movies: { "movies": [ { "title": "Mena", "movieid": "1", ...

Why does Angular CLI create "spec.ts" files?

My current go-to tool for generating and serving projects is Angular CLI. So far, it's been pretty smooth sailing – although I've noticed that for my smaller learning projects, it tends to create more than what I actually need. But hey, that&ap ...

Obtaining the payload of a response sent with Node.js and Express.js

Here is a snippet of code I have written: middlewareA(req,res,next){ res.send('some message to client'); next() } middlewareB(req,res,next){ var sent_message_body = res.<some method or property to retrieve body> logger.info(sent_me ...

getting the HTTP server object in Node.js Express

Currently, I find myself within a middleware function (function(req, res, next) {...}). Is it possible to access the HTTP server object using the req parameter? UPDATE To provide further clarification, my goal is to determine the port on which the serve ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

Understanding how to extract an enum from a string and its corresponding value in TypeScript

I am working with a simple enum called errorCode, shown below: export enum SomeErrorCodes { none = 0, notFound = 1, duplicated = 2 } Currently, I am receiving the name of the enum as a string "SomeErrorCodes" and a number, for example, 1. How ...

Limit the search in the mongoose model to only include keys listed in the schema

Currently, I am in the process of developing a search feature to filter results from a mongoose model. The objective is to have all the filtering options, except for two, applied to Model1. For those last two options, they will then be directed to Model2. ...

Refreshing data asynchronously with Ajax

I am currently using jQuery AJAX to retrieve a page named matid.jsp as shown below: var loadUrl = "matid.jsp"; $(".get").click(function () { $.get(loadUrl, function (responseText) { $("#result").html(responseTex ...

Utilizing jQuery's AJAX GET method with custom parameters to retrieve webpage content

Seeking assistance with using jQuery's get function to call a php script. The php script returns a variable containing the main content of my page, excluding the header/footer. The goal is to update the page content without a reload. Any insights on ...

Tips for using Jquery to retrieve HTML from external sources

I have successfully managed to display an internal webpage on my HTML, as shown below: <!doctype html> <html> <head> <script type="text/javascript" src="jquery-1.4.4.js"></script> </head> <body> & ...

Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time. Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically. clock.component.ts : import { ...

Require assistance with Dhtmlx and Wijmo grid context menus, as well as touch events, specifically when utilized on an iPhone's Safari browser

I recently created a web application utilizing DHTMLX 5.0 and Wijmo grid. Everything functions smoothly when accessed on Chrome for Android, including the context menu which is opened with a touch-'press and hold' gesture. However, I have encount ...

BrowserRouter - The type '{ children: Element; }' is not compatible with the type 'IntrinsicAttributes', as they do not share any properties in common

After upgrading to React version 18, I encountered a type error with the BrowserRouter component. Despite trying various approaches, I am unable to pinpoint the root of the problem. Here is the error that pops up during debugging: Overload 1 of 2, &a ...

What is the best method for updating a nested array within another nested array in an object using MongoDB?

There is a similarity between my issue and the one mentioned in this discussion LINK. However, my problem differs in the following way: { "_id": ObjectId("4d2d8deff4e6c1d71fc29a07"), "comments": [{ "na ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Proper Input Component Typing in React/Typescript with MobX

Looking to create a custom React Input component using Typescript for MobX that requires the following input props: a mobx store stateObject a key from that store stateKey I want Typescript to ensure that stateObject[stateKey] is specifically of type str ...

What could be the reason for encountering the error message "Unable to define properties" while working with NestJs?

Currently, I am facing an issue while trying to assign a value to csrfToken within the session: import { v4 as uuidv4 } from 'uuid'; import * as session from 'express-session'; @Injectable() export class CsrfMiddleware implements NestM ...

The Bootstrap modal window refuses to shut down

In my React application, I am utilizing Bootstrap modal functionality. One specific requirement is that the modal window should remain open when clicking on the modal backdrop. To achieve this, I have implemented the following code: $(".modal").modal({"ba ...

Utilizing MVC6 to send both a CSV file and a string to a controller via Ajax

I'm encountering an issue that involves sending a CSV file along with the value of a string variable back to the controller. Individually, I've been successful in sending the file via the form's submit button and the string variable via aja ...