Nik Nik - 3 months ago 10
Javascript Question

AJAX is not parsing Data and not using PATCH method

I am relatively new to Ajax, my problem is i am trying to submit the form as PATCH, and parse url, which is sent by Mustache {{add_member_url}}, i do not get any errors, and back end works, i have tried it. The server receives GET, although my form method="PATCH", and Ajax method="PATCH", there are two functions in Ajax first get - i render the form second is PATCH to submit the form.

JavaScript

$('.list').on('click', '#add', function(event){
event.preventDefault();
var url_send = $(this).data("add_url")
// $("#yourModal").modal({"backdrop": "static"});
$.get(''+$(this).data("add_url"), function(data){
console.log(this);
var template = $("#add_member_template").html();
console.log("T",template);
data.add_member_url = url_send;
console.log(data.add_member_url);
var rendered = Mustache.render(template, data);
console.log(rendered);
$('.contain').html(rendered);

});
});



$('.contain').on('submit', '#add_member', function(event){
event.preventDefault();

console.log('U',$(this).data("add_url"));
$.ajax({
url:''+$(this).data("add_url"),
method: 'PATCH',
data: $(this).serialize(),
success: function(data) {
console.log(method);

}
});


});
});


HTML Form

<div id="forma" class="contain" ></div>
<script id="add_member_template" type="mustache/template">

<form id="theForm" action="" method="PATCH">

{% csrf_token %}
{% verbatim %}

<p> {{pk}} </p>
<p><label for="ssn">SSN:</label>
<input id="ssn" type="text" name="tename" data-add_url="{{add_member_url}}" value="{{tename}}"></p>

<button id="add_member" data-add_url="{{add_member_url}}" type="submit" value="save" class="btn blue">Submit</button>



{% endverbatim %}
</form>

</script>

Answer

Your event binding is wrong. The submit event only occurs on forms, not on the submit button. You need to bind to the button's click event:

$(".contain").on("click", "#add_member", function(event) {... });