Home > Software design >  How to allow JSON access to the text within a textarea in HTML>
How to allow JSON access to the text within a textarea in HTML>

Time:07-20

I am trying to create a button that allows users to save edits to a post, which they write in a textarea, through JSON.
I am trying to save the data through a PUT request, but I get 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 }}" >{{ post.post }}</h6>
                {% if post.user == request.user %}
                    <button id="{{ post.id }}"  value="{{ post.id }}">Edit</button>
                {% endif %}
                <textarea  id="edit_area_{{ post.id }}" cols="220" rows="5"></textarea>
                <button  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 works correctly, but I am receiving the previously stated error from the PUT request. I think that it is because of the way I am getting the value through edited_post = data["edit_area"]. How do I correctly get access to the text within the textarea to pass to JSON?

CodePudding user response:

In your save_edit PUT function you are using

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

But in your view you are looking for

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

The JSON you are sending looks like

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

So you probably want something like:

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

Also - fetch uses "body" not "post" so you might want to amend your put function to

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