Home > front end >  Form data is passing in html table
Form data is passing in html table

Time:05-23

I am submitting the form data by using fetch API and then I want to show some variable values in HTML table. But it's not working as it's supposed to be. I am getting the value in the HTML table as "undefined". I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong.

Console screen output

Console log

urls.py

from django.contrib import admin
from django.urls import path,include
from django.shortcuts import render, HttpResponse
from home import views

urlpatterns = [

    path('', views.home, name='home')

]

views.py

from json import dumps

def home(request):

    context={}

    if request.method=="POST":

        options_value=request.POST.get('options_value')

        value=request.POST.get('value')

        print(type(options_value),value)

        context['options_value'] = options_value

        context['value']= value

        return JsonResponse(context, safe=False)

    return render(request, 'index.html', context)

index.html

<form method="POST" action="" id="form">
      {% csrf_token %}
          <select
            
            aria-label="Default select example"
            name="options_value"
            id="options_value"
          >
            <option disabled hidden selected>---Select---</option>
            <option value="1">Profile UID</option>
            <option value="2">Employee ID</option>
            <option value="3">Email ID</option>
            <option value="4">LAN ID</option>
          </select>
          <input
            type="text"
            
            type="text"
            placeholder="Enter Value"
            name="value"
            id="value"
          />

          <input
            
            type="submit"
            value="Submit"
            style="background-color: #3a0ca3"
          />
    </form>

<table style="display: table" id="table">
        <tbody>
            <tr>
              <th scope="row">ProfileUID :</th>
              <td></td>
            </tr>
           
            <tr>
              <th scope="row">First Nane :</th>
              <td></td>
            </tr>

        </tbody>
      </table>
<script>
      let form = document.getElementById("form");
      let options_value = document.getElementById("options_value");
      let val = document.getElementById("value");
      const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value;


      form.addEventListener("submit", (e) => {
        e.preventDefault();
        const newform = new FormData();
        newform.append("options_value", options_value.value);
        newform.append("value", value.value);
        newform.append("csrfmiddlewaretoken", csrf);
        fetch("", {
          method: "POST",
          body: newform,
        })

      .then((response) => {

            console.log(response.json());
            let data = response.json();
            console.log("Success:", data);
            let tds = document.querySelectorAll("table tr td");
            tds[0].innerHTML = data.options_value;
            tds[1].innerHTML = data.value;

          })
       .catch(error => {
       console.error('Error:', error);
       });

      });
    </script>

CodePudding user response:

Either you use Django-Template to display data or you use JavaScript if you want to submit your form using JavaScript then you've to use JavaScrip to display data I'm sharing JavaScript approch let me know if you want to use Django-Template then I'll add that.


Just use JsonResponse

def home(request):
    context={}

    if request.method == "POST":

        options_value = request.POST.get('options_value')

        value = request.POST.get('value')

        print(type(options_value),value)

        context['options_value'] = options_value
        context['value'] = value

        print(context)

        return JsonResponse(context)

    return render(request, 'index.html')

and inside your JavaScript do like this

fetch("",
  {
    method: "POST",
    body: newform,
  })
  .then(response => {
    let data = response.json()
    console.log('Success:', data);
    let tds = document.querySelectorAll('table tr td')
    tds[0].innerHTML = data.options_value
    tds[1].innerHTML = data.value
  })
  .catch(error => {
    console.error('Error:', error);
  });

and this is how your HTML will look

<table style="display: table" id="table">
  <tbody>
    <tr>
       <th scope="row">ProfileUID :</th>
       <td></td>
    </tr>
    <tr>
       <th scope="row">First Nane :</th>
       <td></td>
    </tr>
    
  </tbody>
</table>

Update

this three lines are culprit

console.log(response.json());
let data = response.json();
console.log("Success:", data);

it should be

let data = response.json();
console.log("Success:", data);

CodePudding user response:

You can use document.write() to rewrite the html of the page with the data you receive from the fetch request.

fetch(url,option) // Abstracted for brevity
.then(response => response.text())
.then(data => {document.write(data);})

Although this would satisfy your needs, however, it's not the best way to update the values in the document. By rewriting the entire HTML for the document, all stylesheets, images and scripts have to be loaded and executed again, which is unnecessary. Additionally, injecting scripts like this is dangerous.

In case you are performing operations such as saving the results of the form to a database, it's better to return a JSONResponse indicating the result of the operation to the fetch request, and then update the HTML using JavaScript.

Ex.
views.py

from django.http import JSONResponse

def home(request):
  if request.method == "POST":
    # Operations
    if success:
      return JSONResponse(
        {
          "successful": True,
          "message": success_message,
          "data": {}, # Anything else you'd like to send, like Profile UID and Name
        }
      )
    else:
      return JSONResponse(
        {
          "successful": False,
          "message": error_message,
          "data": {}, # Anything else you'd like to send
        }
      )
  # Handle other request methods

index.html's fetch request

fetch(url, options)
.then(response => response.json()) // returns a promise that converts response to a JS Object
.then(data => { // data is a JS object, which is 
                // the same as the dictionary we had in views.py
  if (data.successful === true) {
    // You can set IDs for the `td` where you would like to update the values
    // like "profile-uid" and "profile-name"
    // data.data is the dictionary returned by the JSONResponse 
    // that has additional information, which is also converted to a JS Object
    document.getElementById('profile-uid').textContent = data.data.puid; 
    document.getElementById('profile-name').textContent = data.data.pname;
  }
  else {
    // Handle Errors
  }
})

CodePudding user response:

1st choice) If you're sending a fetch request, I think it's better to use jsonify({'data':dataJSON}) and get data on the same webpage itself.

2nd choice) On your front-end HTML, you can work on your response by storing it like this. JSON.parse('{{ context | tojson }}') in a variable. Make sure you are passing context as a JSON Object from your views.py

  • Related