Transferring documents using Angular and Django

I'm currently working on a blog project using Angular and Django. I have created a page where users can create new posts by entering a title, body, and attaching a file.

Below is the controller code:

$scope.newPost = {};

$scope.addPost = function(){
  if ($scope.newPost){
    PostListSrv.addPost.add($scope.newPost, function(data) {
        if (data) {
          console.log('success');
        }
      }, function(error) {
        if (error) {
          console.log('error');
        }
      }
    );
  } else {

          console.log('Error');
  }
};

This is the service used to communicate with the server:

   .....
  addPost: $resource('my_url', {
  }, {
    add: {
      method: 'POST',
      headers: { 'Content-Type': 'multipart/form-data' },
      params:{title:'title', text:'text', file: 'file'}
    }
  }), 
  ....

The issue arises when attempting to add a new post, resulting in a 400 Error. Specifically, in the 'response' tab under 'Network' (Firefox), a red line indicates: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. How can this be resolved?

Answer №1

Prior to transmitting the parameters, remember to employ JSON.stringify().

.....
createNewPost: $resource('my_url', {
}, {
  post: {
    method: 'POST',
    headers: { 'Content-Type': 'multipart/form-data' },
    params: JSON.stringify({title:'newTitle', body:'newBody', attachment: 'newAttachment'})
  }
}), 
....

Answer №2

To upload a file, simply use the $upload function.

$upload.upload({
    url: 'file-upload-service/',
    file: fileToBeUploaded,
    data: {'name': fileName},
    method: 'POST',
    withCredentials: true,
    contentType:'multipart/form-data',
    dataType:'text'
});

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

Ways to trigger a PHP function after a successful AJAX query

I have incorporated AJAX into my project, as shown in the code below: $.ajax({ type: 'POST', data: ..., success: function(data) {<?php calc(); ?>}, error: function(jqXhr, textSt ...

Cookie information will always be visible in the information box

When I click on my button, the page reloads and the box disappears. However, no cookie is set when I click, and it also does not check if a cookie is set or not. The current problem is: No cookie is added It does not check if the date today is more than ...

Creating a JSON array in Django

# view code: response_data = [] for p in product: response_record = {} response_record['pname'] = p.name response_data.append(response_record) ... # create json formatted array return HttpRespon ...

Transferring data from a div to JavaScript

As a newcomer to the world of javascript, I am experimenting with it for the first time. I have a div that triggers a javascript function. Within this setup, I utilize a timezone controller along with a show.html file that displays the timezone information ...

Changing the CSS class of the Bootstrap datetime picker when selecting the year

Is there a way to change the CSS style of the Bootstrap datetime picker control so that when selecting years, the color changes from blue to red? I attempted to do this with the following code: .selectYear { background-color:red!important; } However ...

How can I utilize an external file in Node js to output as a response?

I came across a similar inquiry, but I am interested in exploring manual methods. My goal is to achieve this without relying on express or any other external library. var http = require('http'); var server = http.createServer(function(req, res) ...

Consistently showcasing images of varying dimensions that are unfamiliar

Currently, I'm in the process of developing a small web application that uses the Spotify API to fetch and showcase top tracks and artists to users. Each track or artist is presented within a Bootstrap panel, with the title displayed in the header an ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Trigger a JavaScript alert when encountering an error message in the database connection function within PHP

Hey there, I've created a function within the db class: FUNCTION DB_Class($dbname, $username, $password) { $this->db = MYSQL_CONNECT ('localhost', $username, $password) or DIE ("Unable to connect to Database Server") ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...

Using Angular Formly to create a select input that is populated with objects

I would like you to take a look at the jsbin provided. I have a select input with options for Ohio and NewYork. In the ng-options for the Select, I am selecting the entire object instead of just the name or key value. I require both to be selected. Upon s ...

Using ES6 syntax to inject modules into an extended controller can result in the Unknown provider error

Currently, I am facing an issue with creating a child class ModalCtrlChild extends ModalCtrl from my controller class ModalCtrl. Whenever I attempt to do this, I encounter an unknown provider error related to the modules injected in ModalCtrl. The project ...

How to structure a URL to retrieve JSON data from an API using the fetch method

As a newcomer to working with APIs and data retrieval methods, I have been exploring tutorials such as this one on the fetch method or using the XMLHttpRequest method. While I have had success with the APIs used in these tutorials, I have run into difficul ...

What is the best way to link the data from the HTML input to the class property in the TypeScript file? (Combining Angular and IntroJs)

I'm working on an onboarding screen with Intro.js and need help with receiving user input. I've been trying different methods like [(ngModel)] = checked, [(checked)] = checked, (checked) = checked, but haven't had any success. Can anyone pro ...

I aim to cross-reference words within a matrix, yet I struggle to pinpoint every word in all eight directions in the matrix

I have a matrix of characters arranged in such a way that they form meaningful words. Additionally, I also have an array of words with their respective starting and ending positions on the matrix. My goal is to extract an array of strings by combining all ...

Show React compilation errors

Whenever I used to start React as per their tutorial, it would show compile errors in this specific scenario. However, after setting up a webpack configuration for a React project, if there are compilation errors, the page simply remains blank. Is there ...

Exploring the concept of reflection in JavaScript and jQuery

Here is a javascript object I have: person.Name = "John"; person.Nick = "Smith"; person.Info = "hi there"; In addition, I have some HTML elements as shown below: <input id="Name" /> <input id="Nick" /> <input id="Info" /> My question ...

Select elements that do not have a specific parent class using LESS

I have created an HTML structure as outlined below: <ul class="list list--sm"> <li class="list__item list__item--draggable"> List item 1 <ul> <li class="list__item list__item ...

Maintain current page with HTML form action

I am currently working on a newsletter signup form located in the footer of every page on my website. When a user enters their email and clicks submit, the form takes them to "newsletter.php" which then sends me an email with their information. However, I ...

An error popped up while using the fetch API due to an unexpected end of input

fetch('http://www.freegamesforyourwebsite.com/feeds/games/?tag=platform&limit=100&format=json', { method:'GET', mode:'no-cors', dataType: 'json', headers: { 'Accept': 'a ...