Home > OS >  Ajax form not sending data in django
Ajax form not sending data in django

Time:07-31

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/{% url "home" %}

I am unable to find, where is the issue.

CodePudding user response:

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.

  • Related