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?

George Stocker
58k29 gold badges185 silver badges239 bronze badges
asked Aug 7, 2013 at 20:27
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.

answered Aug 7, 2013 at 20:32
Sign up to request clarification or add additional context in comments.

1 Comment

I updated the question. I followed your code, but it doesn't seem to work yet.
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.

answered Aug 7, 2013 at 20:29

1 Comment

Can you explain how I do this? and where in the view.py I put the code? THanks
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)

answered Aug 8, 2013 at 16:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.