I have difficulty submitting this form:
<form action="/someurl" method="post">
<input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5">
<input type="checkbox" class="mychoice" name="name" value="apple"> Apple
<input type="checkbox" class="mychoice" name="name" value="orange"> Orange
<input type="checkbox" class="mychoice" name="name" value="pear"> Pear
</form>
And the jquery bit:
$('.mychoice').click( function() {
$.ajax({
url: '/someurl',
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
But nothing happens when I click a checkbox. How can I fix this?
UPDATE: It may worth mentioning that the form is located at a bootstrap modal.
You're missing the data property.
See: JQuery $.ajax() post - data in a java servlet for an example.
If you want to send the contents of the form, then you would use Form.serialize(), but you could put whatever data you want into the property.
$(document).ready(function() {
$('.mychoice').click(function() {
var formData = $('#myForm').serialize();
console.log('Posting the following: ', formData);
$.ajax({
url: '/someurl',
data: formData,
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/someurl" method="post" id="myForm">
<input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5">
<input type="checkbox" class="mychoice" name="name" value="apple">Apple
<input type="checkbox" class="mychoice" name="name" value="orange">Orange
<input type="checkbox" class="mychoice" name="name" value="pear">Pear
</form>
Try this:
$(document).ready(function(){
$('.mychoice').change( function() {
$.ajax({
url: '/someurl',
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
supply missing data
$(document).ready(function() {
$('.mychoice').click(function() {
$.ajax({
url: '/someurl',
data: $(this).closest('form').serialize(),
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
if you are trying to receive the data with the csrf token do as below :
var fd = new FormData()
fd.append('csrfmiddlewaretoken', document.getElementsByName('csrfmiddlewaretoken')[0].value)
fd.append('field_name', $("input[name='field_name']").serialize())
will return
['field_name=9&field_name=15&field_name=10']
you will then have to parse the info in your view ( django )
Try 'change' instead of 'click', like this:
$('.mychoice').change(function(){...})
Related
I have several forms in my html view (they displayed by php foreach).
Form example:
<form method="POST" class="like-form-js">
<input type="hidden" name="post_id" value="<?= $post['id'] ?>">
<input type="hidden" name="user_id" value=<?= CoreController::findIndentityId(); ?>">
<i class="far fa-thumbs-up color-grey c-pointer submit-like"></i>
</form>
I have many such forms in my view. My js:
$('.submit-like').click( function() {
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('.like-form-js').serialize(),
success: function(data) {
console.log('success');
}
});
});
I need to submit only one form on which i clicked, but this forms have similar class and they are all submiting. How to solve this?
You have to specify which form to be submitted
Try this,
$('.submit-like').click(function(){
$(this).parent().submit()
})
$('like-form-js').submit(function(e){
e.preventDefault();
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
console.log('success');
}
});
})
How I to for send an image and form with a request ajax?
HTML
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
</form>
<button id="btnSave">Save</button>
JQuery - AJAX
$("#btnSave").click(function()
{
var Url = 'http://localhost/systemm/public/painel/client';
var Dados = $('#FormClient').serialize();
$.ajax({
type:Type,
url: Url,
dataType: 'JSON',
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
});
When I serialize the data and put in an alert to display I see that the image is not there, how do I send the image along with my form to my server/controller?
Use formData object:
HTML
<form enctype="multipart/form-data">
<input type="text" class="form-control" id="Name" name="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button id="btnSave">Save</button>
</form>
JS
$("#btnSave").click(function() {
var Url = 'http://localhost/systemm/public/painel/client';
var formData = new FormData(this.form);
$.ajax({
type:'post',
url: Url,
dataType: 'JSON',
data: formData,
...
});
});
Let's try following,
<form id="POST_FORM" method="post" enctype="multipart/form-data" >
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button type="submit" id="btnSave">Save</button>
</form>
$("#POST_FORM").submit(function(){
var data = new FormData(this);
addPOST(data);
return false;
});
function addPOST(formData){
$.ajax({
type:'POST',
url: Url,
data:formData,
dataType:"json",
cache:false,
contentType: false,
processData: false,
success:function(response){
},
error: function(data){
console.log("error");
console.log(data);
}
});
}
Try to change content dataType. Set dataType='false'
$.ajax({
type:Type,
url: Url,
dataType: false,
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
Hope this helps
This is the way i have done it.
var obj = document.getElementById('my_form_id')
var data = new FormData(obj);
$.ajax({
type: 'post',
url: $(obj).parent().attr('action'),
processData: false,
contentType: false,
data: data,
success: function(result){
profile_app.user.foto_url = result.url
},
error: function(error){
console.log("error");
}
});
The code works on until I reach the action.php where I post my input. The issue is that the Post never reaches the action.php and all I get is a blank variable.
using: https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('name');
$.ajax({
type: 'post',
url: 'action.php',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
return false;
}
</script>
<form onsubmit="return submitdata();">
<input type="text" name="name">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
action.php:
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>
EDIT:
Fixed it by adding:
var name=document.getElementById('name').value;
and
input type="text" id="name" instead of name="name"
Your "name" is DOM object. To get value use:
var name=document.getElementById('name').value;
You now submit not a string, but Object and this may be the reason why it fails.
Try to add the dataType on your ajax request
make it 'text'
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
I was planning to use FormData as below
var formData = new FormData($(this)[0]);
but figured out that it does not work in IE<10 and which is not accepted. Is there any other approach for same?
This block should work for you.
$.ajax({
url: 'url',
type: 'POST',
async: true,
dataType: "json",
data: $('#data').serializeArray(),
error: function (a, b, c) { onError(a, b, c, parameters); },
success: function (data) { onSuccess(data, parameters); }
});
You can do like this in php instead of using form data,
Serialize you form data and send through ajax, like,
$.ajax({
type: 'post',
url: 'post.php',
data: $('#form').serialize(),
success: function () {
}
});
});
using $('#form').serialize() you can send your all form data to php.
I hope it helps,
function savedata(){
var vacancy_desc = CKEDITOR.instances['vacancy_desc'].getData();
var file_data = $('#fileupload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('vacancy_records',vacancy_records);
form_data.append('vacancy_desc',vacancy_desc);
$.ajax({
url:pathname,
method:"POST",
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data:form_data,
cache:false,
success:function(datas){
alert('Updated successfully !');
return false;
}
});
}
Currently using this:
function acceptimage() {
var data = new FormData();
jQuery.each($('#uploadImage')[0].files, function(i, file) {
data.append('uploadImage-'+i, file);
});
$.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
popup('popUpDiv');
ias.cancelSelection();
ias.update();
}
});
};
And it's sending my file perfectly, but I need to send 4 field values along with it. Could anyone let me know how I post:
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
Along with the file? Many thanks
function acceptimage() {
var data = new FormData();
jQuery.each($('#uploadImage')[0].files, function(i, file) {
data.append('uploadImage-'+i, file);
data.append('x', $("#x").val());
data.append('y', $("#y").val());
data.append('w', $("#w").val());
data.append('h', $("#h").val());
});
$.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
popup('popUpDiv');
ias.cancelSelection();
ias.update();
}
});
};