1

I would like to call function on button click without page refresh in Django so I am using AJAX but it does not work. I haven't know about AJAX before and I am new in it but this is what I managed after 3 days of testing:

Views.py are working but AJAX function does not. It prints Ups, NOT AJAX

views.py:
bot = Instagram()
def instabot(request):
    template = 'instabot.html'
    return render(request, template)

def runinstabot(request):
    print('Welcome here')
    if request.method == 'POST':
        runinstabot.login = request.POST.get('login')
        runinstabot.password = request.POST.get('password') 
        if request.is_ajax():
            bot.login(runinstabot.login, runinstabot.password)
            bot.search()
        else:
            print('Ups, NOT AJAX')
        print(request.POST)
        return HttpResponse('')

    instabot.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
    <title>test bot</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

</head>
<body>
TEST:
<form id='runbot' action='/runinstabot/' method="post" >
    {% csrf_token %}
    <input type='text' id='login' />
    <input type='text' id='password' />
    <input type="submit" value="Submit">
</form>
</body>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript">
    $('runbot').on('submit', function(event){
        event.preventDefault();
        $.ajax({
             type:"POST",
             url: "{ url 'runinstabot' }",
             data: {
                    login:$('#login').val(),
                    password:$('#password').val(),
                    csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
                    },
        });       
   });

</script>
</html>

urls.py:
    url(r'^instabot/', instabot, name='instabot'),
    url(r'^runinstabot/', runinstabot, name='runinstabot'),

Instagram() is a python code that use Selenium to automate some stuff

I would appriciate all advises

memo747
  • 77
  • 10
  • 1
    You shouldn't put your JavaScript code in the same script tag that loads jQuery. The behaviour is undefined - see https://stackoverflow.com/questions/6528325/what-does-a-script-tag-with-src-and-content-mean – Daniel Roseman Sep 09 '18 at 10:02
  • 2
    I strongly recommend you to read [this](https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html) article. – uedemir Sep 09 '18 at 11:09
  • I have found solution and my scripts are working now. This video was very helpful: https://www.youtube.com/watch?v=zojnkKGRXp0&t=4s – memo747 Sep 10 '18 at 17:15

0 Answers0