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.
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 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.
Meanwhile I'm getting stuck on this issue. Normally, it's pretty simple but somehow it doesn't work for what I'm trying to do. I want to get all data from my form input fields by either Jquery or JS and then send them through AJAX to the server sided script (PHP). Even by using append or do it by serialize, I only obtain the object from input field with ID #file. I'm not using a submit button to confirm the uploaded image - only select the file and send it off.
I already tried too add
formdata.append("_token", document.getElementById('_token').val());
but whenever I try to append another element to the formdata the entire script stops working
By using $('#picUploadForm').serialize(); I do not get the any result from the input element with ID #file.
HTML:
<form enctype="multipart/form-data" id="picUploadForm">
<input type="file" name="file" id="file" style="display:none;" >
<input type="hidden" name="_token" id="_token" value="<?php echo $_SESSION['_token']; ?>" />
</form>
<!-- Default Avatar Image -->
<div class="click-slide overlay">
<!-- Profile Image-->
<img src="<?php if(isset($avatar['filelink']) && $avatar['filelink'] !='') { echo $avatar['filelink']; } else { echo "assets/images/avatars/default_avatar_large.png"; }?>" alt="" class="img-full-width-tight" id="imagePreview" />
<!-- Image update link -->
<div id="editLink" >
<span>
<a href="javascript:void(0);" class="pop-inline ti ti-image" ></a>
</span>
</div>
</div><!--/ click-slide-->
JS:
//On select file to upload
$('#file').on('change', function(e){
e.preventDefault();
var formdata = new FormData();
// any other code here....
} else {
// Upload Image to backend
formdata.append("file", document.getElementById('file').files[0]);
// formdata.append("_token", document.getElementById('_token').val()); // does not work!!!
// $('#picUploadForm').serialize(); // only returns data from input #_token
$.ajax({
url: "./serversided.php",
type: "POST",
data: formdata,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$("#statusav").removeClass().html('');
$('.overlay').LoadingOverlay("show");
HideLoadingOverlay();
},
success: function(data){
if(data.status === true){
// alert(data.imgURL);
setTimeout(function(){$("#statusav").removeClass('alert alert-danger').addClass('alert alert-success').html(data.reply)}, 2000);
$("#imagePreview").attr('src', data.imgURL);
} else {
// alert(data.error);
setTimeout(function(){$("#statusav").removeClass('alert alert-success').addClass('alert alert-danger').html(data.error)}, 2000);
}
}
});
}
});
.val() is a jQuery method - it is not a vanilla JS method, so it doesn't work when called on a plain element. document.getElementById will return an element (or null); $('selectors here') will return a jQuery object, on which you can use jQuery functions.
Try this instead, with vanilla JS:
formdata.append("_token", document.querySelector('#_token').value);
Or select the element with jQuery and use the jQuery method:
formdata.append("_token", $('#_token').val());
I am trying to make a form where there will be user data(name,dob etc) and an image. When user submits the form a pdf will be generated with the user given data and the image. I can successfully serialize the data but failed to get image in my pdf. I am using simple ajax post method to post data. Below is my code.
HTML code
<form onsubmit="submitMe(event)" method="POST" id="cform">
<input type="text" name="name" placeholder="Your Name" required>
<input type="file" name="pic" id="pic" accept="image/*" onchange="ValidateInput(this);" required>
<input type="submit" value="Preview"/>
</form>
Jquery code
function submitMe(event) {
event.preventDefault();
jQuery(function($)
{
var query = $('#cform').serialize();
var url = 'ajax_form.php';
$.post(url, query, function () {
$('#ifr').attr('src',"http://docs.google.com/gview?url=http://someurl/temp.pdf&embedded=true");
});
});
}
PHP code
<?php
$name=$_POST['name'];
$image1=$_FILES['pic']['name'];
?>
Here I am not getting image1 value. I want to get the url of the image.
You need FormData to achieve it.
SOURCE
Additionally, you need to change some stuff inside ajax call(explained in link above)
contentType: false
cache: false
processData:false
So the full call would be:
$(document).on('change','.pic-upload',uploadProfilePic);
#.pic-upload is input type=file
function uploadProfilePic(e){
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
$.ajax({
type:"POST",
url:"uploadpic.php",
data: actual,
contentType: false,
cache: false,
processData:false,
dataType:"json",
success: function (response){
#Maybe return link to new image on successful call
}
});
}
Then in PHP you handle it like this:
$_FILES['file']['name']
since you named it 'file' here:
actual.append('file', newpic[0]);
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;
});