1

I am working on a Django environment. I have created a form in my html page which contains a textbox for input for a label like "Enter your name" . I have a submit button below the textbox. I need to pass the inputted name to the button as a value and then this button value is to be passed to a python function in views.py.

Can anyone help me with this ?

Siddharth Singh
  • 105
  • 3
  • 15
  • 2
    To reach to django, you must reach to the server. You reach to the server by performing a request. Read about ajax with django. – Adelin Feb 07 '18 at 13:26
  • 1
    i think you mean you don't want to refresh the page. just execute a function on click? if so you need to use `XMLhttprequest` or `Ajax` – mohammedgqudah Feb 07 '18 at 13:26
  • 2
    Possible duplicate of [How do I integrate Ajax with Django applications?](https://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications) – Adelin Feb 07 '18 at 13:27
  • @mohammed qudah Yes exactly. I don't want to refresh the page. I want to execute a function on click with the button value being passed to the function in the backend – Siddharth Singh Feb 07 '18 at 13:37
  • i will answer the question, the solution will be using jQuery – mohammedgqudah Feb 07 '18 at 13:47
  • @mohammed qudah Thank you man – Siddharth Singh Feb 08 '18 at 05:06

1 Answers1

0

To do this you need to use Ajax, its like calling a url in the background without affecting the user. but first to call a a url(view) we need a url and a view. so i will think you have something like this

url('^click/btn/(?P<data>[0-9]+)', views.click_btn, name="btn_click");

and the view

def click_btn(request, data):
    # do whatever you want with the data....
    return HttpResponse('Done')

now to call this from the fron-end we will use jQuery.ajax

first you have the button

<button id="btn_click">Click me!</button>

now create a script tag and type the following

the script tag must be after the button so he can see it

<!-- if you haven't included jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// get your input value...
var data = $('#my_input').val();
$.ajax({
    url: `/click/btn/${data}`,
    success: function (res) {
    // every code in this function will execute when Ajax call the url
    alert(`Nice! you called the url and get this data: ${res}`)
    }
});
</script>
mohammedgqudah
  • 568
  • 4
  • 15