I am using ng-file-upload from Github. I have successfully uploaded and added image on both target folder and database. However, I need a specific data from my client side that will be needed for my query.
Controller.js ---- sample snippet of my upload function.
$scope.upload = function (dataUrl, name) {
Upload.upload({
url: 'php/profile-pic.php',
method: 'POST',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Process-Data' : false
},
data: {
file: Upload.dataUrltoBlob(dataUrl, name),
id: user[0].id
},
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
console.log(response);
}, function (response) {
if (response.status > 0) $scope.errorMsg = response.status
+ ': ' + response.data;
console.log(response);
}, function (evt) {
$scope.progress = parseInt(100.0 * evt.loaded / evt.total);
});
}
PHP ---- relative code on my server side
$postdata = file_get_contents("php://input");
$data = json_decode($postdata);
// $id = $data->id;
echo json_encode($data) // returns null
if(!empty($_FILES))
{
$filename = $_FILES['file']['name'];
$destination = '/../images/' . $filename;
if(move_uploaded_file( $_FILES['file']['tmp_name'] , PATH . $destination ))
{
$insertQuery = "UPDATE tblusers SET image = ".$_FILES['file']['name']." WHERE id='???'"; // ??? = the specific data that I need
Image ---- from console.log response
The id is what I need to get for my query.
How can I get that? file_get_contents not working for this one, it returns null.
I got the answer I am looking for.
In my upload function in my controller, I changed the key id into 'id' with apostrophe:
data: {
file: Upload.dataUrltoBlob(dataUrl, name),
'id': user[0].id
}
In my php code, I did this:
$id = $_POST['id'];
I got the idea from Github Repo Issues at the last part of the page.
Related
When I am trying to use the download button to download file in laravel ajax, it is not working properly and I am not able to download file.
Below is my code:
<button type="button" request_id="'.$data->id.'" class="btn btn-success download_request_btn" > Download </button>';
Controller:
public function downloadReport(Request $request)
{
$request_id = $request->request_id;
$downloadReport = Upload::where('id', $request_id)->first();
$upload_report = $downloadReport->upload_report;
$headers = array(
'Content-Type: application/pdf',
'Content-Type: application/docx',
);
$url= url('storage/documents/request/'. $upload_report);
return response()->download($url);
}
Ajax:
$(document).on('click', '.download_request_btn', function(){
var request_id = $(this).attr('request_id');
console.log(request_id);
var formData = new FormData();
formData.append('request_id',request_id);
jQuery.ajax({
type: "post",
url: site_url+"/DownloadAjax",
data: formData,
contentType:false,
processData:false,
success: function (res) {
}
});
});
Just to pseudo-code it up with trusting your data is coming back as desired I think you need to trigger the download in your success callback with a variation of the following (may need to adjust to your need):
$(document).on('click', '.download_request_btn', function(){
var request_id = $(this).attr('request_id');
console.log(request_id);
var formData = new FormData();
formData.append('request_id',request_id);
jQuery.ajax({
type: "post",
url: site_url+"/DownloadAjax",
data: formData,
contentType:false,
processData:false,
success: function (res) {
const data = res;
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', 'yourfilename.extensionType'); // Need to modify filename ...
link.click();
}
});
});
you can pass header to force file type and download
$file_path = storage_path('documents/request/'. $upload_report);
$headers = array('Content-Type'=> 'application/pdf');
return \Response::download($file_path, 'file.pdf', $headers);
here you need to add header based on your file type
ref link https://laravel.com/docs/8.x/responses#file-downloads
if(!empty($fileName) && file_exists(($exportDir.'/'.$fileName))) {
$data = route('yourdownloadCSV',['nameFile' => $fileName]);
}
return response()->json([
'status' => 1,
'data' => $data,
'message'=> trans('messages.item_upload_shop_ok'),
]);
public function yourdownloadCSV($nameFile) {
ini_set('memory_limit', '9072M');
ini_set('MAX_EXECUTION_TIME', '-1');
set_time_limit(10*60);
$fullFolderZipFile = public_path().'/export/'.date('ym');
$filePath = $fullFolderZipFile.'/'.$nameFile;
$nameDownload = "test";
if(file_exists($filePath)) {
$byteS = filesize($filePath);
$mb = number_format($byteS / 1048576, 2) ;
if($mb>10){
$filePathZip= ZipUtil::generateZipFromFile($filePath,$fullFolderZipFile,$nameFile);
$nameDownload .=".zip";
}else{
$filePathZip = $filePath;
$nameDownload .=".".pathinfo($nameFile, PATHINFO_EXTENSION);
}
$mimeType = File::mimeType($filePathZip);
return response()->download($filePathZip,$nameDownload,[
'Content-Type' => $mimeType,
'Content-Encoding' => 'Shift-JIS'
])->deleteFileAfterSend(true);
}
return '';
}
I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}
I have multiple uploads on a page, and I am workin on tidying it up, so:
Here's my js:
$(".img").change(function () {
var form = $(this).closest('form');
getPath(form);
})
deleteButton();
copyGalleryData();
});
function getPath(form) {
var name = $(form).attr('name');
submitImage(form, name);
}
var path_to_delete;
function submitImage(form, name) {
var url = '/image/upload';
var form_data = new FormData($(form)[0]);
submit(name);
form_data.append('img', $(form).children(".img"));
$.ajax({
url: url,
data: form_data,
dataType: 'json',
async: true,
type: 'post',
processData: false,
contentType: false,
success: function (data) {
console.log(data);
$(form).children('.image-container').append('<img id="image" name=' + name + '" src="' + data + '" />')
$(".imageDelete").attr('data', data);
alerts();
var deleting = false;
success(name, deleting, data);
$('.messages').html('<div class="alert alert-success">Image Uploaded!<div>');
},
error: function (data) {
alerts();
fail();
$('.messages').html('<div class="alert alert-danger">File type not supported! Use files with image extension only!</div>');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
and controller:
class ImageController extends Controller
{
use S3;
public function upload(ImgRequest $request)
{
if ($request->hasFile('img')) {
$this->imageEntity();
return response()->json($path);
}
if ($request->hasFile('coverUpload')) {
$this->imageCover();
}
}
public function imageEntity()
{
$s3Path = config('app.path', public_path());
$image = Input::file('img');
Log::info('Retrieving Image', ['image' => $image]);
$filePath = 'public/logo/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$update_image = Entity::find($session);
$update_image->logo = $path;
$update_image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return response()->json($path);
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
public function imageCover()
{
$s3Path = config('app.path', public_path());
$image = Input::file('coverUpload');
Log::info('Retrieving Cover', ['image' => $image]);
$filePath = 'public/cover/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$image = new Images;
$image->path = $path;
$image->cover = true;
$image->entity_id = $session;
$image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return $path;
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
Now the funny thing is response is 200, however it is empty ($path is defined) and ajax is triggering error: part of the code and not success. I have checked the log, and try has been successful:
[2017-10-16 11:22:01] local.INFO: Retrieving Image {"image":"[object]
(Illuminate\Http\UploadedFile: /tmp/phpHPchM4)"} [2017-10-16
11:22:01] local.INFO: Adding to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully added to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully saved logo for {"entity_id":"324"}
Could anyone please help me solve this matter?
Update::
I have updated the controller so that the function returns $path, and main function return the response, however for some reason it is saying that $path is undefined, how to pass data from return to controller that is returned it?
When I trying to return the inserted image as json I'm getting error like Cannot use in operator to search for length
Ajax code:
$("#imagesform").submit(function(){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content')
}
});
$.ajax({
url :"{{url('addImages/').'/'}}" + imagesProductId,
type: 'POST',
data:new FormData($("#imagesform").get(0)),
contentType:false,
processData:false,
success: function (data)
{
//alert(data);
//alert(json.parse(data));
$.each(data, function( index, value ) {
$("#insertedImages").append('<img src="'+value+'" width="75"
height="75" class="upload2"><br>');
alert(value);
});
},
});
return false;
});
Here the images get inserted into db.But while returning to the view and trying to display it with the div tag shows error..(specified above)
Controller:
public function addImages(Request $request,$imagesProductId)
{
$product = Product::create($request->all());
$filenames = array();
if (empty($request->images)) {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
$rules = [
'images'=>'required'
];
$validator = Validator::make($request->all(), $rules);
$result = $validator->fails() ? 'QCFailed' : 'QCVerified';
// echo($result);
foreach ($request->images as $photo) {
$filename = $photo->store('public/uploadedImages');
$filename = substr($filename,22);
$filenames[] = asset('storage/uploadedImages/'.$filename);
ProductsPhoto::create([
'product_id' => $product->id,
'productId'=>$imagesProductId,
'nonliveStatus' => $result,
'filename' => $filename
]);
}
return response()->json($filename);
}
This is my controller function for inserting array of images and I'm returning the same to the view and trying to append it using div tag.
Afternoon guys/gals,
I'm relatively new to using AJAX to POST information to a JSON file and I am not sure what the .php file should look like to process it. I have very little experience with .php. Am I on the right track? I've looked a lot of examples but most of them only have pieces of the .php file to process it. I am trying to inject the "task" into the JSON file which I then use handlebars to read on another page.
function fnCreateTask() {
var url = "save.php";
var title = $("#TaskTitle").val();
var date = $("#TaskDate").val();
var desc = $("#TaskDescription").val();
var info = {
Title: title,
Date: date,
Description: desc
};
var body = JSON.stringify(info);
$.ajax({
type: "POST",
url: url,
contentType: 'application/json',
data: body,
dataType: 'json',
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
}
<?php
$fp = fopen('careers.json', 'w');
fwrite($fp, $_POST = json_decode(file_get_contents('php://input'), true););
fclose($fp);
?>
$.ajax POST (or GET for that matter) data will be x-form encoded by default when sent to the server. You can do
on the client
//object for the data
var data = {
title: $("#TaskTitle").val(),
date: $("#TaskDate").val()
};
$.ajax({
type: "POST",
url: "save.php",
data: data,
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
and on the server
// as a separate object to be safe
$dataobj['title'] = $_POST['title'];
$dataobj['date'] = $_POST['date'];
// write json_encode object to file
file_put_contents ( 'filename.json' , json_encode($dataobj));
To create a JSON in PHP :
<?php
$array = array(
"name" => "toto",
"lastname" => "lafraise",
"age" => 33
);
$fp = fopen('careers.json', 'w');
fwrite($fp, json_encode($array));
fclose($fp);