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 ^^
Related
$(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 am attempting to upload a file to a server from a bootstrap modal window, using ajax.
The modal html is
<div class="modal-body">
<div>
<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
The Javascript
$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
url: "attachment.php",
type: "POST",
data: data,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
The PHP server code
print_r($_POST);
print_r($_FILES);
I am not seeing anything in the $_FILES array when I run this.
Any suggestions?
Change the data value in your Ajax post to postData. postData contains the form data.
Change this section
data: data,
To
data: postData,//this contains the form data
You just need to change the data : data kew value inside the
$.ajax({
data : postData,
});
$.ajax({
url: "attachment.php",
type: "POST",
data: postData,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:
$.ajax({
type: 'POST',
dataType: 'json',
data: jsonData,
url: 'xxx.php',
cache: false,
success: function(data) {
//removed for example
}
});
The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.
If you want to send data along with any file than you can use FormData object.
Send your jsonData as like that:
var jsonData = new FormData(document.getElementById("yourFormID"));
Than in PHP, you can check your data and file as:
<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
Try Using formdata instead of normal serialized json
Here's an example:
var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]);
then in your ajax
$.ajax({
type: 'POST',
url: "YOUR URL",
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
CallBack(response, ExtraData);
},
error: function () {
alert("Error Posting Data");
}
});
You can try like this also
You can visit this answer also
https://stackoverflow.com/a/35086265/2798643
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})
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;
}
});
}
I am trying to create an image upload field in my application based on this question:
Send FormData and String Data Together Through JQuery AJAX?
and this tutorial:
http://www.formget.com/ajax-image-upload-php/
I have heard it is quite difficult, this is what i have tried.
HTML
<form method="POST" action="" id="logo_upload">
<input type="file" name="logo_location" id="logo_location" enctype="multipart/form-data">
<button type="submit" name="file_test" id="file_test">Test Upload</button>
</form>
JQuery
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData();
var file_data = $('#logo_location')[0].files[0];
formData.append("file", file_data[0]);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData ,
cache: false,
contentType: false,
processData: false,
id: id
});
});
PHP
var_dump($_FILES);
var_dump($_POST);
As you can see, I haven't got to the uploading side of things yet.
Result
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
I can't see what i am doing wrong, I am getting a result so it is getting to the right place, can anyone point me in the right direction?
EDIT: added #logo_upload in form
var file_data = $('#logo_location')[0].files[0];
EDIT: replaced data with formData variable
EDIT: added attribute: enctype="multipart/form-data"
New Result:
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
'file' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'undefined'</font> <i>(length=9)</i>
</pre>
You're appending file_data[0] to the formdata object, file_data is the file not an array, use file_data.
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData();
var file_data = $('#logo_location')[0].files[0];
formData.append("file", file_data);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData ,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
});
also you can instantiate the form data object with the form in question instead of doing the append.
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
...
I don't see logo_upload id in your form.
When uploading a file enctype="multipart/form-data" is must in form attributes.
data parameter in your ajax getting a variable i.e. not defined. Look at your reference link once again.
Hope this would help you
You are passing wrong variable here and you are not defining success in your ajax request:
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData($('#your_form_id')[0]);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData,
success: function(result){
alert(result);
}
cache: false,
contentType: false,
processData: false
});
});