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;
}
});
}
Related
I need to pass two different datas using ajax.
I've got this:
$('#sendcover').on('click',function(){
$.ajax({
type: "POST",
url: "{{ url('articles_changecover') }}",
data: new FormData($('#test')[0]),
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
});
<form name="test" id="test" method="post" enctype="multipart/form-data">
<input type="text" value="{{article.id}}" name="id" />
<input type="file" name="cover">
<button id="sendcover" type="submit" class="saveData">Save</button>
</form>
I need to pass two var's with data:
id and cover
id - sends {{article.id}}
cover - sends image
(and on the backend side it's uploading img and converting it - but it's already done by someone else)
Could somebody help me how to do it properly? I've never did such thing, and I can't find any working answer. :(
You could send it as an splitted up object like
data: {
myId: id,
myCover: cover
}
but currently you send the whole form that actually should look like
$('form#test').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "{{ url('articles_changecover') }}",
data: formData
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
});
And viewing the source looks fine to send...at least for me ^^
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");
}
});
$(document).on('submit', '#color_changer_form', function(e) {
e.preventDefault();
var colorCode = $('#color_code').val();
var formData = new FormData(this)[0];
$.ajax({
headers: {
'X-CSRF-Token': "{{csrf_token()}}"
},
type: "POST",
url: "{{route('color.store')}}",
data: formData,
async: false,
success: function(data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
});
<form action="" method="POST" id="color_changer_form">
<input type="text" id="color_code" name="color_code">
<button type="submit" id="color_submit" class="btn btn-success">Save Change</button>
</form>
Controller snippet:
public function store(Request $request){
return response()->json($request->all());
}
When I try to get the whole form data using the jQuery AJAX FormData() method, I get an empty array.
In need to use this FormData() because in the near future I have to upload an image using the form data.
Send the whole formData object
Change:
var formData = new FormData(this)[0];
To
var formData = new FormData(this);
If there are no files involved it is simple to use serialize() also
$.ajax({
headers: {
'X-CSRF-Token': "{{csrf_token()}}"
},
type: "POST",
url: "{{route('color.store')}}",
data: $(this).serialize(),
success: function(data) {
console.log(data)
}
});
Never use async:false. it is a terrible practice and is deprecated
I have some AJAX script that submits a form and then updates the web page.
My Code:
HTML:
<form action='jobs.php' method='post' name='editUpdate' enctype='multipart/form-data' id="form-add">
<hr />
<textarea name='description' id="title" class="text1" placeholder="Add Update" cols='100' rows='5'></textarea>
<input type="submit" name='action' id="submit" value="Save Update"></input>
</form>
AJAX:
<script>
$('#form-add').submit(function(e){
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
var prependbdDiv = $('#prependbody');
$.ajax({
url: formURL,
type: 'POST',
data: formData,
dataType: "json",
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if(response.success == "1"){
prependbdDiv.prepend("<tr><td>"+response.datetime+"</td><td>"+response.updatedesc+"</td></tr>");
$('#title').val('');
$("#form-add").fadeToggle();
}
},
error: function(response)
{
alert("ERROR");
},
});
e.preventDefault();
});
</script>
This seems to have resolved my issue:
Submiting a form with Ajax by using FormData on Firefox and IE10+
I am curious why this is the case or is it bad programming on my behalf?
Also when using FireBug the post data does not appear similar to that of the post data from a standard HTML form. IE, with the ajax post using formdata FireBug lists no "Parts" section under the POST details.
Thanks for your help!
I have this form:
<form id="ugaForm" method="POST" action="/url/upload" target="myFrame"
enctype="multipart/form-data">
Please select a file to upload : <input id="file" type="file" name="file" />
<input type="button" onclick="submitF()" value="upload" />
</form>
when submitting normally it works perfectly.
I need an ajax post to imitate this exact form submission.
This code doesnt work:
function submitF() {
debugger;
var mfile = $("form#ugaForm")[0].file;
var fd = new FormData();
fd.append( 'file', mfile);
$.ajax({
url: 'http://localhost/url/upload/',
data: JSON.stringify({ 'objectData' : fd}),
cache: false,
contentType : false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
If you are submitting something through AJAX then why are you putting it into the form. Just remove the form and keep the other things which were inside it so that it would become like this:
<div id="ugaForm">
Please select a file to upload : <input id="file" type="file" name="file" />
<input type="button" onclick="submit()" value="upload" />
</div>
And the JS would be this:
function submitF() {
debugger;
var mfile = $("#ugaForm")[0].file;
var fd = new FormData();
fd.append('file', mfile);
$.ajax({
url: 'http://localhost/url/upload/',
data: JSON.stringify({
'objectData': fd
}),
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
}
Hope it helps.