Tips for enabling JSON access to the content inside a textarea element in HTML:

I'm attempting to develop a button that enables users to save edits to a post they write in a textarea using JSON. However, when attempting to save the data with a PUT request, I encounter the following error:

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Javascript function:

function save_edit(id){
    console.log("save button is clicked");
    const edit_area = document.querySelector(`#edit_area_${id}`);
    //save the post
    fetch(`/edit/${id}`,{
        method: 'PUT',
        post: JSON.stringify({
            post: edit_area.value
        })
    })
    fetch(`/edit/${id}`)
          .then(response => response.json())
          .then(post => {
                const post_itself = 
                      document.querySelector(`#post_itself_${id}`);
                      post_itself.value = `${post.post}`;
                      post_itself.style.display = 'block';
           
    })
}

Django views:

def edit(request, post_id):
    try:
        post = Post.objects.get(pk=post_id)
    except Post.DoesNotExist:
        return JsonResponse({"error": "Post not found."}, status=404)

    if request.method == "POST":
        edited_post = request.POST.get('post')
        try:
            post.post = edited_post
            post.save()
        except:
            return JsonResponse({"error": "Editing the post did not work."}, status=404)

    elif request.method == "GET":
        return JsonResponse(post.serialize())

    elif request.method == "PUT":
        data = json.loads(request.body)
        edited_post = data["edit_area"]
        post.post = data["edited_post"]
        post.save()

    else:  
        return JsonResponse({"error": "Need a GET request."}, status=404)

HTML:

{% for post in page_obj.object_list %}
            <div class = "individual_posts">
                <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a>
                <h6 id = "post_itself_{{ post.id }}" class="post_itself">{{ post.post }}</h6>
                {% if post.user == request.user %}
                    <button id="{{ post.id }}" class="edit_button" value="{{ post.id }}">Edit</button>
                {% endif %}
                <textarea class="textarea" id="edit_area_{{ post.id }}" cols="220" rows="5"></textarea>
                <button class="edit_save" id="save_{{ post.id }}">Save</button>
            </div>
        {% endfor %}

models.py serialization

def serialize(self):
        return{
            "id": self.pk,
            "post": str(self.post),
            "user": self.user.pk,
        }

The GET request functions correctly, but I am encountering the aforementioned error from the PUT request. My assumption is that it's due to how I access the value through

edited_post = data["edit_area"]
. How can I correctly retrieve the text within the textarea to pass to JSON?

Answer №1

When working with the save_edit PUT function, make sure to use the following code:

    post: JSON.stringify({
        post: edit_area.value
    })

However, in your view, you should be looking for something like this:

    data = json.loads(request.body)
    edited_post = data["edit_area"]
    post.post = data["edited_post"]

The JSON being sent appears as follows:

{"post": "Here's my edits"}

To correct this, consider using:

    data = json.loads(request.body)
    post.post = data["post"]

Furthermore, keep in mind that fetch uses "body" not "post," so adjust your put function accordingly:

    body: JSON.stringify({
        post: edit_area.value
    })

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

Error alert: Blinking display, do not dismiss

I am trying to make it so that when the "enviar" button is clicked, the "resultado" goes from being hidden ("display:none") to being visible ("display:block"). This is my html document: <script type="text/javascript"> function showResu ...

Utilizing a particular iteration of npm shrinkwrap for project dependencies

