How exactly do I upload a file using an ajax call ?
My form in template
<form action="images/" enctype="multipart/form-data" method="POST" class="upload">
<table>
{{ form.as_table }}
<td><input type = "button" onclick="" value="Upload" id = "test"/</td>
</table>
</form>
My jQuery function :
$(document).ready(function(){
$("#test").click(function(){
var string = $("form.upload").serialize();
alert(string);
$.ajax({
url :'/test/',
type:'post',
data: {datas:string},
dataType: "json",
success: function(response) {
alert(response);
}
});
});
});
My view :
#csrf_exempt
def test(request):
if request.is_ajax():
form = ImageUploadForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("Saved !!!!")
Here I have the view for the file upload but the file does not appear in the form variable in the django view . What should I do to get the file in the view ?
The form has a filefield for uploading . It is a model form.
2 important pieces are missing here:
jQuery.serialize() doesn't do anything to file fields. Check out jQuery form plugin for a robust method of posting form with files via Ajax
You need to explicitly pass the uploaded files to the form constructor: form = ImageUploadForm(data=request.POST, files=request.FILES)
Related
I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.
I want to implement a send mail form using Thymeleaf.
I have a page called start_page.html that contains this form :
<div class="w3-container w3-padding-64" id="contact">
<h1>Contact</h1><br>
<p>We offer full-service catering for any event, large or small. We understand your needs and we will cater the food to satisfy the biggerst criteria of them all, both look and taste. Do not hesitate to contact us.</p>
<p class="w3-text-blue-grey w3-large"><b>Catering Service, 42nd Living St, 43043 New York, NY</b></p>
<p>You can also contact us by phone 00553123-2323 or email catering#catering.com, or you can send us a message here:</p>
<form th:action="#{~/homePage/contact}" th:object="${contactMail}" method="post" target="_blank">
<p><input class="w3-input w3-padding-16" type="text" th:field="*{nom}" th:placeholder="#{homePage.nom}" required name="nom"></p>
<p><input class="w3-input w3-padding-16" type="text" th:field="*{prenom}" th:placeholder="#{homePage.prenom}" required name="prenom"></p>
<p><textarea class="w3-input w3-padding-16" type="text" th:field="*{message}" style="height: 250px;" th:placeholder="#{homePage.message}" required name="message"></textarea>
<p><button class="w3-button w3-light-grey w3-section" type="submit">[[#{homePage.envoyer}]]</button></p>
</form>
</div>
I have already implemented a controller for this form action
#Controller
#PropertySource(ignoreResourceNotFound = true , value = "classpath:messages.properties")
public class HomePageController {
#Autowired
private MailContactService mailService;
#RequestMapping(value = "/homePage/contact", method = RequestMethod.POST)
public String sendMessage(ContactMail contactMail){
mailService.sendContactMail(contactMail);
System.out.println("done");
return "/home/start_page";
}
}
I'm not getting the desired behavior: I though that my page will stay the same but my page is reloading.
I want to order the controller to do something without getting out of my page.
I googled and I found that I can send a service object to my page but I want to avoid this option if there is other solutions .
Thank you.
You'll need to use an AJAX call if you don't want to refresh your page.
What this means is that you want to intercept the default HTTP form post behavior (that will do a full page refresh) using javascript.
For this you need to :
Remove the action tag on your form (let javascript handle it when clicking the button to submit the form)
Add this to your page (will be executed when the form is submitted :
$(document).ready(function () {
$("#contact-form").submit(function (event) {
// do not post the form and trigger full page refresh
event.preventDefault();
var formData = .. // construct some formData
$.ajax({
type: "POST",
contentType: "application/json",
url: "/homePage/contact",
data: JSON.stringify(formData),
dataType: "json",
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
For a full example, as always, mkyong.com has got you covered :)
I have a very long form that contains files attachment:
this is how my form looks like:
The form will be submitted to this action:
[HttpPost]
public ActionResult AddReceivingConfirm(DTOreceiving entry,IEnumerable<HttpPostedFileBase> fileUpload)
{
return PartialView();
}
through ajax call which is:
$(document).on('click', 'input[type="submit"].genericSubmit', function () { //generic function for ajax submit of ANY FORMS t
if (!$("form#ValidateForm").valid()) {
return false;
};
var frmData = $('.genericForm').serialize();
var frmUrl = $('.genericForm').attr('action');
$.ajax({
type: 'post',
url: frmUrl,
data: frmData,
success: function (e) {
$('#target').html(e);
}
});
return false;
});
everything is binding perfectly except the IEnumerable<HttpPostedFileBase>which always results to null,
the file part of my form is done like this:
<tr>
<td>Attachment #1: </td>
<td colspan="3">
<input id="file1" type="file" name="fileUpload" />
</td>
</tr>
<tr>
<td>Attachment #2: </td>
<td colspan="3">
<input id="file2" type="file" name="fileUpload" />
</td>
</tr>
<tr>
<td>Attachment #3: </td>
<td colspan="3">
<input id="file3 "type="file" name="fileUpload" />
</td>
</tr>
I have tried the brackets version and etc but it won't bind.
After an hour of researching, i've read that it's not possible(?) )to do file posting conventionally through the use of Ajax unless iframe. I am not sure of what my action will be, i kinda want to avoid using plugin so i wanna know if there is some "hacky" ways to access the files directly from my form?
this is my form:
using (Html.BeginForm("AddReceivingConfirm", "Wms", FormMethod.Post, new { id = "ValidateForm", #class = "genericForm" , enctype="multipart/form-data"}))
Unfortunately the jQuery serialize() method will not include input file elements. So your files are not going to be included in the serialized value.
What you should be doing is creating a FormData object, append the files to that. You need to append the form field values as well to this same FormData object. You may simply loop through all the input field and add it. Also, in the ajax call, you need to specify processData and contentType property values to false.
$(document).on('click', 'input[type="submit"].genericSubmit', function(e) {
e.preventDefault(); // prevent the default submit behavior.
var fdata = new FormData();
$('input[name="fileUpload"]').each(function(a, b) {
var fileInput = $('input[name="fileUpload"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("fileUpload", file);
}
});
// You can update the jquery selector to use a css class if you want
$("input[type='text'").each(function(x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
var frmUrl = $('.genericForm').attr('action');
$.ajax({
type: 'post',
url: frmUrl,
data: fdata,
processData: false,
contentType: false,
success: function(e) {
$('#target').html(e);
}
});
});
Seems like your $.ajax needs contentType: false to prevent a bad content-type header from being inserted.
Also, if I am reading the docs ( https://api.jquery.com/serialize/ ) correctly .serialize skips file inputs...
This answer also seems helpful How can I upload files asynchronously?
I am using MVC3, Razor, C#, JQuery and AJAX.
I am using an Ajax call to postback a form to the server. I get all the form element values being passed back to the controller in:
[HttpPost]
public ActionResult Edit(Product myProduct, string actionType)
if (actionType == "Save")
save....
And in the View I have:
#using (Html.BeginForm("Edit", "RA", FormMethod.Post, new { #class = "editForm", #id = "frmEdit" }))
Form Elements:
<td>
#Html.HiddenFor(p=>p.Id)
<button type="submit" name="actionType" value="Save" >Save</button>
</td>
<td>#Html.EditFor(p=>p.Name)</td>
Some Ajax:
$('.editForm').on('submit', function () {
$.ajax({
url: this.action,
type: this.method,
data: $('#frmEdit').serialize(),
context: $('button', this).closest('tr'),
success: function (result) {
$(this).html(result);
}
});
return false;
});
Now I think the problem line is since I have seen quite a few posts about problem with JQuery and submitting button values:
data: $('#frmEdit').serialize(),
But I cannot get the button to submit an actionType of "Save". I just get null.
Thoughts greatly appreciated.
Thanks.
UPDATE:
My code seems to interfere with my JQuery listener ?? My code is:
<input type="submit" id="btn" name="btn" value="Save" onclick="document.getElementById('actionType').value = 'Save';"/>
From the documentation:
No submit button value is serialized since the form was not submitted using a button.
However you can add it by hand:
data: $('#frmEdit').serialize() + '&actionType=Save',
or
data: $('#frmEdit').serialize()
+ '&'
+ encodeURIComponent(button.name)
+ '='
+ encodeURIComponent(button.value),
where button is the <button> DOM element.
I don`t speak english well? but i have problem in Django.
I have models:
class Model1(models.Model):
model2 = models.ManyToManyField(Model2)
#...
class Model2(models.Model):
model3 = models.ForeignKey(Model3)
#...
class Model3(models.Model):
custom = models.CharField()
have view
def simple(request, simple_id):
if request.method == 'POST':
if request.is_ajax():
if 'delete' in request.POST:
id3 = request.POST.get('delete', '')
Model1.objects.get(id = simple_id).model2.filter(model3__id = id3).delete()
That is, when submitting a form with name = "delete" Ajax have removed all the objects belonging to Model2 with the same value of the field "model3"
Here's a piece of template:
<form action="" method="post" id="simple">{% csrf_token %}
<input type="submit" name="delete" id="simple_delete" value="">
</form>
the value passed from js:
$('.deletebutton').click(function(){
id = $(this).attr('data-id');
$('#simple_delete').attr('value', id);
$('#simple').ajaxForm();
$('#simple_delete').click();
});
Well, respectively plugin jquery.form.js also connected
The problem is this - if submission without ajax all is normal, it works ... and if with Ajax is an error such as incorrect int value ... How to make it work via Ajax?
try this
$('.deletebutton').click(function(){
id = $(this).attr('data-id');
$.ajax(function(){
type:"POST",
url :"/your_url/",
data:{
'id'=id,
}
}).done(function(result){
alert('your json object result render by view :'+result)
})
i think it work,
and i didnt get wat you are doing in i.e $('#simple_delete').click();
can you please describe about that
in view
obj = Model1.objects.get(id = simple_id)
model2.objects.filter(model3__id = id3).delete()
i just split single line query into two lines and if not working
use .select_related()