Isset does not work with ajax call - javascript

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.

Related

upload a form's file and text data to PHP using jQuery and AJAX

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;
});

send image url and data through serialization

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]);

Ajax POST format with PHP

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;
});

Image upload via ajax POST without using HTML form

I am trying to send some data via POST method to a PHP file without using form in HTML. This is the code I have. Why doesn't it do anything?
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid" id="gid">
<input type="hidden" value="User" name="user" id="user">
<button onclick="myFormData()">Upload Image</button>
<script>
$('#fileToUpload').on('change', function() {
var myFormData = new FormData();
var file = document.getElementById('fileToUpload').value;
var gid = document.getElementById('gid').value;
var user = document.getElementById('user').value;
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
});
$.ajax({
url: 'imgupload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
</script>
On imgupload.php I get the POST data like this
$gid = $_POST['gid'];
$user = $_POST['user'];
It worked when I used the HTML form method. What's wrong here?
FormData.append() takes key-value pairs, so this is wrong:
myFormData.append(file,gid,user);
You need something like:
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
Appart from that you need to put this code inside an event handler so that it triggers when you need it to.
For example:
$('#fileToUpload').on('change', function() {
// your javascript code
});
And you should probably also put it inside a document.ready block.

PHP upload file to Ajax using onchange

function chkFile(file1) {
var file = file1.files[0];
var formData = new FormData();
formData.append('formData', file);
$.ajax({
type: "POST",
url: "chkFileType.php",
contentType: false,
processData: false,
data: formData,
success: function (data) {
alert(data);
}
});
}
<form action="" method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Upload Files
<input type="file" name="uploadFile" id="uploadFile" onChange="chkFile(this)"/>
<input type="submit" name="submitbutt" value="Checkout">
chkFileType.php
<?php
print_r($_FILE)
?>
I want to create a form that when the user uploads a file, it will do a check on the uploaded file before submitting the whole form. I use onChange when a file is uploaded and then pass the formData value to Ajax to call my chkFileType.php to do the checks and alert back the response.
The function is running without any errors, but no response from alert(data);
I know I am doing something wrong, but have no idea which direction to go from. Am I doing the right way?
Everything looks fine. You have done in right way. But to get any response from an ajax call, you have to print the required stuff in chkFileType.php.
Like,
if($ext =="jpg" || $ext == "png"){
echo "Image"; // data in alert will alert as Image
} else if(check for txt file){
echo "Text File"; // data in alert will alert as Text File
} else if(chck for pdf) {
echo "Pdf";// data in alert will alert as Pdf
}
EDIT
change this
var formData = new FormData( $("#formID")[0] );
Hope you understand what i meant to say.
I think the problem is in that you have written "type" instead of "method", "POST" is a method not a type.

Categories

Resources