Sarath Chandran
Sarath Chandran

Reputation: 189

Ajax not working- No change in the data and page will renderd when submit

Trying to make a submission with out rendering the page, But it's not working and the page will rendered when clicking the submit button. How can i update the details form the following field?

Template something like this

{% for i in userlist %}
<form method="POST" id="profileUpdate">
    {% csrf_token %}
    <input class="email" type="email" value="{{i.email}}" id="email">
    <input class="dob" id="dob" type="text" value="{{i.date_of_birth}}" >
    <button type="submit" class="btn btn-primary">Save changes</button>
</form>
{% endfor %}

Ajax script

<script>
        $(document).on('submit', '#profileUpdate', function (e) {
            $.ajax({
                type: 'POST',
                url: '{% url "profileUpdate" %}',
                data: {
                    email: $('#email').val(),
                    dob: $('#dob').val(),
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    action: 'post'
                },
                success: function (json) {
                    alert("Success");
                },
            });
        });
    </script>

views.py

def profileUpdate(request):
    response_data = {}
    if request.get('action') == 'post':
        email=request.POST.get('email')
        dob=request.POST.get('dob')

        response_data['dob'] = dob
        ob=Employee.object.get(email=email)
        ob.date_of_birth= dob
        ob.save()
        return HttpResponse('')

urls.py

urlpatterns = [    
    path('registeredusers', registeredusers.as_view(), name="registeredusers"),
    path('profileUpdate', views.profileUpdate, name='profileUpdate'),
    
]

Upvotes: 0

Views: 64

Answers (1)

Mr Khan
Mr Khan

Reputation: 2292

Use preventDefault() to prevent page load.

<script>
        $(document).on('submit', '#profileUpdate', function (e) {

            e.preventDefault(); //====> Add this line.
            $.ajax({
                type: 'POST',
                url: '{% url "profileUpdate" %}',
                data: {
                    email: $('#email').val(),
                    dob: $('#dob').val(),
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    action: 'post'
                },
                success: function (json) {
                    alert("Success");
                },
            });
        });
    </script>

Upvotes: 1

Related Questions