File upload by ajax $.post not working - javascript

I am really new to ajax do forgive me if the question is stupid. I have a multi step form and it has the 4 parts , and I am using $.post() ajax request to send this. while all my other details are going fine I am not able to upload my file. this is what I am trying to do
Here I am trying to catch the form values.
var data_img = new FormData();
var hello = $.each(jQuery('#pan_file')[0].files, function (i, file) {
data_img.append('file-' + i, file);
});
Then I am passing these values to the object variable.
obj_params.pan_file = hello;
And then sending it to store with ajax.post()
$.post('<?php echo base_url(); ?>get-ekyc-form', obj_params, function (msg) {
if (msg == "1") {
swal("Success!", "EKYC Form has been Submitted Successfully", "success");
window.location = '<?php echo base_url(); ?>list-active-requirement';
}
}, "json", "processData:false", "contentType:false");
return true;
And this is where I do file transfer.
if ($_FILES['file-0']['name'] != "") {
$image_data = array();
//config initialise for uploading image
$config['upload_path'] = './media/front/img/quote-docs/';
$config['allowed_types'] = 'xlsx|pdf|doc|docx';
$config['max_size'] = '5000';
$config['max_width'] = '12024';
$config['max_height'] = '7268';
$config['file_name'] = time();
//loading upload library
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file-0')) {
$error = array('error' => $this->upload->display_errors());
} else {
$data = array('upload_data' => $this->upload->data());
$image_data = $this->upload->data();
$file_name = $image_data['file-0'];
}
$file_name = $image_data['file_name'];
} else {
$file_name = '';
}
Also I am working on someone elses code so I do understand I must have made loads of mistakes. I'll be grateful if someone could help me around this.

HTML code
<input id="picture" type="file" name="pic" />
<button id="upload">Upload</button>
$('#upload').on('click', function() {
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
in upload.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>

Related

Getting a php variable value back with an ajax result

I'm using croppie.js to crop user uploaded imaged, once the crop is done ajax is used to upload the result. Here is the codes for that...
Page A..
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "uploadown/uploader.php",
type: "POST",
data: {"image":resp},
success: function (data) {
html = '<img id="cropresult" style="margin: 0px;" src="' + resp + '" />;
$("#uploaded-input").html(html);
}
});
});
});
Then uploader.php is..
<?php
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
file_put_contents($imageName, $data);
?>
As you can see uploader.php is using time() for the $imageName variable.
I either need to pass $imageName back to Page A during upload
or
set $imageName in page A first and pass it to uploader.php at the same time as the image info.
After a few hours and many attempts having read many similar questions on here and cannot work out how to do this. Any help greatly appreciated.
Echo out the $imageName in php file, once done use it in javascript.
PHP
<?php
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if(file_put_contents($imageName, $data)){
echo $imageName;
} else {
echo " ";//In this case src will be empty
}
?>
Java script
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "uploadown/uploader.php",
type: "POST",
data: {"image":resp},
success: function (data) {
html = '<img id="cropresult" style="margin: 0px;" src="' + data + '" />';
$("#uploaded-input").html(html);
}
});
});
});
For any queries comment down.
just echo the name in php or var_dump() the array and then you will be able to access it in your javascript
all the data from the php page is addign to the variable name you give to the anonymous function you give to the success callback. for your case it will be accessed as data
Found your full exmaple here: https://websolutionstuff.com/post/crop-image-before-upload-using-croppie-plugin
Consider the following PHP.
<?php
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if(file_put_contents($imageName, $data)){
echo "Success, " . $imageName;
} else {
echo "Error, unable to Put file.";
}
?>
This will provide a response to the AJAX Script.
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "uploadown/uploader.php",
type: "POST",
data: { "image":resp },
success: function (data) {
var response = data.split(",");
var html;
if(response[0] != "Error"){
html = '<img id="cropresult" style="margin: 0px;" src="' + response[1].trim() + '" />';
$("#uploaded-input").html(html);
} else {
console.log(data);
}
}
});
});
});

