Transmit the document to Django using Ajax

I am encountering an issue when trying to send an image using an AJAX request to Django. Below is the HTML code I am using:

<form>
<input type="file" id="files" name="image">
</form>

Next, here is the corresponding JavaScript code:

var control = document.getElementById("files");
var p = {
        title: $('input[name=title]').val(),
        subtitle: $('input[name=subtitle]').val(), 
        content: $('textarea#article-content').val(),
        image: files[0],
    };
    $.ajax({
        url: '/prive/nouveau-projet',
        type: "POST",
        data: JSON.stringify(p),
        crossDomain: true,
        success: function() {
            window.location.href = '/prive/projets/';
        },
        error: function() {
            console.log("error");
        }
    });

Finally, below is the server-side code snippet for handling the request:

if request.method == "POST":
    data = request.POST.keys()[0]
    dataJson = json.loads(data)
    p = Projet(title=dataJson['title'], subtitle=dataJson['subtitle'], content=dataJson['content'], image=dataJson['image'])
    p.save()
    return HttpResponse()

This implementation results in errors related to dataJson['image']. Can anyone provide guidance on how to resolve this issue? Thank you.

Answer №1

Avoid using JSON.stringify, as it is not necessary in this case.

You can simply follow this structure:

var formData = new FormData();
var imageFile = $('#image_field_id')[0].files[0];
formData.append('image', imageFile);
$.ajax({
    url: "/private/new-project",
    processData: false,
    contentType: false,
    type: 'POST',
    data: formData,
}).done(function(response) {
    // process the response data            
});

And in your backend views:

if request.method == "POST":
    file = request.FILES.get('image') # Use FILES instead of POST
    ....

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 why passing $var within @{{ }} in Vue.js + Laravel is not functioning as expected

I am integrating Algolia Vue-InstantSearch into a Laravel Project. Since we are working with a blade file, the {{ }} symbols will be recognized by the php template engine. To ensure that they are only understood by Vue in JavaScript, we can add an @ prefix ...

I am having difficulty aligning the vertical touch event owl carousel

Here is the link: "jsfiddle.net/nLJ79/". Can you try to find a solution to make the owl carousel vertical? ...

Issues with styled-components media queries not functioning as expected

While working on my React project with styled components, I have encountered an issue where media queries are not being applied. Interestingly, the snippet below works perfectly when using regular CSS: import styled from 'styled-components'; exp ...

Tips for retrieving information from a web endpoint using Angular

My task involves utilizing Angular to retrieve data from a web endpoint and display it to the user. The setup requires configuration through bower and the use of grunt as a task manager. I have already installed bower, Angular, and Bootstrap, with the pag ...

Retrieve an item from an array based on the unique ID value of the button that was clicked using

I am working with a phones array that is populated with JSON data: var phones = [ { "age": 0, "id": "motorola-xoom-with-wi-fi", "imageUrl": "img/phones/motorola-xoom-w ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Execute a multer request to upload an image (using javascript and express)

I am utilizing the Express server as an API gateway for my microservices, specifically to process and store images in a database. The issue at hand is that within the Express server, I need to forward an image received through a POST request from the clien ...

How can I convert the date format from ngbDatepicker to a string in the onSubmit() function of a form

I'm facing an issue with converting the date format from ngbDatepicker to a string before sending the data to my backend API. The API only accepts dates in string format, so I attempted to convert it using submittedData.MaturityDate.toString(); and su ...

Add information to a MySQL database using PHP and AJAX within the WordPress platform

In my function.php file, I created a new top-level admin menu. Inside it, I added input fields within an HTML form. <form id="prices_form" method="post" action=""> <div style=font-weight:bold;font-size:16px;>Location 1</div> < ...

Error: Unable to convert Mongoose object to ObjectId

Currently tackling an issue with my small blog app and I seem to be stuck at this error- { "message": "Cast to ObjectId failed for value \" 597c4ce202ca9c353fc80e8a\" at path \"_id\" for model \"Blog\"", "name": "CastErr ...

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...

What is the best way to transfer Express.js variables to MongoDB operations?

I have been developing a blogging application using Express, EJS, and MongoDB. Feel free to check out the GitHub repository for more details. One of the features I've implemented is a simple pager for the posts within the application. Within the pos ...

Establishing a callback function to assign an event handler

I am trying to set up an event handler after making a successful ajax request. The function setup_chat() is responsible for setting the event handler, and it functions correctly except when called as a callback. Here's an example: $('#create_gam ...

Show only upon initial entry: > if( ! localStorage.getItem( "runOnce" ) ) { activate anchor link

My JavaScript form performs calculations, but I only want it to display the first time a visitor enters the site. I attempted to add the following code before my script: jQuery(document).ready(function($) { if( ! localStorage.getItem( "runOnce" ) ) { ...

Struggling with sending a post request in Node.js as the response always returns with an empty body

Here is the structure of my project And this error pops up when I run my program using npm run dev command I'm working on a basic webpage where users can input their name, email, and job details. I then try to insert this information from the HTML fo ...

Is there a quicker alternative to the 500ms delay caused by utilizing Display:none?

My div is packed with content, including a chart from amCharts and multiple sliders from noUiSlider. It also features various AngularJS functionalities. To hide the page quickly, I use $('#container').addClass('hidden'), where the rule ...

Unable to import the UserSerializer module into another serializers.py file

I've been faced with a puzzling issue that I can't seem to resolve. My goal is to import the UserSerializer() from the 'accounts' app in order to nest it within the CommentSerializer() in the 'comments' app. Interestingly, I ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Uploading files in AngularJS using Rails Paperclip

I have been working on implementing a file upload feature with AngularJS/Rails using the Paperclip gem. I was able to resolve the file input issue with a directive, but now I am facing an issue where the image data is not being sent along with other post d ...