Ajax image load after dropzone success event - php

So I am using dropzone.js and I want to reload a particular image after the success event of dropzone.
my controller
public function edit($id)
{
$offer = Offer::find($id);
if(!is_object($offer->getMedia('featimgs')->first())){
$offerfeatimg = '/assets/images/offerfeatimg.jpg';
} else {
$offerfeatimg = $offer->getMedia('featimgs')->first()->getUrl('medium');
}
return view('admin.offers.edit')->with(compact('offer', 'offerfeatimg'));
}
so this is where I pass the image to the view:
<div class="panel-body">
<img src="{{ $offerfeatimg }}" class="img-responsive">
#if($offerfeatimg != '/assets/images/offerfeatimg.jpg')
<div class="removebutton">
Izbrisi sliku
</div>
#endif
<form action="/admin/offer/featimg/{{ $offer->id }}" class="dropzone" id="my-awesome-dropzone">
{!! csrf_field() !!}
<div class="dz-message">Prebacite glavnu sliku za ovu ponudu</div>
</form>
</div>
the view:
so I would want to reload this part via ajax after success dropzone event:
<img src="{{ $offerfeatimg }}" class="img-responsive">
#if($offerfeatimg != '/assets/images/offerfeatimg.jpg')
<div class="removebutton">
Izbrisi sliku
</div>
#endif
Any ideas ?

This is assuming a bit about your javascript setup, including jquery. If the dropzone object is available on the form node, you should be able to do something like this in javascript:
var dz = $('form.dropzone').get(0).dropzone;
dz.on("success", function (file, response) {
var imageSrc = ... // add logic here to determine src from server response
$(".img-responsive").attr('src', imageSrc);
if(imageSrc != '/assets/images/offerfeatimg.jpg') {
$(".removebutton").hide();
}
else {
// you may need to edit your html so that this button exists in order to show it
$(".removebutton").show();
}
});
Or you can set up event handlers like this:
Dropzone.options.myAwesomeDropzone = {
... other options ...,
success: function () {
...
}
};
Take a look at handling dropzone events: http://www.dropzonejs.com/#events

Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
parallelUploads: 1,
success: function (file, response) {
var imageSrc = response;
$(".img-responsive").attr('src', imageSrc);
if(imageSrc == '/assets/images/offerfeatimg.jpg') {
$(".removebutton").hide();
} else {
$(".removebutton").show();
}
this.removeAllFiles();
}
};

Related

Images not rendering in blade view after ajax call Laravel 7

