File upload with form inputs AJAX not working - php

I've been searching for solutions across SO and have tried them, but not one of the answers I found has solved my problem. So here is it.
I am working on a simple web app with input details and file upload (.docx files). I used FormData for the handling of form data, but the server-side operation only works for the form inputs like text, password, date ,etc.
This is my JS code; the commented lines are the one which I attempted but did not work.
var myForm = $("#add-thesis-form");
var formData = new FormData(myForm);
//var formData = myForm.serialize();
$.ajax({
type: "POST" ,
url: "thesis-scripts/add_thesis.php",
data: formData
// processData: false,
// contentType: false
}).done(function(data){
$('#addThesisModal').modal('hide');
alert(data);
//alert("Successfully saved a record to the database. ");
showThesis();
});
My PHP code (using Meekro DB)
$title = $_POST["title"];
$description = $_POST["description"];
$categoryId = $_POST["category_id"];
$collegeId = $_POST["college_id"];
$departmentId = $_POST["department_id"];
$uploadedBy = $_SESSION["user"];
$uploadedAt = DB::queryFirstField("SELECT NOW();");
$year = $_POST["thesis_year"];
$keywords = $_POST["keywords"];
$authors = $_POST["authors"];
//FILE UPLOAD
$targ_dir = "../uploads/";
$targ_file = $targ_dir . basename($_FILES["thesis"]["name"]);
$flagOk = 1;
$tempFolder = $_FILES["thesis"]["tmp_name"];
move_uploaded_file($tempFolder, $targ_file);
//!FILE UPLOAD
$result = DB::insert('theses', array(
"title" => $title,
"description" => $description,
"categoryId" => $categoryId,
"collegeId" => $collegeId,
"departmentId" => $departmentId,
"uploadedBy" => $uploadedBy,
"uploadedAt" => $uploadedAt,
"pubyear" => $year,
"filepath" => $targ_file,
"views" => 0,
"rating" => 0,
"keywords" => $keywords,
"authors" => $authors
));
I've tried a print_r($_FILES) and that one works, but this one doesn't. Please help me. Thanks.
Setting the contentType:false causes the server to throw an error Undefined index on all the $_POST variables.

