Ajax form not sending data in django

Question:

I am trying to send data to Django without page refresh. So I am using ajax.
Created a Django model and form

class MyModel(models.Model):
    text=models.CharField(max_length=100)

class MyForm(forms.ModelForm):
    class Meta:
        model=MyModel
        fields = "__all__"

Then send the form to the HTML page via views.py

def home(request):
    print(request.POST.get('text',False))
    form = MyForm(request.POST)
    if request.method=='POST':
        print(request.POST.get('text',False))
        if form.is_valid():
            data=form.save()
    return render(request,'home.html',{'form':form})

Create a form in HTML template

<form action = ""  id="post-form" method = "post">
      {% csrf_token %}
      
      {{ form.as_p }}
      <input type="submit" value="submit" id="submit-button">
    </form>

This is the javascript file


$(document).on('submit','#post-form',
    function(x){
        x.preventDefault();
        console.log("button clicked")
    $.ajax({
            type:'POST',
            url:'/',

            data:{
                text:$("id_text").val(),
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
                },
           

            success:function(){
                alert('Saved');
                      }
                    })            
    
    
    }

)

I think it might be the issue with URL, if i set url like this way

url:'{% url "home" %}',

Then in console, i got this error

XHR POST http://127.0.0.1:8000/%7B%%20url%20%22home%22%20%%7D

I am unable to find, where is the issue.

Asked By: Talha Anwar

||

Answers:

You should use # for selecting id, so use text:$("#id_text").val().

For using dynamic url, use like this:

url:"{% url 'home' %}",

For more information, about using dynamic urls refer this question.

Edit:

One way to use dynamic url is to pass it with onsubmit event, so try this:

Template file or home.html

 <form id="post-form" method="POST" onsubmit="checking('{% url 'home' %}')">
        {% csrf_token %}
        
        {{ form.as_p }}
        <input type="submit" value="submit" id="submit-button">
    </form>

Js file:

function checking(dynamicUrl) {
  $(document).on("submit", "#post-form", function (x) {
    x.preventDefault();
    console.log("button clicked");
    $.ajax({
      type: "POST",
      url: dynamicUrl,

      data: {
        text: $("#id_text").val(),
        csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
      },

      success: function () {
        alert("Saved");
      },
    });
  });
}
Answered By: Sunderam Dubey