0

I have view which takes care of all the Ajax submits from the client side. And to differentiate them by I uses different submit button names such as this one

<input type="submit" value="Send" name="send_message">

Suggested from this question. The only problem is that from the view side it doesn't seems to carry the name to the server side so I cannot use the following if-statement

if 'send_message' in request.POST:

It works if I send it normally with page fresh. But I want to use it with Ajax.

I came up with a hack that you can add this name with jQuery. Simply by after serializing() your data you then concatenate the name attribute by data += "&send_message"

Then the if statement will work. But it doesn't seems so clean. So I wonder if there's a better way to handle this? Or should I make different views to handle the different Ajax calls I have?

Community
  • 1
  • 1
starcorn
  • 7,071
  • 19
  • 73
  • 118

1 Answers1

0

You really should post each form to a different URL.

If not, you could add a hidden input with the name of the form as the value.

<input name="form_name" type="hidden" value="form_1" />

views.py:

form_name = request.POST['form_name']

  • The things it will be many different urls which doesn't actually bring the user to another page. I thought it would be cleaner to stack all the Ajax calls to the same url instead. And then check what ajax call it is and process it accordingly – starcorn May 14 '12 at 10:40
  • It's normally considered cleaner to have one function (view, url) do one specific task only. But if you really want to organize all your code into one view, then you can use an hidden element as above. –  May 14 '12 at 11:57