Maybe your form should includes enctype="multipart/form-data"
Maybe this would work :
$.ajax({
type: "POST" ,
url: "thesis-scripts/add_thesis.php",
data: "multipart/form-data"
...

Related

Image file coming empty

I have created a script to upload the image with text but the problem is that when we post the data and upload the image the file is coming empty I do not know why the file is coming empty can anyone help me out to get the correct file
This is my ajax script
$(document).ready(function(e) {
$("#post").on('submit', (function(e) {
$("#load").show();
var form = this;
var formData = new FormData(this);
alert(formData);
formData.append('post_dt', $("#contentbox").html());
$.ajax({
url : "http://domainname.com/demo/forums/post_forum",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
success : function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
$("#contentbox").empty();
form.reset();
},
complete: function() {
$("#load").hide();
}
});
}));
});
This the html form which is being created
<form method="POST" action="" id="post" enctype="multipart/form-data" onsubmit="return false;">
<ul>
<li>
<i class="fa fa-photo"></i> Upload A Photo / Document
<input type="file" name="image" />
</li>
</ul>
<div id='display'></div>
<div id="contentbox" contenteditable="true" name="post_dt">
</div>
<input type="submit" id="sb_art" class="btn_v2" value="Start Discussion" />
</form>
My php script which I have created within the controller
public function post_forum() {
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$this->load->library('upload', $config);
if(!empty($this->input->post('image'))) {
if (!$this->upload->do_upload('image')) {
$error = array('error' => $this->upload->display_errors());
} else {
$dt = $this->upload->data();
$file = $dt['file_name'];
}
} else {
$file = 'Filename.jpg';
}
$word_dta = $this->input->post('post_dt');
$time_posted = time();
$user_id = $this->basic_model->is_login($this);
$data_upload = array(
'upload_document' => $file,
'discussion' => $word_dta,
'user_id' => $user_id,
'time_posted' => $time_posted,
'status' => 'Posted'
);
$post_id = $this->basic_model->insertRecord($data_upload, 'forums');
$data = array(
'file_name' => $file,
'data' => $word_dta,
'time_posted' => $time_posted,
'post_id' => $post_id,
'name' => $this->basic_model->getUserData(),
'command' => 'Submit Post'
);
$this->load->view('forum/includes/get_data', $data);
}
add id as imageFieldId to file in html. Then try
var file_data = $('#imageFieldId').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
//formData.append('post_dt', $("#contentbox").html());
$.ajax({.....
I have sorted out my issue I was making a mistake within the controller which was my mistak so I have resolved my issues take care
Ensure your webserver (nginx/apache) upload size limit are correct.
This link could be your reference to set the upload size:
Increase File Upload Size Limit
Edit NginX Conf to Increase File Size Upload

Prevent PHP thumbnail generator response as in ajax

I am trying to upload an image through ajax and needs to get the image URL as response.
code below..
$(".filupldt").on('change',function(){
var file_data=$(this).prop("files")[0];
var form_data=new FormData();
form_data.append("file",file_data);
form_data.append("type",$(this).prev().prev().val());
form_data.append("primerkey",$(this).prev().val());
var element = this;
$.ajax({
type:'POST',
mimeType: 'multipart/form-data',
url:'includes/dealerimg.settings.php?operation=savedealerimgeqtype',
dataType:'json',
async:false,
processData: false,
cache: false,
contentType: false,
data:form_data,
success:function(response){
console.log(response);
//$(element).parent().prev().prev().attr('src',response);
},
});
});
PHP Ajax function
$createthumb = new createthumb();
$todburl = $this->url;
$ajaxtype = $_POST['type'];
$uploads_dir = "../assets/equipmenttype/";
$uniid = uniqid();
$now =date('Y-m-d H:i:s');
$pkid = $_POST['primerkey'];
$ext =pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$filename = $pkid."_".$DealerID."_dealerupdate";
$thumbnamer = $pkid."_".$DealerID."_thumb_dealerupdate_".$uniid.".".$ext;
$tmpname = $_FILES['file']['tmp_name'];
$imagename = $_FILES['file']['name'];
$loc_thumb = $uploads_dir.$thumbnamer;
$createthumb->create_thumb_with_ratio($tmpname,300,300,$loc_thumb); //CREATING THUMB
$createthumb->upload_original(1,$filename,$imagename,$tmpname,$uploads_dir);//for upload original
$thumnametodb = $thumbnamer;
$orinametodb = $filename."_".$imagename;
$data = ['dddd'=>$todburl."assets/equipmenttype/".$thumbnamer];
header('Content-Type: application/json');
echo json_encode($data);
This function working perfectly and creating thumb in my required folder.
But this is an ajax page and I want to show the image name as response.
In this case the ajax response is like below attached image.
How can i solve this issue ?
Thanks
You said that you want to show the image name as response :
Then just
echo $_FILES['file']['name'];
then in your script you get the image name as response with :
success:function(response){
console.log('Image Name = '+response);
}
Your current response is JSON representation (json_encode($data)) & not the image's name.
Probably some output is braking the response data. To be sure that nothing prints on the response page try putting ob_start() and ob_end_clean()
ob_start();
//...
// your code here
//...
$data['dddd'] = $todburl."assets/equipmenttype/".$thumbnamer;
ob_end_clean();
echo json_encode($data);

functions.php script breaks when variable isn't hard coded

I have written a jQuery script that takes a JSON encoded list produced with this function is run in my theme's functions.php and creates a playlist for my jPlayer. However, the script only works when the $file variable is hard coded (for example, OH0400). But I need it to pick up the $file variable based on the page being loaded. But when I switch to this method (using URL), the script says the JSON is null.
I've run the script in multiple ways and the output between the hard coded $file and the variable based $file appear to be the same. Why do I get null when I make the switch?
Here's the PHP in my theme functions.php.
function MyjPlayerList(){
$url = explode( '/', $_SERVER['REQUEST_URI'] );
$file = strtoupper($url[2]);
//$file = 'OH0400';
$filename = '/dir/oralhistory/mp3files/'.$file.'*.mp3';
$FILES = glob( $filename );
foreach( $FILES as $key => $mp3 ) {
$mp3 = str_replace( '/dir/oralhistory/mp3files/', '',$mp3);
$FILE_LIST[ $key ][ 'title' ] = $mp3;
$FILE_LIST[ $key ][ 'mp3' ] = 'http://websiteurl.org/mp3files/'.$mp3;
}
$myjplayerdata = json_encode( $FILE_LIST );
header ( 'Content-type: application/json' );
echo $myjplayerdata;
exit;
die();
};
Here is my javascript:
ajax_player = function() {
jQuery('div#player').load('/js/player.html' , function() {
var cssSelector= {
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
};
var playlist = [];
var options = {
swfPath: "/js/Jplayer.swf",
supplied: "mp3",
smoothPlayBar: true,
keyEnabled: true
};
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);
jQuery.ajax({
url: "/wp-admin/admin-ajax.php" ,
type: "POST",
dataType: "text json",
data: { action: "MyjPlayerList"},
success:(function(data) {
jQuery.each(data, function(index, value){
myPlaylist.add(value); // add each element in data in myPlaylist
console.log(data);
})
})//function (data) close
})//ajax close
})//jquery.load
}//ajax_player
Yes, check the character encoding you're using. That could be the problem.
thanks to the debugging of Marc,turns out that what I get when i run the script in page & what i get when I call the script w/ javascript are different. it's trying to glob admin-ajax.php instead of the URL.

AJAX POST return data not appearing

I have an AJAX call which runs on a form submit (with prevent default to stop standard submit):
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
$('#processingFile').hide();
$('#downloadFile').show();
$('#shareURL').val(data.url);
$('#downloadFile').attr('href', data.url);
$('#aboutFile').html('<b>File URL:</b> ' + data.url + '<br /><b>File Size:</b> ' + data.size + '<br /><b>Time Stamp:</b> ' + data.timestamp + '<br /><b>Client IP:</b> ' + data.ip);
}).fail(function() {
$('#saveFile').hide();
$('#error').show();
});
The file it submits to is a PHP file which is as follows:
// VARIABLES
$fileURL = $_POST['fileURL'];
$tmpURL = substr(md5(rand()), 0, 7);
$deleteCode = md5($tmpURL);
// COOKIE
setcookie($tmpURL, $deleteCode, time()+86400);
// SAVE FILE
if($fileURL){
file_put_contents("tmp/" . $tmpFile, file_get_contents("http://" . $fileURL));
}
// OUTPUT
$result = array(
'url' => "tmp/" . $tmpFile,
'size' => filesize("tmp/" . $tmpFile) * .0009765625 * .0009765625,
'timestamp' => date('H:i:s d-m-Y'),
'ip' => $_SERVER['REMOTE_ADDR']
);
echo json_encode($result);
When the script is run everywhere which uses data.x in the jQuery returns undefined. Any idea why that happens and how to fix it?
data is a string containing your returned JSON text; it isn't an object.
To parse the JSON object, you have a couple of options:
Call JSON.parse() yourself.
Pass dataType: "json" to tell jQuery AJAX to parse it for you.
Set Content-Type: application/json in the server's response so that jQuery knows to parse it for you.
Set dataType: 'json' and check! Look this doc and set your datType.