Why is the input file data empty? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am working with an ajax PHP upload, the upload works well without ajax jQuery. I went to Google to find more resources on it and adjusted my code several times but still get the same error at the backend that file is empty. This is my code.
At the frontend
<input class="input is-link" id="file" name="file" type="file">
<button id="sendImg" class="button">Send</button>
</form>
My jQuery code
$(function(){
$("#chatsCard").on('click', '#sendImg', function (e){
e.preventDefault();
//alert("test");
var filedata = $("#file").prop("files")[0];
var recipient = $("#uname").html();
//alert(filedata);
$.ajax({
type:'post',
url:'upload.php',
contentType:false,
processData:false,
cache:false,
dataType:'json',
data:{
//rec:recipient,
filedata
},
success:function(data){
alert (data);
}
});//ajax end
});//click end
});//doc end
Backend
<?php
session_start();
require("assets/db.php");
$logged = $_SESSION['logged'];
//This is always my ajax response.
if(empty($_FILES['file'])){
$response = "No picture selected";
echo json_encode($response);
exit;
}
$imgFolder = "media/";
$fileTpath = $_FILES['file']['tmp_name'];
$fileSize = filesize($fileTpath);
$info = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($info, $fileTpath);
$filetype = explode ("/",$filetype);
$filetype = $filetype[1];
$allowedFiles = array("jpg" , "png" , "jpeg");
//rename image.
$newName = uniqid(8);
$newName = "recipient".
$newName. "." . $filetype;
//check file size
if($fileSize > 21464568){
$response = "Picture is greater than 2MB, Resize and try again";
echo json_encode($response);
exit;
}
//check format.
elseif(!in_array($filetype, $allowedFiles)){
$response= "You are only allowed to upload jpeg,jpg or png";
echo json_encode($response);
exit;
}
//check for existence of file.
elseif(file_exists($imgFolder.$newName)){
$response = "Failed!!! Upload again!!!";
echo json_encode($response);
exit;
}
//move to folder.
else{
move_uploaded_file($fileTpath,$imgFolder .$newName);
$recipient = $_POST['rec'];
$time = date("d-M-y")." at ". date("h:ia");
$msg = "media";
//insert to messaging
$q = "INSERT INTO messaging(message,sender, receiver,time) VALUES(?,?,?,?)";
$stm = $conn->prepare ($q);
$stm->bind_param("ssss",$msg,$logged,$recipient,$time);
$stm->execute();
//insert media details
$q1 = "INSERT INTO media(sender,mediaName,mediaType) VALUES(?,?,?)";
$stm = $conn->prepare ($q1);
$stm->bind_param("sss",$logged,$newName,$fileType);
$stm->execute();
//json response
$response = "success";
echo json_encode($response);
exit;
}
?>
Since I removed the jQuery and the uploading works normally, I assumed the problem is not from the backend so I focused on the jQuery by tweaking it to these
//First change
var fd = new FormData();
var file = $("#file").props('files')[0];
var file data= fd.append("file",filedata);
//This still gives no picture selected.
//Second change
var fd = new FormData($("#mediaPic")[0])
//Passed fd as data but still the same response.
//Tried other stuffs I got on Google to get the image data but still d same response.
You just need to post FormData() object, Append method returns null. Datatype text is preferred. So the final jQuery code would be:
$(function(){
$("#sendImg").on('click', function (e){
e.preventDefault();
//alert("test");
var recipient = $("#uname").html();
var form_data = new FormData();
var file = $("#file").prop('files')[0];
form_data.append('file', file);
$.ajax({
url: 'upload.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
alert(data);
}
});//ajax end
});//click end
});//doc end
To add additional value with form_data, simple use before submitting
form_data.append("rec", "value");

Cant get var to pass on Ajax post script

