0

I'm basically having the same issue addressed in a previous question (Django request.POST does not contain the name of the button that submitted the form) but the fix described there does not work.

I am using ajax so that, after submission, I stay on the same page. My page has two forms. The first form has three buttons and I correctly pass the "name" of the button in the GET request. My second form has two buttons but I am unable to pass the "name" of either button in the GET request (the "name" of the input field, however, is in the GET request). I don't know why it's not working. Any ideas?

JS SOLUTION:

$(document).ready(function(){
    console.log("hello from email.js");
    $('.email_citations').submit(function(event){
        console.log("submit email");
        var whichButton = $(".form_button[clicked=true]")[0].value
        console.log("WHICH BUTTON: ");
        console.log(whichButton);
        var email_address = $(this).val();
        var data = $(this).serialize();
        data += "&" + whichButton;
        console.log(data);
        $.ajax({
            data: data,
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            success: function(data){
                console.log("DATA: ");
                console.log(data);
                $('.email_sent_message').html(JSON.parse(data).submit_message);
            }
        });
        return false;
    });
    $(".form_button").click(function() {
        $(".form_button").removeAttr("clicked");
        $(this).attr("clicked", "true");
    });
});

html forms:

<!-- This form works! -->
<form action="export_options" method="get">
    <button type="submit" name="plain" class="button inline large hover" id="exportButton2">Download Plain Text</button>
    <button type="submit" name="ris" class="button inline large hover" id="exportButton1">Download RIS File</button>
    <button type="submit" name="bibtex" class="button inline large hover" id="exportButton3">Download BibTeX File</button>
  </form>

<form class="email_citations" id="EmailCitationsForm" action="email_it" method="get">
    <input class="input-text" type="text" size="75" maxlength="75" style="width: 40%; font-size: 16px; margin-right: 5px; height: 50px" name="email_address" placeholder="email address">
    <button type="submit" value="selected" name="which_citations" class="form_button button inline large hover" id="exportButton4" >Send My Selected Citations</button>
    <button type="submit" value="all" name="which_citations" class="form_button button inline large hover" id="exportButton5">Send All Citations</button>
</form>
<div class="email_sent_message" style="float: left; color: #9e1d2a; font-size: 20px; font-weight: bold">{{ submit_message }}</div>

My javascript/ajax in an email.js file:

$(document).ready(function(){
    console.log("hello from email.js");
    $('.email_citations').submit(function(event){
        console.log("submit email");
        var clicked_button = $(".form_button[clicked=true]")[0].name;
        console.log(clicked_button);
        clicked_button.push($(".form_button[clicked=true]")[0].value);
        console.log(clicked_button);
        var email_address = $(this).val();
        var data = $(this).serialize();
        data += "&" + clicked_button;
        console.log(data);
        $.ajax({
            data: $(this).serialize(),
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            success: function(data){
                $('.email_sent_message').html(JSON.parse(data).submit_message);
            }
        });
        return false;
    });
    $(".form_button").click(function() {
        $(".form_button").removeAttr("clicked");
        $(this).attr("clicked", "true");
    });
});`

My view:

def email_it(request):
    context = RequestContext(request)
    if request.method == 'GET':
        getdict = request.GET.dict()
        form = EmailCitationsForm(request.GET)
        if form.is_valid():
            context = request.session.get('All_Citations_Context')
            if ('which_citations') in getdict.keys():
                if 'all' in getdict.values():
                    text_template = 'email_allCitations.txt'
                    html_template = 'email_allCitations.html'

                    text_content = render_to_string(text_template, context, context_instance=RequestContext(request))
                    html_content = render_to_string(html_template, context, context_instance=RequestContext(request))

                    msg = EmailMultiAlternatives(subject, text_content, from_email, to)
                    #msg.attach()
                    msg.attach_alternative(html_content, "text/html")
                    msg.send()
                    submit_message = "Thank you. Your citations have been sent via email."

                    return http.HttpResponse(json.dumps({'submit_message': submit_message}))

                if 'selected' in getdict.values():
                   text_template = 'email_selectedCitations.txt'
                   html_template = 'email_selectedCitations.html'

                    text_content = render_to_string(text_template, context, context_instance=RequestContext(request))
                    html_content = render_to_string(html_template, context, context_instance=RequestContext(request))

                    msg = EmailMultiAlternatives(subject, text_content, from_email, to)

                    msg.attach_alternative(html_content, "text/html")
                    msg.send()
                    submit_message = "Your citations have been sent via email."

                    return http.HttpResponse(json.dumps({'submit_message': submit_message}))
            else:
                submit_message = "Something went wrong. Sorry, your email did not send."

        else:
            submit_message = form.errors['email_address']
    else:
        form = EmailCitationsForm()
        submit_message = ""
    return http.HttpResponse(json.dumps({'submit_message': submit_message}))
Community
  • 1
  • 1
steph
  • 701
  • 2
  • 10
  • 30
  • I just added the ajax code to my question... – steph Jan 08 '15 at 21:36
  • who do you think is ``$(this)`` in your js? – Mihai Zamfir Jan 08 '15 at 22:25
  • I'm note quite sure what you're getting at...$(this) contains the data in my request but my problem is that the button data (the 'name' info of the button) is not in there. The other form info (csrftoken and email_address) are there but the button data is not...? – steph Jan 08 '15 at 23:15
  • this is what I was saying: Inside the callback, this refers to the jqXHR object of the Ajax call, not the element the event handler was bound to. Try to print the button name in your JS – Mihai Zamfir Jan 09 '15 at 12:00
  • Thank you, Mihai. I've just started using JS and Ajax so I don't know what that means but I will read about is- at least I have a direction now! – steph Jan 09 '15 at 16:08

1 Answers1

1

Ok, this is more of an HTML/jQuery problem than a Django one.

First, your first form works because presumably you let the browser handle the submit. If you use a similar code to the one provided, it does not work.

If you log $(this).serialize() you get precisely what you get on the backend. Check out this answer jQuery: how to get which button was clicked upon form submission?

<form class="email_citations" id="EmailCitationsForm" action="email_it" method="get">

    <input class="input-text" type="text" size="75" maxlength="75" style="width: 40%; font-size: 16px; margin-right: 5px; height: 50px" name="email_address" placeholder="email address">
    <button type="submit" value="selected_citations" name="selected_citations" class="form_button button inline large hover" id="exportButton4" >Send My Selected Citations</button>
    <button type="submit" value="all_citations" name="all_citations" class="form_buttonbutton inline large hover" id="exportButton5">Send All Citations</button>

</form>

Notice I've removed the django bits.

$(document).ready(function(){
    console.log("hello from email.js");
    $('.email_citations').submit(function(event){
        console.log("submit email");
        var clicked_button = $(".form_button[clicked=true]")[0].name;
        console.log(clicked_button);
        var email_address = $(this).val();
        var data = $(this).serialize();
        data += "&" + clicked_button;
        console.log(data);
        $.ajax({
            data: $(this).serialize(),
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            success: function(data){
                $('.email_sent_message').html(JSON.parse(data).submit_message);
            }
        });
        return false;
    });
    $(".form_button").click(function() {
        $(".form_button").removeAttr("clicked");
        $(this).attr("clicked", "true");
    });
});

Or see in plunker http://plnkr.co/edit/CxPGmxQfeHhtsWiANDJ1

Community
  • 1
  • 1
elpaquete
  • 241
  • 2
  • 9
  • Thank you so much elpaquete! I'm still having an issue passing the data to my view function though. The button info is not in my request. When I print request.GET in my view, I only have: . However, I added `clicked_button.push($(".form_button[clicked=true]")[0].value);` to the JS and my request.GET now contains but I can't locate 'selected_citations' within that querydict. If 'all_citations' was clicked, though, I can locate it..? – steph Jan 09 '15 at 16:35
  • I found a work around: I gave both buttons the same name but different values. In my view, I search the dictionary values (either 'all_citations' or 'selected_citations'). This works- I can find 'all_citations' when that button was clicked and 'selected_citations' when that button was clicked. I don't know why my original way wasn't working but this does! Thank you! – steph Jan 09 '15 at 16:51
  • I'm sorry to bother again, but just one last thing...the emails now send correctly but my "submit_message" does not appear on the same page. When I submit the form, I am sent to a new page containing only {"submit_message": "Thank you for using AppCiter. Your citations have been sent via email."} rather than having the submit message appear on the same page. This was working before and I'm not sure how to fix it again...? @elpaquete – steph Jan 09 '15 at 17:34
  • Me neither. Are you returning a HttpResponseRedirect to the browser? – elpaquete Jan 12 '15 at 11:39
  • This issue was that `clicked_button.push($(".form_button[clicked=true]")[0].value);` was causing an error and so the Ajax function was never being executed! I had to change everything around- the fix is back in my question. Thank you for your help! – steph Jan 12 '15 at 16:19