PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to allow JSON access to the text within a textarea in HTML>

 July 23, 2022     django, javascript, json     No comments   

Issue

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 }}" 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 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?


Solution

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
    })


Answered By - SamSparx
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing