A
A
Artyom Innokentiev2015-09-12 11:04:25
JavaScript
Artyom Innokentiev, 2015-09-12 11:04:25

Why is there a redirect to localhost:8000/ after sending a POST request via AJAX?

I use jQuery AJAX and Django.

When you click the "Add" button, a POST request is sent (csrf token is created using the csrf.js file, as in the documentation ), the source address of the local server is localhost:8000, after sending the request it changes to - localhost:8000/?. Why is this happening? A snippet of the index.html

file :

<form>
    <input type = "text" id = "task_text"><input type = "submit" value = "Добавить" id = "add">
</form>


Snippet of index.js file :
$('#add').click(function()
    {
      text = $('#task_text').val();

      $.ajax(
      {
        url: '/test/',
        type: 'POST',
        data: {task_text: text}, 
        success: function(text){
          console.log(text)
        },
      });
    });


Views.py snippet :
def test(request):
  if request.is_ajax():
    r = request.POST['task_text']
    Task.objects.create(text = r)
    return redirect('/')
  else:
    message = "bad"
    return HttpResponse(message)


If you have any advice, criticism of the code - please write)

Also, there is a related question:
  • Is it possible to use AJAX without form <form>and <input type = "submit">using only <input type = "button">and index.js file?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexey, 2015-09-12
@artinnok

the initial address of the local server is localhost:8000, after sending the request it changes to - localhost:8000/?. Why is this happening?
Apparently because of this line:
Is it possible to use AJAX without a form
You can hang a click handler on the button and send an ajax request inside. You actually do this, so the form can simply be removed from the markup.

I
Ivan Demidov, 2015-09-12
@Scrum

$('#add').click(function()
    {
      text = $('#task_text').val();

      $.ajax(
      {
        url: '/test/',
        type: 'POST',
        data: {task_text: text}, 
        success: function(text){
          console.log(text)
        },

        return false;
 
      });
    });

And it's better to hang up a listener on the form and listen to
submit

A
Artem Klimenko, 2015-09-12
@aklim007

still at the moment pay attention djbook.ru/rel1.8/ref/settings.html#append-slash

V
Vladislav Sklyar, 2015-09-12
@VladSkliar

You have the same view in the view:
Write

success: function(text){
          alert(response['msg'])
        },

And in the view:
msg_value = 'Your text is add!'
response_data['msg'] = unicode(msg_value)
return JsonResponse(response_data)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question