1

I'm trying to have Django to run a function when I tell it based off a JavaScript button. How do I accomplish this? Where do I write the Django function?

JavaScript in main.html:

            function mainFunction(){
            alert("Beginning API Main Function");

                $.ajax({
                    type: 'POST',
                    url: 'livestream/postdata/',
                    success: function(){alert('DONE!');},
                    error:function(){alert('ERROR!');},
            });
            alert("ENDING API MAIN FUNCTION");
        }

Urls.py:

    url(r'^postdata$', 'livestream.views.postdata', name='postdata')

Views.py:

def postdata(request):

    r = ...api... (I know that the api works)
    print(r.text)

When I run the function 'mainFunction()' I get the two alerts and then another that says 'ERROR'. Why is this?

9
  • And this isn't cross site like in your other question? Commented Aug 7, 2013 at 20:33
  • ya, I'm going to take a different approach to the problem Commented Aug 7, 2013 at 20:57
  • 1
    I believe the url (in AJAX) should be: url: '/livestream/postdata/', (notice that first /?) Commented Aug 7, 2013 at 21:16
  • @HieuNguyen Thanks, but it didn't fix the issue of the error Commented Aug 7, 2013 at 21:31
  • Could you post your full view code then? Commented Aug 7, 2013 at 21:38

3 Answers 3

1

Set up a route in your urls.py file

url(r'^action/$', 'yourproject.views.action', name='action')

In your views.py file, you would create that action.

def action(request):
  # do your magic!

Then, when someone interacts with that button, do an ajax call that hits the URL at /action.

1
  • I updated the question. I followed your code, but it doesn't seem to work yet. Commented Aug 7, 2013 at 20:51
0

You add a listener to the button which makes an ajax call when fired. In your view.py you handle the response for that ajax call.

1
  • 1
    Can you explain how I do this? and where in the view.py I put the code? THanks Commented Aug 7, 2013 at 20:33
0

@HieuNguyen

Thank You for answering my question. It was through chat, so I'll write down, what worked.

  1. in ajax need a '/' before lifestream. /livestream/postdata/
  2. url(r'^postdata/$', 'livestream.views.postdata', name='postdata')
  3. in views.py

    before function I needed @csrf_exempt

    return HttpResponse(r)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.