I am using $.ajax({}) of jQuery, I am trying to move the uploaded file in folder on click. The upload came successful but my problem is when uploading, the page is refreshing I already tried e.preventDefault() and <button type="button">
This is my html code
<input type="file" id="student-img-file" accept="image/*" name="student-img-file">
<button type="button" id="btn-submit-form" class="mt-4">Submit Form</button>
This is my jQuery code
$('button#btn-submit-form').on('click', function(e){
let formData = new FormData()
formData.append('student-img-data', $('#student-img-file').prop('files')[0])
$.ajax({
url: '../PHPFunctions/AdmissionFormFunction.php',
method: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
success: function(result){
console.log(result)
}
})
})
this is my PHP(AdmissionFormFunction.php) code
$studentImgData = $_FILES['student-img-data'];
if(move_uploaded_file($studentImgData['tmp_name'], '../FileUploads/' . $studentImgData['name'])){
echo "YESSSSSSSSSSSS";
}
I am not using form tags by the way
I just turned off my vs code live server. I forgot that any changes that i've made in my folder system in vs code will refresh the page.
Related
Good morning. I'm trying to make the form submission of a message more fluid avoiding the reload of the page for the sending of it. Since the message may be text or image, I need to send both of them to a PHP page for upload. I'm using this code in the html page:
<form id="newmessage" enctype="multipart/form-data">
<textarea form="newmessage" id="messagetext" name="messagetext" ></textarea>
<input type="submit" name="submit" value="send" onclick="return newMessage();">
<input type="file" accept="image/*" id="image" name="image">
</form>
<script>
function newMessage(){
var messagetext = document.getElementById("messagetext").value;
var image = document.getElementById("image").value;
$.ajax({
type:"post",
url:"new_message.php",
data:
{
"messagetext" :messagetext,
"image" :image,
},
cache:false,
success: function(html) {
document.getElementById("messagetext").value = "";
}
});
return false;
}
</script>
As you can see, I'm allowing users to type in the textarea or upload a file. When they submit the form, the newMessage() method is invoked and sends image and messagetext to new_message.php, which process them:
// new_message.php
$messagetext = $_POST["messagetext"];
$image = $_FILES["image"]["tmp_name"];
if((!empty($messagetext) || isset($image))) {
if(!empty($messagetext)) {
// create text message
} else if(isset($image)) {
// create image message
}
}
When I write a text message it works perfectly, but it doesn't send anything if it's image. Maybe the image variable in AJAX is not taking the file properly. I excuse if this question is unclear, but I'm a beginner in StackOverlow and I'm open to edits. Thanks for all replies.
can you try this. you don't need to worry about the file and message in textarea. Make sure you have added jQuery.
$("#newmessage").on("submit", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var formData = new FormData(this);
$.ajax({
url: "new_message.php",
type: "POST",
data: formData,
success: function (msg) {
document.getElementById("messagetext").value = "";
},
cache: false,
contentType: false,
processData: false
});
return false;
});
I have some text and a file control and a button and an image which all disappear when the button is clicked and I call an ajax request from there. I checked all the other stack overflow answers and all the other sites, but doing anything including inserting a hidden field, or adding the missing code with PHP or JS all don't work. Thank you very much for your help.
<div id = "CreatePostUpload">
Select Image to Upload:
<input type='file' name='CreatePostImageFile' id = "CreatePostImageFile" />
<input type='button' onclick = "uploadCreatePostPhoto()" value='Save' name='but_upload' id = "CreatePostImageSubmit" />
<img src="images/cancel.png" onclick="closeCreatePostUploadPhoto()"/>
</div>
Everything inside the CreatePostUpload div disappears when I call the following:
function uploadCreatePostPhoto() {
var fd = new FormData();
var files = $('#CreatePostImageFile')[0].files[0];
fd.append('file', files);
$.ajax({
url: 'uploadMyCreatePostPhoto.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
$("#CreatePostUpload").html(response);
closeCreatePostUploadPhoto();
},
});
}
Thank you very much for your help.
epascarello, who posted this comment
because you replace the content..... $("#CreatePostUpload").html(response);
is right: I was replacing my content.
I have multiple input fields of type file generated using php foreach loop.Below is a snippet html form generated
<input name="userImage" id="a1Cym4V" type="file" />
<button type="button" onclick="upload_proof('a1Cym4V')">Upload</button>
<input name="userImage" id="pe7h6Cx" type="file" />
<button type="button" onclick="upload_proof('pe7h6Cx')">Upload</button>
<input name="userImage" id="L9iCaxV" type="file" />
<button type="button" onclick="upload_proof('L9iCaxV')">Upload</button>
If i upload an image using the first input form, it works fine, all others will return empty value even when a file is selected.
This is the javascript code i use to process the file upload via ajax.
function upload_prooff(id){
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
formData.append('id', id);
formData.append('upload_proof', '1');
$.ajax({
url: "convert.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
}
});
}
The data contains var_dump($_FILES) from the server.
What is the best approach to solve this problem?
I have a form, inside which I want to have a "virtual form", which handles file attachments. I have a File-input and a button to send the file.
The problem is that my PHP backed gets only POST and that with structure:
"file"; filename="xxx.jpg"
Content-type: image/jpeg
.
.
.
where the dots represent the binary data from the file.
From what I have read it should be $_FILES and $_POST variables but I don't get them.
Here are the relevant codelines in HTML and in Javascript:
<input type="file" id="file-to-append" name="file-attachment">
<input type="button" onClick="append_file()" value="Add file">
function append_file() {
var formData = new FormData();
console.log(jQuery('#file-to-append'));
formData.append('file', jQuery(":file")[0].files[0]);
jQuery.ajax({
url : 'file_upload.php',
type : 'POST',
data : formData,
processData: false,
success : function(data) {
console.log(data);
alert("Added");
}
});
}
Could somebody spot or know where the problem lies?
The data is passing properly so there is no problem with your Ajax call.
You get the file object in PHP using the super global $_FILES.
In your case, you would use it like:
$file = $_FILES['file'];
echo $file['name'];
echo $file['tmp_name'];
.
.
.
To take a look at the $_FILES array you could:
echo "<pre>";
print_r($_FILES);
echo "</pre>";
Things are getting stranger and stranger. I got it working, but only on IE 11 by setting contentType: 'multipart/form-data' With Chrome it doesn't work at all with that setting.
I have tried with contentType: false, but it doesn't work on either platform though it should be the right thing(TM) to do :/.
I have also added enctype-setting in the outer form, but I wonder how it could help, because I am not submitting (whole form) but only adding things "inside" the main form (that I handle myself). Apparently it didn't help either.
This shouldn't be a problem but for some reason I am stuck with this ajax implementation, though I have used file upload since long time ago (two figure number)...
hank
Use right encrypte in your form
<form id="data" enctype="multipart/form-data" method="post" >
<input type="submit" value="Add file">
</form>
use ajax submit
$("form#data").submit(function()
{var formData = new FormData($(this)[0]);
$.ajax({
url: "filename.php",
type: 'POST',
data: formData,
async: false,
success: function (data)
{
var jsonData = $.parseJSON(data);
var errFlag =jsonData.errorFlag;
var errMsg =jsonData.errorMessage;
if(errFlag == 1)
{
//successmessage;
}
else
{
//errormessage;
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
I know that I cannot upload a file with jquery so I come up with this solution:
var ifframe = $("<iframe></iframe>");
var input = $('<input type="file" id="file" name="file" size="10"/>');
var form = $('<form action="/upload" method="post" enctype="multipart/form-data"></form> ');
form.append(input);
ifframe.append(form);
input.change(function(){
form.submit();
}
);
input.trigger("click");
Basically I try to create a form insde the iframe and the trigger a click on the file field so the user is given a window where he can select image. then the form is automatically submitted and the main page does not get redirected since the form is in an iframe. The problem is that the main page does get redirected. Can anybody help me out here?
Actually, JQ can submit a form w. attachment asynchronously. Take a look at this example. Much better than an iframe approach.
$("#addProductForm").submit(function (event) {
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$("#productFormOutput").html(returndata);
alert(formData);
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});