django ajax using jquery and Jasonresponse

 


+++++++++++++++++++++++

Template 


{% block javascript %}

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


    <script>

        $(document).ready(function () {

            // catch the form's submit event

            $('#changelogs').submit(function () {

                // create an AJAX call

                $.ajax({

                    data: $(this).serialize(), // get the form data

                    type: $(this).attr('method'), // GET or POST

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

                    // on success

                    success: function (response) {

                        alert("Thankyou for reaching us out " + response.id);

                    },

                    // on error

                    error: function (response) {

                        // alert the error if any error occured

                        alert(response.responseJSON.errors);

                        console.log(response.responseJSON.errors)

                    }

                });

                return false;

            });

        })

    </script>

    {% endblock javascript %}


+++++++++++++++++++++++++



Views ===============


++++++++++++++++++++++


def logs(request):

    if request.method == 'POST':

        log = request.POST.get('logs')

        print(log)

        logsave= Changelogs.objects.create(changelogs = log)

        logsave.save()

        hanglogs = list(Changelogs.objects.values().order_by("id"))

        return JsonResponse(hanglogs, safe=False)

    changlogs = list(Changelogs.objects.all().order_by("id"))

    hanglogs = list(Changelogs.objects.values().order_by("id"))

    params = {'name':'ritesh','site':'India','changelogs':changlogs}

    return render(request, 'files/logs.html', params)


++++++++++++++++++++++

Comments

Popular posts from this blog

javascript validate form by separate by comma

20 python library