Tumblr API Posting A Photo from HTML Canvas

I'm having some issues trying to get my code to post the HTML canvas into Tumblr as a photo. I'm using PHP, and the code on the server side is as follows:
if(isset($_POST['postphoto']) and $_SESSION['loggedin']) {
$title = $_POST['title'];
$caption = $_POST['caption'];
tags = $_POST['tags'];
$imageData = $_POST['imageData'];
$imageData = substr($imageData,strpos($imageData,",")+1);
$imageData = str_replace(' ','+',$imageData);
# Set access token
$tumblr->set_token($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$data = array();
$data['post'] = array(
'type' => 'photo',
'generator' => 'AppName',
'data' => $imageData,
'name' => $title,
'caption' => $caption,
'tags' => $tags
);
$response = $tumblr->fetch('http://www.tumblr.com/api/write', $data);
if($response['successful']) {
echo "Update successful!<br><br>";
} else {
echo "Update failed. {$response[body]}<br><br>";
}
}
On the JavaScript side, I have the following:
var imgData = canvas.toDataURL("image/png");
$("#imageData").val(imgData);
imageData is of form type hidden so I simply set the value. The entire form is then posted to the PHP side. I have checked and the values are passed correctly (I did a similar thing for TwitPic, it works since it simply takes in the toDataURL value, but Tumblr is giving lots of issue).
Thanks for the help! :)
It could be because you are posting title to photo posts?
Photo posts don't have title. Let me know if it works when u remove 'name' => $title,.

Categories