My reference is here How to send FormData objects with Ajax-requests in jQuery?
The answer on that link worked on my program. My problem is how to append more data in FormData? I'm using python django and I would like to know where I can put the csrfmiddlewaretoken and inputfilename
Before, this is what I have in form data
var form_data = {
inputfilename: $("#filename").val(),
inputfile: $("#file").val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
ajax: 1
};
and now,
var form_data = new FormData();
form_data.append('file', input.files[0]);
I'm not quite sure what's the issue you are having. Just append the csrf token the way you append the file:
var fd = new FormData();
fd.append('file', input.files[0] );
fd.append('csrfmiddlewaretoken', csrf_token);
$.ajax({
url: url,
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: callback
});
Related
I've been using the following code to upload image to server. Is it possible to change it to pass file data using an object instead of form data and using GET instead of POST.
var uploadfileinfo = document.getElementById("upload-file-info").value;
var file_data = $('#a_imgfile').prop('files')[0];
var a_imgfile = document.getElementById("a_imgfile");
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
async: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
alert(response);
},
error: function(err) {
alert(err);
}
});
Browser file upload will send form multipart contenttype, you cant send content type in GET request
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
If you are looking for some workaround you can use some base64 encoder and pass your image to url query param
In GET request you can only get data or pass query paramerters. If you want to upload image change any other data it must be in POST request
Read more https://www.w3schools.com/tags/ref_httpmethods.asp
I am trying to send the uploaded file and the input text data (there are 5 text fields) without using form action. Is this the correct way to do it, this code works fine if I send only form_data or the values in {} but not both together. This is my code:
actionval = document.getElementById('action').value;
titleval = document.getElementById('title').value;
stageval = document.getElementById('stage').value;
substageval = document.getElementById('substage').value;
agentval = document.getElementById('agent').value;
var file_data = $('#uploadFileTrans').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "tabs/get_old_contents.php",
data: {form_data, insert1:actionval, insert2:titleval, insert3:stageval, insert4:substageval, insert5:agentval},
type: 'post',
complete: function(response){
alert('Details added successfully!');
$('#restrans').html(response.responseText);
// console.log('hey', response.responseText);
// editor.setValue(response.responseText);
}
});
and php is this :
$action = (isset($_POST['insert1'])?$_POST['insert1']:"");
$title = (isset($_POST['insert2'])?$_POST['insert2']:"");
$stage = (isset($_POST['insert3'])?$_POST['insert3']:"");
$substage = (isset($_POST['insert4'])?$_POST['insert4']:"");
$agent = (isset($_POST['insert5'])?$_POST['insert5']:"");
$date = date("Y/m/d");
and this is to upload , it works fine if I have only form_data in data field of ajax
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
You can't put a FormData inside an object being sent with AJAX. You need to add the other parameters to the FormData object, and use that as the data by itself.
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('insert1', actionval);
form_data.append('insert2', titleval);
form_data.append('insert3', stageval);
form_data.append('insert4', substageval);
form_data.append('insert5', agentval);
$.ajax({
url: "tabs/get_old_contents.php",
data: form_data,
processData: false,
type: 'post',
complete: function(response) {
alert('Details added successfully!');
$('#restrans').html(response.responseText);
// console.log('hey', response.responseText);
// editor.setValue(response.responseText);
}
});
You have to add all your data to the FormData object and pass that as the data parameter. Also, set processData to false and contentType to false.
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('insert1', actionval);
form_data.append('insert2', titleval);
form_data.append('insert3', stageval);
form_data.append('insert4', substageval);
form_data.append('insert5', agentval);
$.ajax({
url: "tabs/get_old_contents.php",
data: form_data,
type: 'post',
processData: false,
contentType: false,
complete: function(response){
alert('Details added successfully!');
$('#restrans').html(response.responseText);
// console.log('hey', response.responseText);
// editor.setValue(response.responseText);
}
});
below you can see the html code, javascript/jquery and PHP. I'm trying to send a request using AJAX PHP, to send multiple variable to PHP, one of them is FormData and the other is some text or values from inputs etc.
Here's html code:
<div>
<p>Name:</p>
<input id="newP_name"></input>
<p>Product Image</p>
<input type="file" id="img"></input>
<p>Description:</p>
<textarea id="newP_desc"></textarea>
<button name="submitProductBtn" id="submitProductBtn">Submit</button>
Here's my javascript:
$("#submitProductBtn").click(function(){
var file_data = $('#img').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'imgParser.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data, name: "John",
type: 'POST',
success: function (response) {
alert(response);
},
error: function (response) {
alert("ERROR OCCURED");
}
});
});
As you can see I'm trying to pass to 'data:' the FormData (image) and a second variable name.
Here's PHP code:
<?php
if(isset($_FILES["file"]["name"])){
if($_FILES["file"]["error"] == 0){
move_uploaded_file($_FILES["file"]["tmp_name"], "images/".$_FILES["file"]["name"]);
echo $_POST["name"];
}else{
echo $_POST["name"];
}
}
?>
I would expect it to print "John", but the alert is blank, image showing ->
Any help appreciated,
thanks in advance.
EDIT:
Changed slightly the jQuery code, still outputs empty, but when I had code commented out in PHP (below closing tag), it printed it.
here's my new jquery code:
$("#submitProductBtn").click(function(){
var file_data = $('#img').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', "John");
$.ajax({
url: 'imgParser.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function (response) {
alert(response);
},
error: function (response) {
alert("ERROR OCCURED");
}
});
});
You append all data fields to the form data object just like you did with the file
form_data.append('file', file_data);
form_data.append('name', 'John');
I'm not sure what is form_data maybe you can try this,
form_data.append('file', file_data);
form_data.append('name', 'john');
and simply pass form_data in data property
$.ajax({
...
...
data: form_data
Faced with such a problem that you can't add parameters to ajax request, because there is a "Form Data" and it does not work to add more options. When you add in the parameter 'data' another variable, the error occurs. How to do that would be to post a file and parameters in one request?
Forgive the mistake, error or no, the php file simply does not output anything, rather empty values
//Here the file is sent without problems, but the parameters no more don't accept php file, nothing displays in the result
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: fd,
type: "POST",
processData: false,
contentType: false,
success: function(data) {
$(".news .containers").append(data);
}
});
//When this code runs the PHP file won't take anything, although I was expecting the output variables and the file. Using var_dump, $_POST and $_FILES displays array(0){}
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: {fd, title:newsHeader, description:description, hashTag:hashTag, themeHashTag:themeHashTag, viewNews:viewNews},
type: "POST",
processData: false,
contentType: false,
success: function(data){
$(".news .containers").append(data);
}
});
//Similarly, nothing appears in the php file
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: {fd:fd, title:newsHeader, description:description, hashTag:hashTag, themeHashTag:themeHashTag, viewNews:viewNews},
type: "POST",
processData: false,
contentType: false,
success: function(data){
$(".news .containers").append(data);
}
});
Just like you have appended the file, you can append more data into it like:
fd.append('file', input[0].files[0]);
fd.append('var1', val1);
fd.append('var2', val2);
var fd = new FormData();
fd.append( 'file', input.files[0] );
fd.name = 'something';
fd.etc = 'something more';
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
I put above code within a submit event, I found in my backend I received duplicated formData's data. Because after submit I did not want to hard refresh the page for good UX. How to clear the formData after ajax's success?