Transmit the "form data" over to the AJAX request

Snippet of HTML code:

<form id="custom_form" name="custom_upload" method="POST" enctype="multipart/form-data">
<label>Choose File:</label>
 <input id="in" name="csv_file" value="Add CSV" type="file" required />
<table class="opttable">
  <tr>
     <td>
         Title<span style="color: red;">*</span>
     </td>
     <td>
     <select id="select1" class="optselect form-control">
          <option>abc</option>
          <option>cde</option>                                                      
      </select>
      </td>
   </tr>
</table>
<input type="submit" value="Submit" class="onsubmit">
</form>

JavaScript section:

$('.onsubmit').on('click', function (e) {
      var id = {{id}}
      var fd= $('form').serialize()
      console.log(fd)
      $.ajax({
       url: '/someview/'+id,
       type: 'POST',
       data: fd,
       sucess: function(data) {
       console.log(data);
       },
       error: function(err) {
         console.log('err: '+err);
       }
    });
});

This is a code implementation where I am trying to include both file and regular data in an AJAX call. Utilizing the serialize method for converting form data into strings, but wondering how to handle file inclusion along with it.

Answer №1

Using the method $('form').serialize() will generate an array of objects structured as shown below: </p>

<pre><code>[
{"Name":"elementname","Value":"12"},
{"Name":"elementname2","Value":"hello"}
]

You have two options for sending this data. You can either stringify the entire array and send it like this:

data: { "formData" :JSON.stringiy(fd)}

or

You can convert the array into simple key-value pairs and send them to the server as a JSON string:

dataToSend={}

for(var v=0; v<fd.length;v++){
dataToSend[fd["Name"]] = fd["Value"]; 
}

and then include it in the data like this:

data: { "formData":JSON.stringify(dataToSend)}

To handle this data on the server side, you can use the following Python code:

import json
json.loads(request.POST.get('formData'))

Answer №2

To send data to the server, you can utilize the FormData object and append the desired values.

If you are sending a post request, ensure you have a csrf_token. It should be stored within your HTML page. Here's an example:

<script>
    var CSRF_TOKEN = '{{ csrf_token }}';
</script>
$('.onsubmit').on('click', function (e) {
      e.preventDefault();
      var id = {{id}};
      var formData = new FormData();
      formData.append('csvFile', $('#in')[0].files[0]);
      formData.append('csrfmiddlewaretoken', CSRF_TOKEN);

    $.ajax({
       url : '/someview/'+id,
       type : 'POST',
       data : formData,
       processData: false,
       contentType: false,
       success : function(data) {
       },
       error: function(data){
       }
    });
});

To access the file in your views, you can retrieve it using the following code:

csv_file = request.FILES.get('csvFile')

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

Tips for excluding specific codes from running in BeforeAll for a specific Describe() block in Jasmine

Currently, I am in the process of writing a Jasmine unit test spec. The JS file contains several describe() blocks. Within the BeforeAll function, my objective is to execute a function only for the "A" and "C" Describe-Blocks. How can this be accomplished ...

Tips for customizing the appearance of the react-stripe-checkout form

Could someone please provide guidance on applying custom styles to the react-stripe-checkout form component, such as changing the background color? Visit this link for more information ...

Ensure that the headers of the table are properly aligned with the

Here's the code snippet I'm currently working with: function deleteRow(row) { var i = row.parentNode.parentNode.rowIndex - 2; // this -> td -> tr // -2 because the first 2 rows are used for header var tbl = docu ...

Trouble getting templates to render with Django URLs

Instead of guiding me to the page, Django is displaying the following error: “C:\Users\RodrigoPinto\Desktop\Insider\users\register” does not exist This is my URL; from django.urls import path from users import employee_ ...

Having trouble invoking the .js file with form POST

I've encountered a problem with my code that is technically "working," but it's not functioning as intended. Within the header of my page, I have the following code snippet: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jqu ...

The paragraph tag remains unchanged

I am currently working on developing a feature that saves high scores using local storage. The project I'm working on is a quiz application which displays the top 5 scores at the end, regardless of whether the quiz was completed or not. However, I&apo ...

What is the most reliable method for converting a 32-bit unsigned integer to a big endian byte array?

Looking for a simple and reliable method to convert an unsigned integer into a four-byte-array in big endian format, with padding if necessary? Take a look at this example: Input value: 714 Output: Resulting byte array [ 0xca, 0x02, 0x00, 0x00 ]; By the ...

Experiencing difficulties in retrieving property of a non-object when working with json and php

My current project involves using AngularJS to collect user input from a form, then sending this data to a PHP backend for processing. After decoding the JSON file in PHP, I then perform a database lookup to find information that matches the input values. ...

Wcf Service does not define Angular JS methods

I am utilizing a WCF Service within an AngularJS application. The WCF Service is functional, and I am attempting to display a list of user records from a SQL database. However, upon running the application, I encountered the following errors: angular.js: ...

What is the best approach to convert text to uppercase or lowercase based on the length of the string in Angular version 1.5?

My goal is to apply text formatting to a string named 'name'. Once the string is entered into an HTML form and the save button is clicked, the new formatted string should be displayed below the form. The formatting rule states that if the length ...

HTML code displayed on the chat interface

Is there a way or some JavaScript/HTML code to block HTML and cone files from appearing in a chat box when writing HTML code? When I input HTML code in the text box, it appears as is. How can I prevent this? Is there a specific code to use? Below is an e ...

Click on the hyperlinks one by one that trigger ajax events

There is a feature on the popular social media platform reddit.com where you can load more comments by clicking a link. I understand that comments may be hidden for performance reasons, but I would like to automatically expand all comments without having t ...

Extending the declaration of JavaScript native methods is not possible when using TypeScript

When attempting to enhance the JS native String class by adding a new method, I encounter error TS2339. interface String { transl(): string; } String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'St ...

Chrome experiencing stuttering issue with jQuery's .slideUp() function

When I click a button, I want to hide certain elements in my HTML document. $(document).on('mouseup','#button',function() { setTimeout(setupBox1,100); setTimeout(setupBox2,Math.floor((Math.random() * 3000) + 800)); setTimeo ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

Tips for switching the status of each item as I navigate the page with the tab key

I am facing an issue with my list of items that have hidden content appearing on hover. I want to achieve the same functionality while tabbing through my page, but currently, all hidden content appears at once. Check out a live example of my code here jQ ...

"Implementing a feature in Angular to display only a single ul element at a time while iterating through a

In the image above, there is an Add Person button. When this button is clicked, a new row labeled Person 1 is created, and this process continues for each subsequent click. At the right end of every row, there is a share icon that, when clicked, should ope ...

If an empty JSON value is sent, the $_POST variable will be empty

These are the methods I'm using to send data: $.ajax({ url: `/api/task/${taskId}`, type: 'POST', data: JSON.stringify({test: []}), contentType: 'application/json' }); Alternatively, I've also tried this appro ...

Tips for storing information in a database when a user decides to exit

Is there a proper method to achieve this task? I aim to store in the database the number of minutes that a user has watched in a video until they close the page, and then resume the video from where they left off when they revisit the same video. I attempt ...

Stop the Page from Refreshing following an AJAX PUT Call

Is there a way to prevent my page from reloading after an Ajax PUT Request? What I'm trying to achieve is updating my database with a PUT request triggered by a button click. Upon successful update, I want to call another function using AJAX GET to r ...