I am working on a search filter, fetching data from db through ajax call, text data is rendering but the image is not rendering, the link is also present in console image tag, but not showing in the blade view... if I submit it through form it renders data and images as well, please guide me... Thanks
Here's my blade code:
#if (count($product)>0)
#foreach ($product as $row)
<div class="col-sm-6 col-lg-4 px-2 mb-3">
<div class="card shadow-sm">
<div class="card-img position-relative">
<div class="owl-carousel position-relative">
#if (count($row->images)>0)
#foreach($row->images as $images)
<div> <img class="w-100" height="180px" width="250" src="{{ asset('carchain_private/public/src/uploads/ImagesP'.$row->product.'/'.'u_'. $row->user_id.'/'.'qr_'.$row->id.'/' . $images->name) }}"></div>
#endforeach
#else
<div> <img src="{{URL::asset('src/img-market/car.jpg')}}" alt="image"> </div>
#endif
</div>
<div
class="imgs-num rounded-pill bg-white light-color d-inline-flex align-items-center px-2">
<img class="camera-icon mr-1"
src="{{URL::asset('src/img-market/camera-to-take-photos.png')}}" alt="camera icon">
{{count($row->images ?? '0')}}
</div>
</div>
Here's my controller code:
$product = DB::table('manual_lovers')->select("*")
->leftJoin('users','manual_lovers.user_id','=','users.id')
->leftJoin('location_manual_collectors','manual_lovers.id','=','location_manual_collectors.user_id')
->leftJoin('prices_manual_collectors','manual_lovers.id','=','prices_manual_collectors.user_id')
->select('manual_lovers.*','users.user_type','prices_manual_collectors.price','prices_manual_collectors.currency','location_manual_collectors.address','location_manual_collectors.latitude','location_manual_collectors.longitude')
->get();
if($request->ajax()){
$page = view('marketplace.search_results_append', compact('product'))->render();
return response()->json(array(['page' => $page, 'count' => $count]));
}
here's the ajax call:
<script>
$('#condition,#price_min,#price_max,#year_min,#year_max,#mileage_from,#mileage_to,#location,#latitude,#longitude,#distance_km,#search_make,#model,#search_body,#country,#color,#sort_by').on('change',function(e){
e.preventDefault();
var condition = $('#condition').val();
var price_min = $('#price_min').val();
var price_max = $('#price_max').val();
var year_min = $('#year_min').val();
var year_max = $('#year_max').val();
var mileage_from = $('#mileage_from').val();
var mileage_to = $('#mileage_to').val();
var location = $('#location').val();
var latitude = $('#latitude').val();
var longitude = $('#longitude').val();
var distance_km = $('#distance_km').val();
var search_make = $('#search_make').val();
var model = $('#model').val();
var search_body = $('#search_body').val();
var country = $('#country').val();
var color = $('#color').val();
var sort_by = $('#sort_by').val();
$.ajax({
beforeSend: function(){
$('.ajax-loader').css("visibility", "visible");
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:"{{route('advanced_search')}}",
method:"POST",
dataType:"json",
data:{
condition:condition,
price_min:price_min,
price_max:price_max,
year_min:year_min,
year_max:year_max,
mileage_from:mileage_from,
mileage_to:mileage_to,
location:location,
latitude:latitude,
longitude:longitude,
distance_km:distance_km,
search_make:search_make,
model:model,
search_body:search_body,
country:country,
color:color,
sort_by:sort_by
},
success:function(data) {
// console.log(data);
$('#result_count').html(data[0].count);
$('#search_results_append').html(data[0].page);
},
complete: function(){
$('.ajax-loader').css("visibility", "hidden");
},
});
});
</script>
Here's the console's picture:
Here's the blade's view:

How to pass the button value in ajax url and display the json response in bootstrap panel body?

Laravel View code:
<div class="container" style="display:none;" id="panel1">
<div class="panel panel-default">
<div class="panel-heading" style="color:#0000FF" data-toggle="tooltip" title="Gateways!">
<input type="button" value="Haghway Lite" style="background-color:transparent;border:none;width:100%;height:100%;" name="button1" id="button1"><font size="5"></font>
</div>
<div class="panel-body" align="center">
<img src="haghwaylitecontroller.jpg" width="100" height="100">
</div>
</div>
</div>
This my view code.
Script(ajax):
<script type="text/javascript">
$(document).ready(function() {
$("#button1").click(function(){
var button1 = $(this).val();
if(button1) {
$.ajax({
url: "{{url('panelview').'/'}}"+button1,
type: "GET",
dataType: "json",
success:function(data) {
$.each(data, function(key,value) {
$("#panel1").append('<div "'+ value.panel1 +'"></div>');
});
//alert("success");
}
});
}else{
alert("failed");
}
});
});
In this script code, I calling the ajax function with the button id and trying to pass the value of button to be redirected to the mentioned url and the returned json response to be displayed on the panel body. Here if I am trying to print the button value it alerts NaN
Route:
Route::get('panelview/{button1}','viewController#newProduct');
Controller:
public function newProduct($button1)
{
$users=addModel::select('Desc')->where('Pname',$button1 )->first();;
return json_encode($users);
}
The controller code should fetches the correspoding record based on the value of button and return the response.

How do I customize import file in OroCRM

I want to add a import button in my app to import a file to sever, after that I’ll handle the file by myself. It means I just want to reuse import button and import dialog, but in OroCRM, I have to use processor and importing sevice serve by OroCRM. How can I just use import button and import dialog without using the way OroCRM import file?
Thanks a lots. :)
If you don't want to use OroCrm import. Then you can do it like this process. It might help you.
Follow these steps.
Step.1(index.html.twig)
{% set html %}
{{ UI.dropdownItem({
'path': '#',
'aCss': 'import',
'title': 'Import File',
'label': 'Import File',
'iCss': 'fa-download'
}) }}
{% endset %}
{{ UI.dropdownButton({
'label': 'Import File',
'iCss': 'fa-download',
'aCss': 'pull-right',
'html': html
}) }}
Step.2(in index.html.twig). Create modal section.
{# Modal popup starts here #}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title file-add-h">Select Import File</h4>
<h4 class="modal-title file-report-h" style="display:none;">Import File Report</h4>
</div>
<div class="modal-body">
<div id="file-add">
<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />
<button type="button" class="btn btn-info btn-lg pull-right submit-file">Submit</button>
</div>
<div id="file-report" style="display:none;"> </div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{# modal popup end here #}
Step.3(in javascript file)
{# javascript #}
// Set the target
$(document).ready(function () {
$(".import").attr('data-toggle', 'modal');
$(".import").attr('data-target', '#myModal');
});
// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
var isCompatible = false;
if (window.File && window.FileReader && window.FileList && window.Blob) {
isCompatible = true;
}
return isCompatible;
}
function importFile(flag) {
if (!browserSupportFileUpload()) {
alert('The File APIs are not fully supported in this browser!');
} else {
var data = null;
var file = $('#txtFileUpload')[0].files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {
var csvData = event.target.result;
data = $.csv.toArrays(csvData);
if (data && data.length > 0) {
//console.log(data);
var jsonArr = [];
for (var i = 0; i < data.length; i++) {
if (i !== 0)
{
var json_obj = {};
for (var j = 0; j < data[0].length; j++) {
json_obj[data[0][j]] = data[i][j];
}
jsonArr.push(json_obj);
}
}
$.ajax({
url: '{{path('your_import_controller_path')}}',
type: 'POST',
data: {'data': JSON.stringify(jsonArr), 'flag': flag},
success: function (response, status, xhr) {
alert(response);
}
});
} else {
alert('No data to import!');
}
};
reader.onerror = function () {
alert('Unable to read ' + file.fileName);
};
}
$('#txtFileUpload').val("");
$("#file-report").html("");
$(".file-add-h").show();
$(".file-report-h").hide();
$("#file-add").show();
$("#file-report").hide();
$('#myModal').modal('toggle');
}
$(document).on("click", ".submit-file", function () {
importFile(0);
});
$(document).on("click", ".inser-file", function () {
importFile(0);
});
{# Then in your controller action #}
/**
* #Route("/import",name="your_import_controller_path")
*/
public function importDataAction(Request $request)
{
$import_data = $request->request->get('data');
$flag = $request->request->get('flag');
$import_arr = json_decode($import_data);
$em = $this->container->get('doctrine')->getManager();
$message = '';
foreach ($import_arr as $i) {
$tbl = new EntityTableName(); // in which entity you want to insert
$tbl->setCode($i->CodeA); // CodeA is columns from excel
$em->persist($tbl);
}
$em->flush();
echo 'Records Imported Successfully';
exit;
}

401 Unauthorized DELETE request to RESTful API in laravel via Ajax

I've created a restful API using laravel controllers. I have a PhotosController which has a destroy($id) method for resource deletion. also I have a piece of javascript code that sends a DELETE request to my app. the result should be the deletion of the photo with $id id. but laravel doesn't route my request to destroy method. instead it sends an 401 Unauthorized error.
the thing is that I want to send DELETE request to my app via Ajax, but laravel doesn't let my request to be routed!
routes.php file :
Route::resource('photos', 'PhotosController');
destroy method :
public function destroy($id)
{
try{
unlink($_SERVER["DOCUMENT_ROOT"].'/uploads/doctors/' . $id);
Session::forget('photo');
$msg = Notification::where('flag', 's')->where('code', 'user-update-delete-photo-gallery')->first()->msg;
return Response::json(array('success' => $msg));
}catch (Exception $e){
App::abort(500, $e->getMessage());
}
}
my Ajax request :
$.ajax(
{
url: "/photos/" + name,
method : "DELETE", // Or POST : result is the same
data :{
_token : $("input[name=_token]").val(),
_method : 'DELETE'
},
success: function(data, textStatus, jqXHR ){
parent.replaceWith("");
toastr.success(data['success']);
$("#overlay").hide();
},
beforeSend : function(jqXHR, settings ){
$("#overlay").show();
},
error : function(jqXHR, textStatus, errorThrown ){
toastr.error(jqXHR.responseText);
$("#overlay").hide();
}
}
);
Thanks for your help.
I do this sort of thing all the time in my Laravel Apps with no issues. This code allows the user to delete a resource through AJAX while presenting a bootstrap confirmation dialog first. The code is laid out in the order the events would occur.
VIEW WITH RESOURCE TO DELETE
<a class="delete-plan" href="{{ route('admin.plans.destroy', $plan['id']) }}" data-redirect="{{ route('admin.plans.index') }}" data-plan-name="{{ $plan['name'] }}" data-lang="billing.plans">
<i class="fa fa-trash fa-lg"></i>
</a>
JQUERY TO PROMPT CONFIRMATION MODAL
$('.delete-plan').on('click', function(e) {
e.preventDefault();
var data = {
'route': $(this).attr('href'),
'redirect': $(this).data('redirect'),
'modal_title': 'Delete Plan',
'content_view': 'Are you sure you want to delete plan: <strong>' + $(this).data('plan-name') + '</strong>?',
'lang': $(this).data('lang')
};
loadDestroyModal(data);
});
function loadDestroyModal(data) {
$.get('/ajax/destroy-modal', { data: data }, function(modal) {
$('body').append(modal);
$('#destroy-modal').modal('show');
});
}
AJAX CONTROLLER
// routed by /ajax/destroy-modal
public function destroyModal() {
$data = Input::get('data');
$params = [
'route' => $data['route'],
'redirect' => $data['redirect'],
'title' => $data['modal_title'],
'content' => $data['content_view'],
'lang' => $data['lang']
];
return View::make('_helpers.modal-destroy', $params);
}
DESTROY CONFIRMATION MODAL (_helpers.modal-destroy)
<div id="destroy-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true"><i class="fa fa-times"></i></span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">{{ $title }}</h4>
</div>
<div class="modal-body">
{{ $content }}
</div>
<div class="modal-footer">
<button id="modal-confirm" type="button" class="btn btn-primary" data-route="{{ $route }}"
data-redirect="{{ $redirect }}" data-lang="{{ $lang }}">Confirm</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JQUERY TO PROCESS DESTROY METHOD AND REDIRECT FLASH MESSAGE
$('body').on('click', '#destroy-modal #modal-confirm', function(e) {
var redirect = $(this).data('redirect');
var lang = $(this).data('lang');
$(this).html('<i class="fa fa-spinner fa-spin"></i> Please Wait');
$.ajax({
'url': $(this).data('route'),
'type': 'DELETE',
'success': function(response) {
if (response) {
redirectWithFlashMessage(redirect, 'destroy', 'success', lang);
} else {
redirectWithFlashMessage(redirect, 'destroy', 'errors', lang);
}
}
});
});
PLANS CONTROLLER
public function destroy($id)
{
try
{
Stripe::plans()->destroy(['id' => $id]);
return Response::json(TRUE);
}
catch (Exception $e)
{
return Response::json(FALSE);
}
}
JQUERY FOR REDIRECTION
function redirectWithFlashMessage(redirect, type, status, lang) {
var params = {
type: type,
status: status,
lang: lang
};
$.get('/ajax/flash', params, function(response) {
window.location.href = redirect;
});
}
AJAX CONTROLLER (Redirect with Flash)
public function flashData() {
$message_type = 'success' == Input::get('status') ? 'success' : 'failure';
$message = Lang::get(Input::get('lang'))[Input::get('type') . '_' . $message_type];
Session::flash($message_type, $message);
return ['status' => $message_type, 'message' => $message];
}
It's a lot of code but once setup it's extremely easy to replicate.
I think your system's requiring the authentication for controller action "destroy" method. So you need to login before calling that method.
If you're using the middleware "auth" (app\Http\Middleware\Authenticate.php), you can easy find the "handle" function that returning "Unauthorized" error.
Hope this will help.

Laravel Ajax request returning whole page rather than just data

I'm trying to use ajax to find the next page on my pagination. However it keeps bringing in the whole body. I've taken a print screen to show the problem.
I'm not an expert on ajax show would appreciate some help as to how I can rectify this issue?
My code is below:
public function viewall()
{
$data["projects"] = $projects = Auth::user()->projects()->paginate(3);
if(Request::ajax())
{
$html = View::make('projects.viewall', $data)->render();
return Response::json(array('html' => $html));
}
return View::make('projects.viewall')->with('projects', $projects);
}
Js/js.js
$(".pagination a").click(function()
{
var myurl = $(this).attr('href');
$.ajax(
{
url: myurl,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajax-loading').show();
}
})
.done(function(data)
{
$('#ajax-loading').hide();
$("#projects").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
viewall.blade.php
#extends("layout")
#section("content")
<div class="container">
<h4>Your Projects</h4>
<div id="ajax-loading" class="alert alert-warning" style="display: none;">
<strong>Loading...</strong>
</div>
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
<div class="one-third column" id="projects">
{{ $project->project_name }}
{{ $project->project_brief }}
{{ date("d-m-Y", strtotime($project->start_day)) }}
</div>
#endforeach
#else
<h5 class="errorslist">You have no projects click <a class="errorslist" href="/project/create">here to create a project</a></h5>
#endif
#endif
<div class="sixteen columns">
{{ $projects->links() }}
</div>
</div>
#stop
This line:
$("#projects").empty().html(data.html);
will fill the #project up with your returned html which you created here:
$html = View::make('projects.viewall', $data)->render();
So,you just need to change projects.viewall with only 'partial view' that you want to load.
Probably you don't need to extends your main layout.
But you render a view here:
$html = View::make('projects.viewall', $data)->render();
so html is created by Laravel and then you insert it as html into the #projects domElement.
I experienced this kind of problem, just run
dd( json_decode( json_encode( Products::paginate(5) ), true) );
and can get a hint :)
I have read a solution about this here:
http://www.tagipuru.xyz/2016/05/17/displaying-data-using-laravel-pagination-in-the-html-table-without-page-reload/

Categories