0

I am trying to get a string data that is send from Ajax to Python. However, as I log the code, the data isn't sent. It's empty. Could you tell me why?

p.s. the purpose of the code is to get the name of the submit button to validate in views.py

javascript

<script type='text/javascript'>
$(".submit-btn").click(function(){
  var button_pressed = JSON.stringify($(this).attr('name'));
  $.ajax({
    url: "{% url 'add_test' %}",
    type: 'POST',
    data: {'button_pressed' : button_pressed, 'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val()},
  })
});
</script>

views.py

def add_test(request):
    if request.method == 'POST':
        test_name = request.POST.get('test_name')
        test_type = request.POST.get('test_type')
        test_date = request.POST.get('test_date')
        test_obj = Test(test_name = test_name, test_type = test_type, test_date = test_date)
        test_obj.save()
        button_pressed = request.POST.get('button_pressed')
        #button_pressed = json.loads(button_pressed)        
        print button_pressed ,"+++++++++++++++++++++++++++++"
        return HttpResponseRedirect('/test-management/test/')

test_list.html

<form class="form" method="POST" action="{% url 'add_test' %}">
                        {% csrf_token %}
                        <h2>Add Test</h2>
                        <div class="card-body">
                            <div class="form-group bmd-form-group">
                                <div class="input-group">
                                    <p>Name :</p>
                                    <input type="text" class="form-control" id="test_name" name="test_name" placeholder="Test Name...">
                                </div>
                            </div>
                            <div class="form-group bmd-form-group">
                              <div class="input-group">
                                  <p>Type :</p>
                                  <input type="text" class="form-control" id="test_type" name="test_type" placeholder="Test Type...">
                              </div>
                            </div>
                            <div class="form-group bmd-form-group">
                                <div class="input-group">
                                    <p>Date :</p>
                                    <input type="date" class="form-control" id="test_date" name="test_date" placeholder="Test Date...">
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer justify-content-right">
                            <button type="submit" class="btn btn-primary btn-link btn-wd btn-lg" data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary btn-link btn-wd btn-lg submit-btn" name="add_new">Add & New</button>
                            <button type="submit" class="btn btn-primary submit-btn" name="add">Add</button>
                        </div>
</form>

I am new to Django, so sorry if the question is silly. Thank for helping!

5
  • your button_passed not passed by ajax? Commented Jun 27, 2018 at 7:30
  • @sueling yes, value of button_passed isn't passed. Commented Jun 27, 2018 at 7:32
  • 1
    can you make a console.log of this? var button_pressed = JSON.stringify($(this).attr('name')); Commented Jun 27, 2018 at 7:38
  • please check your script work like @JorgePeris said Commented Jun 27, 2018 at 7:38
  • @JorgePeris i console.log it and get the value. it works to that point. Commented Jun 27, 2018 at 7:44

3 Answers 3

1

Change the type submit button:-

<button type="submit" class="btn btn-primary submit-btn" name="add">Add</button>

to

<button type="button" class="btn btn-primary submit-btn" name="add">Add</button>

Sign up to request clarification or add additional context in comments.

2 Comments

I finally decide to change my logic and follow your suggestion. I changed the button type from 'submit' to 'button'.
when you performing click event on a button, type button is perfect choice. In case of submit it perform on your form submit, not in your ajax. If type submit is very necessary then go for preventDefault option as mention in another answer.
0

I guess your form is sended with your submit button. It send your form data, not ajax data.

Just send ajax with other button or add preventDefault()

<script type='text/javascript'>
$(".submit-btn").click(function(e){
  e.preventDefault();
  var button_pressed = JSON.stringify($(this).attr('name'));
  $.ajax({
    url: "{% url 'add_test' %}",
    type: 'POST',
    data: {'button_pressed' : button_pressed, 'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val()},
  })
});
</script>

Also, you have to change your view if you want to receive your form data

Comments

0

I've found out that we can't get the name of the submit button if it's of type 'submit'. So, I made the type to 'button'. There are quite a few modification that I do to make the code work, but it all works fine now.

javascript

<script type='text/javascript'>
$(".submit-btn").click(function(){
  var test_name = JSON.stringify($("#test_name").val());
  var test_type = JSON.stringify($("#test_type").val());
  var test_date = JSON.stringify($("#test_date").val());
  var button_pressed = JSON.stringify($(this).attr('name'));
  $.ajax({
    url: "{% url 'add_test' %}",
    type: 'POST',
    data: {'button_pressed' : button_pressed, 'test_name' : test_name, 'test_type' : test_type,
    'test_date' : test_date,'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val()},
  })
  var button_pr = $(this).attr('name');
  if (button_pr == 'add_new'){
    $("#test_name").val("");
    $("#test_type").val("");
    $("#test_date").val("");
  } else {
    $(".cancel-btn").click();
  }
});
</script>

views.py

def add_test(request):
    if request.method == 'POST':
        test_name = json.loads(request.POST.get('test_name'))
        test_type = json.loads(request.POST.get('test_type'))
        test_date = json.loads(request.POST.get('test_date'))
        test_date = datetime.strptime(test_date, '%Y-%m-%d').date()
        test_obj = Test(test_name = test_name, test_type = test_type, test_date = test_date)
        test_obj.save()
        return HttpResponseRedirect('/test-management/test/')

test_list.html

<form class="form" method="POST" action="{% url 'add_test' %}">
                        {% csrf_token %}
                        <h2>Add Test</h2>
                        <div class="card-body">
                            <div class="form-group bmd-form-group">
                                <div class="input-group">
                                    <p>Name :</p>
                                    <input type="text" class="form-control" id="test_name" name="test_name" placeholder="Test Name...">
                                </div>
                            </div>
                            <div class="form-group bmd-form-group">
                              <div class="input-group">
                                  <p>Type :</p>
                                  <input type="text" class="form-control" id="test_type" name="test_type" placeholder="Test Type...">
                              </div>
                            </div>
                            <div class="form-group bmd-form-group">
                                <div class="input-group">
                                    <p>Date :</p>
                                    <input type="date" class="form-control" id="test_date" name="test_date" placeholder="Test Date...">
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer justify-content-right">
                            <button type="button" class="btn btn-primary btn-link btn-wd btn-lg cancel-btn" data-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary btn-link btn-wd btn-lg submit-btn" name="add_new">Add & New</button>
                            <button type="button" class="btn btn-primary submit-btn" name="add">Add</button>
                        </div>
                    </form>

Basically, I write java script code to get value of form fields, send them to 'add_test' as Ajax. To get name of the button I clicked, I cannot use button of type 'submit'. Thank you

Comments

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.