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());
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 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 am doing image upload without using submit button. When user choose a image, he upload immediately. But I have a problem, Ajax only print "succes", but image is not in folder. PHP without ajax work.
This is my html:
<form action="../PHP/fotogaleria.php" method="post" class="form_fotogaleria" enctype="multipart/form-data">
<div class="obal_fotogalerie">
<div class="stvorcek">
<label class="file_nahod">
<input type="file" name="odoslat_fotogaleria" class="odid">
<img class="priecinok" src="../Obrazky/folder.png">
<p> NahraƄ</p>
</label>
</div> <!-- koniec "stvorcek" -->
</div> <!-- koniec "obal_fotogalerie" -->
</form>
PHP:
$name = $_FILES['odoslat_fotogaleria']['name'];
$tmp_name = $_FILES['odoslat_fotogaleria']['tmp_name'];
$path = '../Obrazky-zvieratok/';
$cielovy_file = $path . basename($name);
move_uploaded_file($tmp_name,$path.$name);
echo "success";
And here is AJAX:
$('.odid').change(function(e) {
e.preventDefault();
$.ajax({
url: '../PHP/fotogaleria.php',
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
}
Can someone help?
You're passing the input element to the FormData constructor. You should pass the form element instead.
data: new FormData($(this).closest('form').get(0)),
I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.
With this AJAX script, I'm trying to send the content of contentText and contentID.
Just sending contentTEXT works, but I want to send the ID as well, so I can comment on the original post.
But it doesn't work!
myData looks like this when it semi works:
> var myData = '?content_txt='+$("#contentText").val(),
> '&content_id='+$("#contentId").val(); //build a post data structure
But i want it to be something like this, i think
<script type="text/javascript"> $(document).ready(function() {
//##### send add record Ajax request to response.php ######### $("#FormSubmit").click(function (e) { e.preventDefault(); if($("#contentText").val()==='') {
alert("Please enter some text!");
return false; }
$("#FormSubmit").hide(); //hide submit button $("#LoadingImage").show(); //show loading image
var myData = '?content_txt='+$("#contentText").val(), '&content_id='+$("#contentId").val(); //build a post data structure
jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "response.php", //Where to make Ajax calls contentType: "application/x-www-form-urlencoded;charset=UTF-8", dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
}, error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError); } }); });
//##### Send delete Ajax request to response.php ######### $("body").on("click", "#responds .del_button", function(e) { e.preventDefault(); var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode) var DbNumberID = clickedID[1]; //and get number from array var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class $(this).hide(); //hide currently clicked delete button
jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "response.php", //Where to make Ajax calls dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut(); }, error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError); } }); });
}); </script>
My form I'm trying to use
<form class="form-horizontal" accept-charset="utf-8">
<fieldset>
<legend><?php echo WORDING_ADD_A_COMMENT; ?></legend>
<!-- Textarea -->
<div class="control-group">
<div class="controls">
<textarea name="content_txt" id="contentText" cols="45" rows="5" placeholder="<?php echo WORDING_COMMENT_PLACEHOLDER; ?>"></textarea>
<input type="hidden" name="content_id" id="contentId" value="<?php echo $_GET['topic_id']; ?>"/>
</div>
</div>
<!-- Button -->
<div class="control-group">
<label class="control-label" for="singlebutton"></label>
<div class="controls">
<button id="FormSubmit" class="btn btn-primary"><?php echo WORDING_BUTTON_COMMENT_BOX; ?></button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</div>
</div>
</fieldset>
</form>
var variable = {
'content_txt': $("#contentText").val(),
'content_id': $("#contentId").val()
};
try to use
var myData = '?content_txt='+$("#contentText").val()+'&content_id='+$("#contentId").val();
You only use ? and & when you manually build a query string and in that case you would need to encode your values as well.
When you send the data as a parameter, the easiest solution is to generate an object. That will be encoded automatically by jQuery:
//build a post data structure
var myData = { 'content_txt': $("#contentText").val(),
'content_id': $("#contentId").val() };
As you are using a form, you can also serialize the form:
var myData = $('.form-horizontal').serialize();
data:'content_id='+ $("#contentId").val()+ '&content_txt='+ $("#contentText").val() ,