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?
Related
I have an HTML page that creates buttons from a list it gets from python code.
list = ['a','b','c','d'] it will build buttos names a b c d, 4 buttons.
And I added a script myFunction that on-click gives a pop up to put some clear text that I send to my python code.
It all works for all buttons on the list, except for the last button and I don't know why.
only for the last button created in the page won't show pop-up and decides that the user entered an empty response on the clear text.
code:
<form target="_blank" method="get" action="connect" style="display: inline;">
{% if thing['x'] %}
<button class="button button" onclick="myFunction(form);openNav()"> {{ thing['letters'] }} </button>
<input type="hidden" name="reason" id="myField" value=""/>
{% endif %}
</form>
function myFunction(frm) {
var txt;
console.log(frm.reason.value); // 1st option
console.log(event.srcElement.parentElement.nextElementSibling.outerHTML) // 2nd option
var reason = prompt("Please enter reason:");
if (reason == null || reason == "") {
txt = "CANCEL";
} else {
txt = reason;
}
frm.reason.value = txt; // 1st option
console.log(event.srcElement.parentElement.nextElementSibling.value == txt); // 2nd option
return txt
}
Error i see in F12:
Authentication:271 Uncaught TypeError: Cannot read property 'outerHTML' of null
at myFunction (Authentication:271)
at HTMLButtonElement.onclick (Authentication:230)
I see it gives red X on this line :
console.log(event.srcElement.parentElement.nextElementSibling.outerHTML) // 2nd option
Solution was to delete the consol log. this was what dropped everything for the last button.
console.log(event.srcElement.parentElement.nextElementSibling.outerHTML) // 2nd option
As it got NULL response.
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
I need to upload user's image to server for django(1.8) to process it.
I'm sure the client only submits the form only once. Howerver, the backend executed the related view function many times and return 504 when I submitted a little large image(about 2M).
Here is my html:
<form action="/test/" method="POST" id="upload_form" enctype="multipart/form-data">
{% csrf_token %}
<a href="javascript:void(0);" class="addPic">
<input id="choose_btn" class="btn" name="user_image" type="file"></a>
</form>
<button type="button" id="upload_btn" class="btn btn-danger " data-loading-text="uploading..." autocomplete="off"> Upload!</button>
Here is my js(insure there is only one submit , inspired from https://stackoverflow.com/a/4473801/1902843):
$('#upload_btn').click( function () {
var $btn = $(this).button('loading');
$('#upload_form').submit(function(e){
console.log("start submit");
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
console.log("has submitted!");
e.preventDefault();
} else {
console.log("first submitted");
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
$('#upload_form').submit();
});
and my back-end view function is:
model
class UserImage(models.Model):
image = models.ImageField(upload_to='./user_image/%Y%m/%d', storage=ImageStorage(), blank=False)
detect_result = models.TextField(max_length=1000, blank=True)
view
#csrf_exempt
def test(request):
# if use form's is_valid() function, it always return false.
# very weird, thus i annotate it
# if request.method == 'POST':
# form = UploadFileForm(request.POST, request.FILES)
# if form.is_valid():
user_image = request.FILES['user_image']
im = UserImage(image=user_image)
im.save() #after looking for log, it saved many times depending on image size?
img_path = settings.MEDIA_URL + str(im.image)
...
processing image
...
return render_to_response('open.html', result_data)
I would personally start by placing your submit button within the form.
<form action="/test/" method="POST" id="upload_form" enctype="multipart/form-data">
{% csrf_token %}
<a href="javascript:void(0);" class="addPic">
<input id="choose_btn" class="btn" name="user_image" type="file"></a>
<button type="button" id="upload_btn" class="btn btn-danger " data-loading-text="uploading..." autocomplete="off"> Upload!</button>
</form>
And then use an event listener on the #upload_btn instead of triggering a click. Also, only call $('#upload_form').submit() once
$('#upload_btn').on('click', function (e) { // Attach a click event listener
// Check the form, display loading icon, etc
// and when ready to submit the form ...
$('#upload_form').submit();
});
i have a custom gateway (which works perfectly), the problem is when a customer buys something for the first time, there is some token than needs to be generated with the card info, the thing is that just before that token is generated, the form tries to submit, but an error is displayed saying that "the object could not be found", so, no refresh and nothing, if i press again the submit button (or "place order" button) everything works!.
i believe that by that second time, the token is generated and in the corresponding hidden field:
here is my code, hope somebody could help me :S
HTML (from the chrome inspector):
<input type="hidden" name="card-name" data-conekta="card[name]">
<input type="hidden" name="exp-month" data-conekta="card[exp_month]">
<input type="hidden" name="exp-year" data-conekta="card[exp_year]">
<input type="hidden" name="conektaTokenId" value="">
<input type="hidden" name="conektaCustId" value="false">
Javascript
jQuery(window).load(function() {
var form;
var first_name;
var last_name;
var cvc;
jQuery('form[name="checkout"]').submit(function(event) {
jQueryform = jQuery(this);
Conekta.setPublishableKey(jQuery('input[name="pbkey"]').val());
console.log('entro');
if( jQuery('input[name="conektaCustId"]').val()=="true" && jQuery('input[name="conektaTokenId"]').val().substr(0,4)!="tok_"){
console.log('entro');
first_name = jQuery('#billing_first_name').val();
last_name = ' ' + jQuery('#billing_last_name').val();
expiry = jQuery('#conekta_card-card-expiry').val().replace(/ /g, '').split("/");
jQuery('input[name="card-name"]').val( first_name + last_name );
jQuery('input[name="exp-month"]').val( Number(expiry[0]));
jQuery('input[name="exp-year"]').val( Number(expiry[1]));
jQueryform.prepend('<span class="card-errors"></span>');
Conekta.token.create(jQueryform, conektaSuccessResponseHandler, conektaErrorResponseHandler);
woocommerce_order_button_html
return false;
}
else{
return;
}
});
var conektaSuccessResponseHandler= function(response){
var token_id = response.id;
jQuery('input[name="conektaTokenId"]').val(token_id);
}
var conektaErrorResponseHandler= function(response){
jQueryform.find('.card-errors').text(response.message);
}
});
i have found the solution, you have to add the class processing to the checkout form and just when you finished procesing your data to be send to wherever you need to (usually wordpress/woocommerce), remove that class so the form can submit the new data.
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.