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) {... });
Related
Required the form to be submitted via an ajax call and you will intercept the result and update your page. You never leave the index page.
I'm having trouble having the ajax call working
<form action="/cart" method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="{{id}}">
<input type="hidden" name="update" value="0">
</form>
var form = $('#addProduct');
form.submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/cart",
data: form,
dataType: "json",
success: function(e) {
window.location.href = "/";
}
});
})
you can use
JavaScript
new FormData(document.querySelector('form'))
form-serialize (https://code.google.com/archive/p/form-serialize/)
serialize(document.forms[0]);
jQuery
$("form").serializeArray()
You are changing the whole meaning of the ajax call. Ajax call is used for updating something without page refresh. In your case on success, you are changing the URL which is not right. Remove window.location.href = "/"; from your code and try to append messages or alert something like alert('Product is added to cart');
Your ajax call is not sending data to the server. Use formdata object or serialize() to get form input values then send it to the server.
Use
var form = new FormData($('#addProduct')[0]);
OR
var form = $("'#addProduct").serialize();
Instead of
var form = $('#addProduct');
And on success, send response from server and update your DOM in success function. Don't use window.location.href = "/";
To update your document after success you can use append(e) to update your DOM
<form method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="2">
<input type="hidden" name="update" value="0">
</form>
<div id="display">
</div>
$(function(){
$("#addProduct").submit(function(e){
e.preventDefault();
var quantity = $(this).children("input[name=quantity]").val();
var productid = $(this).children("input[name=productid]").val();
var update = $(this).children("input[name=update]").val();
$.ajax({
type:"post",
url:"/cart.php",
data:{update:update,quantity:quantity,productid:productid},
success: function(feedback){
$("#display").html(feedback);
},
error: function(err){
alert("error");
}
});
});
});
I update my answer and i use the div with id display to show my data return from ajax success
Html:
<form id="yourFormId" method="POST" action="/">
{{csrf_field()}}
<div id="check" class="input-group margin-bottom-sm">
<input class="form-control" type="text" name="find" placeholder="Search">
<button type="submit"><div id="search" class="input-group-addon"><i class="fa fa-search"></i></div></button>
</div>
</form>
JS:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + this.val() );
});
});
</script>
That script doesn't work. I need an ajax solution to pass dynamically my input text to action url. How to do that?
Try this:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + $(this).val() );
});
});
</script>
i think u want to submit your form with ajax request with dynamic text field value.
you can use simple java script function on change or click event whatever you want or with ajax request
you simple use like this
window.location.href="/"+$(this).val();
return false;
This code will submit your form on keyup (as soon as you stop typing)
var timerid;
jQuery("#yourFormId").keyup(function() {
var form = this;
clearTimeout(timerid);
timerid = setTimeout(function() { form.submit(); }, 500);
});
In this code you intercept the form submit and change it with an ajax submit
$('.form-control').bind('keyup', function() {
$("#yourFormId").submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: '/url/toSubmit/to',
data: $("#yourFormId").serialize(),,
success: function (response) {
//write here any code needed for handling success }
});
});
});
To use the delay function you should use jQuery 1.4. The parameter passed to delay is in milliseconds.
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 script which dynamically generates form elements with their corresponding ID, for e.g.
response from MySQL db says - 4, then
<form ID="form0">
<Input>....
<Button type="submit>....
</form>
<form ID="form1">
<Input>....
<Button type="submit>....
</form>
<form ID="form2">
<Input>....
<Button type="submit>....
</form>
<form ID="form3">
<Input>....
<Button type="submit>....
</form>
once this list of forms are generated, I have an AJAX code which detects the submit buttons and send the input values off to db via PHP page, something like this below,
$(document.body).on('submit', '#form' ,function(e){
e.preventDefault();
var postData = $("#form").serialize();
$.post("../../../functions/processing.php",postData,function(data, status){
var selectedData = JSON.parse(data);
$.each( selectedData, function( i, val ) {
// do something here...
});
});
});
So my question is that, for the list of forms, I have to somehow generate multiple of this AJAX code for form0, form1, form2, form3.. and because I can't anticipate how many forms will be generated, I can't just write one AJAX code like the one above.. is there anyway to dynamically generate AJAX codes for dynamically generated multiple forms?
Give the form a class that identifies it as a form to be handled by your AJAX handler. Then, inside the handler, reference this to get the form element that is being submitted.
<form ID="form0" class="js-ajax-form">
<input>....
<button type="submit>....
</form>
Handler
$(document).on('submit', '.js-ajax-form' ,function(e){
e.preventDefault();
var postData = $(this).serialize();
$.post("../../../functions/processing.php",postData,function(data, status){
var selectedData = JSON.parse(data);
$.each( selectedData, function( i, val ) {
// do something here...
});
});
});