I'm trying to create a simple calculator which gets an input number from the user and shows the calculated output below it. The code works fine but it redirects and reloads the page, obviously. I don't want that I want the output to be displayed as soon as the user fills the form. I have 0 knowledge of js and ajax so I would appreciate you guys helping me with that part. I searched a lot but couldn't understand what to do. this is my form:
<form id="myform" method="POST">
{% csrf_token %}
Enter first number: <input type="text" name="num1"><br><br>
<input type="submit">
</form>
and this is the output bellow the form I want:
<h1>congrats!</h1>
as simple as that. fill the form, submit and display a simple message without refreshing
If you have zero knowledge and could not produce any code you will most likely face a lot of problem, AJAX vs Django form is another level of complexity and will not implement unless you are 100% sure that will add something to the UX, but in short.
Using Jquery you could built an Ajax call to a Django view :
JS Script:
$(document).ready(function () {
$("form").submit(function (event) {
var formData = {
justification: $("#justification").val(),
};
$.ajax({
type: "POST",
url: "{% url 'django-view' %}",
data: formData,
dataType: "json",
encode: true,
}).done(function (data) {
if (data.success) {
console.log("error");
} else {
# display your text somewhere in your page
}
});
event.preventDefault();
});
});
Django View :
@csrf_exempt
def form_post(request):
# Do something with your data
text = request.POST.get("num1")
print(text)
return JsonResponse({"text": text})
As you can see you need a lot more to work with Ajax, you need a good understanding of Django form, a good enough one for Ajax and JS and finally how asynchronous works.