I've a problem trying to submit a formset through Ajax. A little informaton of what I'm doing is that the user enters a word and through Ajax I get the length of of it and produce a formset according to that number. I then print it out with a for loop and each form has a valid button that its suppose to submit that specific format to validate it. So its a single form submit for each button. Here is my code:
<div id="example1" type="hidden">
{{ exampleForm.management_form }}
{% for form in exampleForm %}
<form onsubmit="return false;" method="GET" id="{{ form.prefix }}" >
( {{ form.letterOfWord }} + {{ form.keyToUse }} ) MOD 26 =
{{ form.letterToFill }} <button name="action" id="validateButton" value="validate"> Validate </button> <br>
</form>
{% endfor %}
And my javascript file:
$("#validateButton").on({
click : function() {
// var variable = document.getElementById('id_plaintext');
// console.log(variable.value)
console.log("Inside validate button function")
var serializedData = $('form').serialize();
console.log(serializeData);
$.ajax( {
url: "/exampleCaesar",
type : "GET",
data: { CSRF: 'csrf_token',
serializedData
},
success : function(exampleData) {
console.log(exampleData)
}
}); //END OF Ajax
} //END OF FUNCTION
}); //END OF validateButton
Thing is that when I click any of the validate buttons, nothing is submitted. I know this because I got a console.log in the javascript to know when it goes in. If that doesnt print out then it didn't actually go in.
Any tips? Been breaking my head all day for this. Thanks
you have multiple IDs validateButton. This might be source of your problems. As far as I know, or would guess, jquery will only trigger on the first button of the first form in this case.
Also, I'm not sure if jquery will serialize proper form when you use this code
var serializedData = $('form').serialize();
as again, you have multiple form in your html
Also, the managment_form should be inside of <form>, otherwise it won't get sent to Django. Check out the docs https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#using-a-formset-in-views-and-templates
Related
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 backend 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>
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) {... });
I have an issue where my form submits even though I've not told it to (in Javascript). I have an event handler for the form button, which checks if the input is a valid integer above 0, and works upon that. The problem is that even if it finds this to be false, the form still submits.
Here is my form code:
<form id="case_form" method="post" action="/dms/create/">
{% csrf_token %}
<h3>Case ID</h3>
<input name="caseID" id="caseNum" type="text" class="form-control" placeholder="ID of Case to create" required
autofocus><br/>
<button class="btn btn-lg btn-primary btn-block" id="submitButton">Create Case</button>
</form>
And my Javascript event handler.
$('#submitButton').click(function () {
numVal = $("#caseNum").val();
if (Math.floor(numVal) == numVal && $.isNumeric(numVal) && numVal > 0){
$("#case_form").submit();
}else{
$("#errorDisplay").show();
//Code gets here but still submits once leaving function
}
});
This is my first Answer :D
Try this.
<form onsubmit="return fnValidate()" ...> ... </form>
Javascript:
function fnValidate(){
var numVal = $("#caseNum").val();
if (Math.floor(numVal) == numVal && $.isNumeric(numVal) && numVal > 0){
return true;
}else{
$("#errorDisplay").show();
return false;
}
}
When fnValidate returns True your form will be submited. when function returns false this won't be submited.
Good Luck !
Solved it...
Apologies for submitting this question, I was trying to figure it out for ages, then Sod's law - as soon as I submit the question I have a "oh, that's so obvious" moment.
I forgot to put...
type=button
...in the button HTML.
this was happening to me, I realized I had to put my commented code in these Django comment tags for them to stop firing: {% comment %} comments here {% endcomment %}.
When I submit a form with invalid two form data I need to click twice the submit button to display javascript alert. Then after inputting valid data I need to click twice to make not to display javascript alert
$(document).ready(function () {
$('.dateinput').datepicker();
$("#daterangeresult").click(function(){
var start_date = "{{ form.data.start_date }}";
var end_date = "{{ form.data.end_date }}";
if (Date.parse(start_date) >= Date.parse(end_date)) {
alert("Enter start date less than end date");
}
});
});
My html file is
<form action="" method="POST"> {% csrf_token %}
Start Date: {{ form.start_date }} End Date:{{ form.end_date }}<br/>
<input type = "submit" value = "See Results" id = "daterangeresult"></form>
what is problem here?
Building a site so users can add topics onto a site and ask then Q&A. Using AJAX, the "Add Media" button on the home page loads my Add Media Form (text and an image) to the site. The box is rendering fine with the correct forms, but after hitting Submit the form doesn't save in the database. When just rendering the form onto a new HTML page without jquery, the model works just fine and the input is saved. How do I get the information submitted in a jquery lightbox to be saved in the database too?
So this is the html page
#home.html
Add Media
<div id="login-box" class="addmovie-popup">
This is the jquery that goes with it
#home.js
$(document).ready(function() {
$('.block3 a').click(function(ev) {
ev.preventDefault();
var url = $(this).attr('href');
$('#login-box').load('http://127.0.0.1:8000/home/add_movie/');
});
});
The URL conf
#urls.py
url(r'^add_media/$', 'add_media'),
The view for adding media
#views.py
def add_media(request):
if request.method == "POST":
form = MediaForm(request.POST, request.FILES)
if form.is_valid():
form.save(user = request.user)
return HttpResponseRedirect("/home//")
else:
form = MediaForm()
return render_to_response("qanda/add_media.html", {'form': form}, context_instance = RequestContext(request))
And the HTML form that it is rendering
#add_media.html
<h1> Add Media:</h1>
<form enctype = "multipart/form-data" action = "" method = "post">{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value = "Add" />
<input type = "hidden" name = "next" value = "{{ next|escape }}" />
</form>
If you're loading HTML into your page dynamically action = "" would point to the current page, which clearly doesn't handle your POST requests.
Set the action to the correct URL.
I've got a list of 10-20 objects on each page creating these forms:
<div id="routeTable">
{% for route in route_list %}
<div id="routeDone">
<form class="doneForm" action="/route/complete/" method="post">
<input type="hidden" name="route_id" value="{{ route.route_id }}" />
<input type="hidden" name="next" value="{{ request.get_full_path }}" />
<input type="submit" value="Done" class="doneButton" />
</form>
</div>
{% endfor %}
</div>
And I'm trying to add some jquery to the page in order to intercept the usual form submit and instead do so using ajax as below. (I already have a view that returns an html chunk which will be swapped out for the above div#routeTable. The problem is line 4 "var route_ID...":
<script>
$(document).ready(function() {
$(".doneForm").submit(function() {
var route_id = $(this).attr('input[name=route_id]').val()
$.ajax({
type: "post",
url: "/route/complete/",
data: route_id,
success: function(data) {
$("#routeTable").html(data);
}
});
return false;
});
});
</script>
Unfortunately I'm having trouble passing the proper route_id into the js variable named route_id. I expect it will require use of the 'this' keyword, but I haven't been able to figure out exactly how.
Any suggestions on how to fix up my javascript would be greatly appreciated.
Try to change
var route_id = $(this).attr('input[name=route_id]').val()
to
var route_id = $(this).find('input[name=route_id]').val()
The reason being that input[name=route_id] is not an attribute, but a selector that represent a tag input and an attribute on that tag [name=route_id].
You could also do
var route_id = $('input[name=route_id]',this).val()
var route_id = $(this).attr('input[name=route_id]').val()
Should be something like:
var route_id = $(this).find('input[name=route_id]').val()