I can't seem to pass the "filename" variable from main.php to save_sign.php, can someone help me with this?
main.php
<? $filename="222222"; ?>
<script>
$(document).ready(function() {
$('#signArea').signaturePad({drawOnly:true, drawBezierCurves:true, lineTop:90});
});
$("#btnSaveSign").click(function(e){
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
var filename = '<? echo $filename; ?>';
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: { img_data:img_data },
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
</script>
save_sign.php
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = $_POST['filename'];
//Location to where you want to created sign image
$file_name = ('./doc_signs/'.$filename.'.png');
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
You need to add filename var to ajax data like below
url: 'save_sign.php',
data: { img_data:img_data,filename:filename}

Echo PHP inside of string

I am running a simple chat application and it's powered by a process.php file, but the chat is on chat.php.
Basically people can search for a "Topic", and it'll take them to domain.tld/chat.php?topic=topicname (topicname being whatever they searched for)
I need my process.php file to echo
<?php echo $_GET['topic']; ?>.txt
instead of chat.txt, so that each topic has a unique text file (so that all chats aren't linked)
This is my process.php file:
<?php
$function = $_POST['function'];
$log = array();
switch($function) {
case('getState'):
if(file_exists('logs/chat.txt')){
$lines = file('logs/chat.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists('logs/chat.txt')){
$lines = file('logs/chat.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = htmlentities(strip_tags($_POST['nickname']));
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
$message = preg_replace('/#(\w+)/', ' #$1', $message);
fwrite(fopen('logs/chat.txt', 'a'), "<span>". $nickname . "</span>" . $message = str_replace("\n", " ", $message) . "\n");
}
break;
}
echo json_encode($log);
?>
This is my chat.js file
/*
Created by: Kenrick Beckett
Name: Chat Engine
*/
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
In theory this should create a unique topicname.txt file in /logs/ whenever somebody starts chatting in a topic that's nonexistent. I'm just having trouble adding the topicname in place of chat.txt in process.php. So far I know that it does create a chat.txt file by itself, so it should create a unique .txt file once I echo it correctly.
Also, I'm aware that a database is a better option when compared to storing messages in unique .txt files, but this is how I want to do it.
Here's an example of how I was trying to add it to my process.php a snippet from process.php)
case('getState'):
if(file_exists('logs/<?php echo $_GET['topic']; ?>.txt')){
$lines = file('logs/<?php echo $_GET['topic']; ?>.txt');
}
^ That probably isn't even the right format, as I'm new to PHP and make tons of mistakes, and it probably won't know what the GET is because it's not a part of chat.php ... it's a separate file.
Try with -
'logs/' . $filename . '.txt'
where ever you want.
Update
if (!empty($_GET['topic'])) {
$filename = $_GET['topic'];
} else {
$filename = 'something else';
}
if(file_exists('logs/' . $filename . '.txt')){ $lines = file('logs/' . $filename . '.txt') ....
It is already in php. So no need to add <?php ?> and echo. Just simply concatenate them.
you are already in php tag.. no need to add extra php tags
case('getState'):
if(file_exists("logs/".$_GET['topic'].".txt")){
$lines = file("logs/".$_GET['topic'].".txt");
}
or Try this
case('getState'):
if(isset($_GET['topic']){
$filename = "logs/".$_GET['topic'].".txt";
if(file_exists($filename)){
$lines = file($filename);
}
}
}

Php error showing while accessing input type = file using jquery/ajax method

I need to access input type=file using jquery/ajax so that I can pass the value/file to php page. but It's showing me following error message :
Notice: Undefined index: file in D:\software installed\xampp\htdocs\contact-management
\editContactDetails.php on line 16
Is there any problem in my following code or Is there anyway to access it ?
My html code:
<form enctype="multipart/form-data">
<input type="file" name="file" id="file" class="file"/>
<input type="button" name="submit" value="Update Details" class="submit" id="UpdateDetails"/>
</form>
Jquery/Ajax code:
$(document).ready(function() {
$("#UpdateDetails").click(function() {
var fn = $('#family_name').val();
var cdid = $('#cdid').val();
var family_name = $('#family_name').val();
var given_name = $('#given_name').val();
var work_phone = $('#work_phone').val();
var mobile_phone = $('#mobile_phone').val();
var email = $('#email').val();
var email_private = $('#email_private').val();
var file_des_1 = $('#file_des_1').val();
var file = $('#file').val();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "editContactDetails.php",
data : {
'cdid' : cdid,
'family_name' : fn,
'given_name' : given_name,
'work_phone' : work_phone,
'mobile_phone' : mobile_phone,
'email' : email,
'email_private' : email_private,
'file_des_1' : file_des_1,
'file' : file
},
dataType: "html", //expect html to be returned
success: function(response){
$("#successUpdate").html(response);
//alert(response);
}
});
});
});
Php file Code:
//uoload first docuement with description...
$file_des_1 = $_POST['file_des_1'];
$did = mt_rand(100000, 999999);
$file = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = ($_FILES["file"]["size"] / 1024);
$temp = $_FILES["file"]["tmp_name"];
//require file formate
$allowedExts = array("doc", "docx", "xls", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
//rename uploaded docuement
echo $doc_1 = $did.".".$extension;
$contacts_doc_directory = "contact_directory";
Try this for file upload
<form enctype="multipart/form-data" >
<input type="file" name="file" id="file" class="file"/>
<input type="button" name="submit" value="Update Details" class="submit" id="UpdateDetails"/>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#UpdateDetails").click(function() {
var formData = new FormData($('form')[0]);
alert(formData);
$.ajax({
url: 'editContactDetails.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
// myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
// beforeSend: beforeSendHandler,
// success: completeHandler,
//error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});//ajax
});
});
</script>
Before you start to work with data passed to a php script you should check that these data are actually passed to script... you can do it using isset() and empty() that checks if a value is set of variable you pass as an argument.
so your script becomes:
if (isset($_POST['file_des_1']) && !empty($_POST['file_des_1']) && isset( $_FILES["file"] ) && !empty( $_FILES["file"]["name"] )) {
//uoload first docuement with description...
$file_des_1 = $_POST['file_des_1'];
$did = mt_rand(100000, 999999);
$file = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = ($_FILES["file"]["size"] / 1024);
$temp = $_FILES["file"]["tmp_name"];
//require file formate
$allowedExts = array("doc", "docx", "xls", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
//rename uploaded docuement
echo $doc_1 = $did.".".$extension;
$contacts_doc_directory = "contact_directory";
}

Categories