When deploying my node.js app to Appfog, I encountered a problem with their install script failing to parse npm-shrinkwrap.json. The current format of a dependency in shrinkwrap.json is as follows: "async": { "version": "0.2.10", "from": " ...

Establishing a universal function within Ionic AngularJS

I have the following code snippet, where I have added a reset function that I want to be able to use from ng-click in any part of any template. angular.module('starter', ['ionic', 'starter.controllers', 'starter.services ...

How can you utilize a bind function to deactivate a button?

Can someone help me figure out how to temporarily disable a button using the bind function for 10 seconds? jQuery('#wsf-1-field-155').bind('click', function() { ScanRegistration(); setTimeout(function() { jQuery('#wsf- ...

organizing various kinds of data values within an array

Within this array, I have two types of variables - an integer and a string. My goal is to sort the array either alphabetically or by the length of the string. However, it seems that the sorting algorithm is prioritizing the integer over the string. ...

Accessing a specific item from a JSON response in Python

I have a specific dataset that I need to extract items from the "item" object. The challenge is that sometimes the response can be an array, and I'm struggling with how to handle this situation in Python. My goal is to iterate through these values and ...

Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) { using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() { if (x.state == 4 && x.responseCode == 200) notifyUser(i); } } My goal now is to e ...

What is the relationship between JavaScript and the height of a window?

Consider the code snippet below: 24 <script type="text/javascript"> 25 26 function UpdateDisplay($isVisible){ 27 if($isVisible) 28 $('.relatedContent').stop().css({ 29 "transform": "tr ...

The functionality of loading JSON is not working properly in ePub3

Currently, I am working on a project involving the creation of an ePub3 eBook. One of the exciting features I have successfully integrated is three.js to showcase some models. My next goal is to develop 'hotspot' elements (small cubes that users ...

Guide to retrieving a specific cookie value with socket.io

I have successfully retrieved all cookies using the socket.request.headers.cookie. Upon console logging, the output appears as follows: PHPSESSID=mtklg8k81cpkop5ug6aechbb34; user=77; io=1Klg6xgTRXhb2OWiAAAA Now, I am trying to extract only the value of ...

Steps for organizing a list based on the number of clicks

I've created an HTML list with images of political party logos. Each logo is a grid item that can be clicked on. I want to sort the list based on the number of clicks each logo receives, essentially ranking them by popularity. However, I'm not su ...

Setting a class in AngularJS when there is a change in ng-repeat with pagination

I am currently attempting to assign a class to an item in a paginated list by simulating a click on the element within the directive's link property: link : function (scope, element, attrs) { element.bind('click', function () { ...

Having difficulty transforming the Json string into a Map<String, Object> structure

I need help converting my JSON data into a map using jackson-core-2.9.6. Here is an example of the JSON: { "name": "Loren", "inputDetails": { "truncated": false, "result": [ { &qu ...

What is the best way to use Immer to update Zustand state when incorporating objects that are added through a controlled form using React-Hook-

Having some trouble with integrating Zustand and Immer using React-Hook-Form. My goal is to capture a series of values from a form, store them in a list, and allow for the addition of new objects to that list. In this scenario, the user inputs data for a ...

Best practice for integrating configuration settings into a Redux application

One essential step before launching my application is to read the config.json file. This file contains the URLs to my backend services, which will be utilized in my Redux action creators. I have contemplated two different approaches: Fetching the JSON a ...

Angular factory variable scoping

I am encountering an issue with altering the folders variable (an array) within the return statement of my Angular factory. It seems to work for the create action, but I am having trouble with the scope of the variable in the factory. This code works: fo ...

Encountering a C# ASP.NET error while attempting to parse JSON data from a file using JObject

I'm attempting to run the following code: JObject settingsInfo = JObject.Parse(File.ReadAllText("settings.json")); const string ServerName = (string)settingsInfo["servername"]; Despite its apparent simplicity, I am consistently encountering the fol ...

How can I set a header to be automatically included in every "render" response in Node.js/Express?

One of the challenges I face involves implementing "controllers" in my code: app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); In particular, I'm worki ...

Adding a logo to a website that utilizes CSS, HTML, JS, and Bootstrap

Hey there! I'm new to the world of Front-end development and I've been learning by watching videos and reading everything I can find on the Internet. Currently, I'm using HTML, CSS, and JS for my website. Can anyone help me figure out how to ...

Guide to utilizing JSON classes in Xcode 4.1

How can I utilize the nsjsonserialization class in my Xcode 4.1 project? Do I need to download any frameworks for it, and if so, where can I find them? ...