Call Python Function from JavaScript Code

Call Python function from JavaScript code

All you need is to make an ajax request to your pythoncode.
You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript

$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});

Call python function from JS

Apart from the mentioned points and assuming you already have a proper setup to serve your python script and return the response. You should submit an asynchronous request, especially if the python code does some heavy computation.

function postData(input) {
$.ajax({
type: "POST",
url: "/reverse_pca.py",
data: { param: input },
success: callbackFunc
});
}

function callbackFunc(response) {
// do something with the response
console.log(response);
}

postData('data to process');

If you only do some light computation and you have no problem working with a code deprecated as of jQuery 1.8, go with the synchronous approach. This is not recommended as it blocks the main thread.

function runPyScript(input){
var jqXHR = $.ajax({
type: "POST",
url: "/reverse_pca.py",
async: false,
data: { param: input }
});

return jqXHR.responseText;
}

// do something with the response
response= runPyScript('data to process');
console.log(response);

Read more about it here: How do I return the response from an asynchronous call? and http://api.jquery.com/jquery.ajax/

How to call Python functions from JavaScript in Django?

in the urls.py you create an url

path('my-ajax-test/', views.myajaxtestview, name='ajax-test-view'),

then your ajax should loook like

pay attention to the csrf_token otherwise will send you an error

        $ajax({
type: "POST",
url: '{{ url 'ajax-test-view'}}',
data: {csrfmiddlewaretoken: '{{ csrf_token }}',
text: "this is my test view"}, /* Passing the text data */
success: function(response){
alert(response);
}
});

in views.py

def myajaxtestview(request):
return HttpResponse(request.POST['text'])

Summary:

you need to create the url in your urls.py which leads to your views.py
then the view gets the data that you've sent in the request.POST in the request you have plenty of data you can find more about it here.
in your case you are more interested in request.POST it's a python dictionary
so you pick the parametre that you have send and work with it
you may play with it like return HttpResponce('test'+ request.POST['text'])

If you want to get something from models.py let's say you data that you sent from the js is {object_type: hammer}

def myajaxtestview(request):
look_for = request.POST['object_type']
#lets say you have model Items
my_items= serializers.serialize('json', Items.objects.filter(object_type=look_for))
return JsonResponse(my_items)


Related Topics



Leave a reply



Submit