How to call a python function through an ajax call in a django project? -


i'm starting on simple web app , i'm trying call python function render separate view via ajax call. want click on try button , render different html template. right displays error message ajax, have no idea possibly breaking it. need point me in right direction..some sort of starting point appreciated. in advance :)

my project urls.py looks

from django.conf.urls import include, url, patterns django.conf.urls.static import static django.contrib.staticfiles.urls import staticfiles_urlpatterns sudokuproject import settings  urlpatterns = patterns('', url(r'', include('sudokuapp.urls', namespace="sudoku"))) + static(settings.media_url, document_root=settings.media_root)  urlpatterns += staticfiles_urlpatterns() 

my app urls.py

from django.conf.urls import include, url . import views  urlpatterns = [     url(r'home/', views.sudoku_home, name="home"),     url(r'solve/', views.sudoku_solve, name="solve") ] 

views.py

from django.shortcuts import render django_ajax.decorators import ajax  def sudoku_home(request):     return render(request, 'sudokuhome.html')  @ajax def sudoku_solve(request):     return render(request, 'sudokusolve.html') 

$(document).ready(function(){      $('#try').click(function() {          alert('hi');          $.ajax({              url:"{% url 'sudoku:solve' %}",              type:"post",              success: function (data) {                  alert('woohoo success');              },              error: function(data) {                  alert("something's wrong");              }          })      });  });
<body>      hello welcome sudoku      <button id="try">try me</button>  </body>    <script type="text/javascript" src="{% static 'js/jquery.js' %}" ></script>

i believe using django-ajax library, , installed it.

according django-ajax documentation, have return dictionary:

@ajax def my_view(request):     c = 2 + 3     return {'result': c}  # result send browser in following way (json format)  {"status": 200, "statustext": "ok", "content": {"result": 5}} 

so function should return this:

@ajax def sudoku_solve(request):     return { "message": "hello world!" } 

and can use data in front-end this:

...         success: function (data) {             alert(data.content.message);         }, ... 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -