0

I'm trying to do page with simple calculator. I made calculator in js, and now, when I click button I want to pass arguments from js to django. Count them there and print on redirect page.

I have problem with redirect page. When I dont put button in form, js script call calc view, but dont redirect page. I want redirect page and print a result there.

html code:

<form action="calc/" method="post">
    {% csrf_token %}
    <input id='btn' type="submit" value="CALC" onclick="change()">
</form>

javascript code:

function change(){
    var foo = 1;
    var foo1 = [1, "tralal", true, ''];

    $.ajax({

        url: 'calc/',
        data : {
            'foo': foo,
            'foo1': foo1,
        },
        success: function (data) {
            alert("it worked!");
        }
    }
)};

urls in django

path('calc/', views.calc, name='calc')

view in django

def calc(request):
    foo = request.GET.get('foo')
    print(foo)
    foo1 = request.GET.getlist('foo1[]')
    print(foo1)
    context = {'data': foo1}
    return render(request, 'calc.html', context)
magnus250
  • 97
  • 3
  • 12

3 Answers3

0

If you want to redirect to another page, you have to do it explicitly from the javascript when the success callback is called. You can see here some answers on how to redirect the page from javascript. To do so, you will have to have another view for serving the result page. The results of the calculation can be kept in the server (cached), or communicated from the client.

But, I wonder why you are using an Ajax request for that. Ajax requests are useful if you want to do some async http requests to the server without refreshing (or redirecting) the page. So I would say, don't use an Ajax request here, just simply submit the form. You can have a look for example here to see how forms work in javascript. You can also check this Django tutorial about using forms. Django has some tools for handling forms that can be quite convenient when for instance you want to update or create new instances in your database model. It can be a bit confusing at the beginning, but I think it is worth spending some time understanding Django forms.

XavierFav
  • 3
  • 2
  • Hey, I tried do this using window.location.href = "http://127.0.0.1:8000/calc/"; in js, but this doesnt solve the problem, because It starts 2 times calc view. First without arguments from js (redirect to ~/calc/) second passing arguments, but without page refresh (from ajax). I cant use forms there. I wrote in post that I want create simple calculator, but that would pass the truth. This is calculator which convert user's draw to a matrix on which I can perform operations and give back a result on new redirect page. – magnus250 Apr 03 '19 at 16:32
0

I do something like this, it work, but I dont know is it correct.

views.py

def link(request):
    global matrix
    matrix = request.GET.getlist('foo1[]')
    return HttpResponseRedirect('/calc/')


def calc(request):
    if request.is_ajax:
        global matrix
        context = {'data': matrix}
        return render(request, 'calc.html', context)
    else:
        return HttpResponseRedirect('/')

urls.py

path('link/', views.link, name='link'),
path('calc/', views.calc, name='calc'),

js function

$(document).ready(function() {
$("#btn").click(function(e) {
    var foo = 1;
    var foo1 = [1, "tralal", true, ''];

    $.ajax({
        url: 'link/',
        data : {
            'foo': foo,
            'foo1': foo1,
        },
        success: function (data) {
             window.location.href = "calc/"
        }
    });
});
});

html code

<input id='btn' type="submit" value="COUNT">

calc.html

{% for d in data %}
    <p>"{{ d }}"</p>
{% endfor %}

Page redirect to calc/ and show correct not none matrix. Result

magnus250
  • 97
  • 3
  • 12
0

What you get when using window.location.href = "127.0.0.1:8000/calc" is normal. You are just redirecting to the same page without any url query parameters.

So, you basically want to redirect to the same page? Why then do you want to redirect? This does not make much sense to me. And again, if you wanna redirect, don't use AJAX, and follow the "normal" approach for submitting forms.

So what I think makes more sense, is to not redirect, but use the data you receive from the the AJAX request and show the information. You can still use some Django tempting en return some rendered HTML that you will then add dynamically with some Javascript code.

It could be something like that:

Javascript

$.ajax({
    url: 'link/',
    data : {
        'foo': foo,
        'foo1': foo1,
    },
    success: function (data) {
         $('#result-container').html(data)  // add the data in the div container
         $("#your-form").trigger('reset'); //you should reset your form
    }
});

Main HTML at "/" should contain

<div id="result-container"></div>

And you should just get rid of your link view and have the other somehow like that

def calc(request):
    if request.is_ajax:
        matrix = request.GET.getlist('foo1[]')
        context = {'data': matrix}
        return render(request, 'calc.html', context)

But I tell you again, you should use Django forms for what you are doing. See this tutorial for example.

I hope it helps.

XavierFav
  • 3
  • 2
  • Im on main page 127.0.0.1:8000/ then I click button and js send data to django, django math and show results on 127.0.0.1:8000/calc/ page. https://imgur.com/a/ZMa0UIL <-- this is what user create in canvas window with js. I cant use forms. I generate matrix from image, and this matrix I want pass to django. In an earlier post I put only piece of code, so this could put you in error. – magnus250 Apr 04 '19 at 20:13