I have a python script running in views.py within Django which returns two very large string arrays, x and y. It currently is able to run off a button press within my index.html.
def python_file(request):
final()
return HttpResponse("ran")
The ajax code I have running to do the button press.
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function gotoPython(){
$.ajax({
url: "/python_file",
context: document.body
}).done(function() {
alert('finished python script');
});
}
</script>
It’s also attached to the URLS.py. I know there’s no array being returned right now, because I am unsure how to run the script, get the data simultaneously, then add it to the page without refreshing the page. So, I am asking what would be the best practice to do what I described. Any help would be appreciated.
2
Answers
You can add parameters to the ajax.done(function) in order to get what your server returned.
You can check ajax documentation here : https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings-settings
And your django view should return some text content :
This is generally what I do, not sure if it’s best practice, but I return it with Json
I included two examples, and POST and a GET.
I also included some other stuff I usually return
status
andmsg
. When I catch an error or have an invalid POST I send backstatus = False
andmsg = '{error message}
, then I can show that error message in the front end with Javascript. I keep this standardized in my project, but you do you.Note: Some things like, Django
Decimal
objects, can not be be put into a Json Dump. In the Decimal example you’ve got to turn them into a Float or an Int