Unable to generate pdf in laravel controller - laravel

I had write some sample codes to generate pdf in my laravel controller. It get a 200 response code but the pdf is not generating.
Below is my code.
function exportPDF() {
// instantiate and use the dompdf class
$dompdf = new PDF();
$dompdf->loadHtml('<h1>hello world</h1>');
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
return $dompdf->stream();
}
But this is working when i directly include the code inside route in web.php file.
Route::get('/generate-pdf', function () {
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML('<h1>Test</h1>');
return $pdf->stream();
});
EDITED
web.php
Route::post('/report-audit-export-pdf', 'ReportAuditController#exportPDF');
.js
window.exportPDF = function() {
var hidden_category = $('#hidden_category').val();
$.ajax({
type: "POST",
url: '/report-audit-export-pdf',
data: {
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("jqXHR : " + jqXHR + " and textStatus : " + textStatus + " and errorThrown : " + errorThrown);
},
success: function(content) {
// alert("Success");
}
});
}
May i know what the problem is?

You cannot generate PDFs via Ajax because Ajax requests expect a response, which Laravel sends back as JSON by default. So what you could do, is make a normal GET route that will display the PDF e.g:
Route::get('display-pdf', 'ReportAuditController#exportPDF');
Since your ajax does not POST any data (your data object is empty), you could bypass your ajax request and simply use an anchor
Display PDF
If for some reason, you still want to use Ajax, you can use the success response from the ajax request like this
$.ajax({
type: "POST",
url: '/data-url',
data: {},
success: function(content) {
window.location.href = '/display-pdf';
}
});

Related

Laravel ajax return whole HTML page instead data

I'm having this trouble with the ajax request. This code works on other pages, only on this not working.
I want to call ajax (from different controller - CalendarController) on "show" page from controller ClientController - (http://.../client/35) maybe is that wrong
Client.js
$(document).ready(function() {
$('#events-list').on('click', '.event-popup', function () {
var getEventId = $(this).data('id'); //this line is okay, return dynamic id as i want
$.ajax({
type: "GET",
url: "getEvent/" + getEventId,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json',
})
.done(function (data) {
console.log(data); //if i remove dataType: 'json' whole page will print in log instead data
})
.fail(function(data,jqXHR, textStatus, errorThrown) {
toastr.error("error");
console.log(data,jqXHR, textStatus, errorThrown);
})
});
});
Error message from ajax
parsererror" SyntaxError: Unexpected token < in JSON at position
...
responseText: "<!DOCTYPE html><html lang="sr"><head>... - WHOLE PAGE
web.php
Route::get('/getEvent/{id}', 'CalendarController#getEventData');
CalendarController
public function getEventData($id)
{
$event = Event::findOrFail($id);
return Response::json($event);
}
I added how to Controller looks but does not return data, this ajax call does not come to the controller
I think the problem is somewhere in the URL or because I want to add data with another controller to the show page, but I can't figure
Thanks in advance
EDIT
Ajax request is redirected for some reason
Instead of findOrFail() (it returns HTML if the object doesn't exist), use find() method. Then you can check if the object exists or not and return json as per the condition.
Example:
public function getEventData($id)
{
$event = Event::find($id);
if(!$event) {
return response()->json([
'success' => false,
'message' => 'Not Found'
], 404);
}
return response()->json($event);
}

Errors on the request (forbidden + empty string)

I am new to magento and not so expierenced with ajax. I need to do a ajax request to send the data to the php. I have this code to send the data to the php file:
function Ajax() {
jQuery.ajax({
type: 'POST',
url: "./handler.php",
data: {
source1: catId
},
success: function( data ) {
console.log( data );
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
It seems that the data won't reach the php file. If anyone can help me fix my code, that would be great.
This is JS, so you need the full URL for an ajax request.
url: "http://www.test.com/handler.php",

Submiting Symfony 2 embedded form with file using ajax

I'm creating embedded file uploading form with file validation in Symfony 2. For file uploading I used this example http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html and for embedded forms this http://symfony.com/doc/current/cookbook/form/form_collections.html. It's work perfect, but I must submit a form using ajax, how can I do it?
Below is a example how I submit form using ajax.
$("#submit_form").click(function() {
var $form = $(this).parents('form:first');
var $that = $(this);
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
data: $form.serialize(),
success: function($data) {
if ($data.status == 'ok') {
$that.parents('#lightbox').html($data.template);
}
},
url: $form.attr('action')
});
return false;
});
So the problem is I can't pass files with ajax.
Use this plugin http://malsup.com/jquery/form/ . Works like a charm!
This can submit the form and also upload files. All you need to do is call ajaxSubmit and then implement the method that handles the response.
$('#myForm2').submit(function() {
$(this).ajaxSubmit({success: showResponse});
});
function showResponse(responseText, statusText, xhr, $form) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}

Joomla 2.5 Ajax component not working

I've been trying for ages to get Json working in Joomla and I just can't do it. I think I've tried every combination of URL etc so any help would be great:
this is for the admin side structure looks like
admin
-controllers
--orderitem.php
-views
--orderitem
---tmpl
----orderitem.php
-controller.php
function updateNow(newrefresh) {
var dataJSON = JSON.encode (newrefresh);
var request = new Request.JSON({
method: 'post',
url: 'index.php?option=com_customersitedetails&view=orderitem&task=refreshscreen&format=raw',
data: {
json: dataJSON
},
onComplete: function(jsonObj) {
alert("Your form has been successfully submitted ");
}
}).send();
};
Although runs the alert box it doesn't retun JSON just
View not found [name, type, prefix]: orderitem, raw, customersitedetailsView
Any ideas where I can start? thanks
You're missing views/orderitem/view.raw.php containing a CustomersitedetailsViewOrderitem class.
views/orderitem/view.raw.php
class CustomersitedetailsViewOrderitem extends JViewLegacy
{
public function display($tpl = null)
{
$response = 'Your magic response here';
echo $response;
JFactory::getApplication()->close();
}
}
You can look here for proper ajax call in joomla
How to Write PHP in AJAX
inside your controllers you should have a file "mycall.json.php" this file will process and return a json format of your ajax call
Joomla doesn't gives a build in AJAX as part of it's system. my answer is from Josef Leblanc course in lynda.com
http://www.lynda.com/Joomla-1-6-tutorials/Joomla-1-7-Programming-and-Packaging-Extensions/73654-2.html
As I said :
Write this i the frontend JS :
$.ajax({
type: 'GET',
url: 'index.php',
data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
dataType: 'json',
async: true, // can be false also
error: function(xhr, status, error) {
console.log("AJAX ERROR in taskToggleSuceess: ")
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
},
success: function(response){
// on success do something
// use response.valuname for server's data
}
,
complete: function() {
// stop waiting if necessary
}
});
in the backend you should have a file under com_componentname/controllers/taskname.json.php
the file should look like this
class ComponentnameControllerTaskname extends JControllerLegacy (Legacy only J3.0)
{
public function __construct($config = array())
{
parent::__construct($config);
$this->registerTask('operationname', 'functionname');
}
public function functionname() {
// do something in backend
echo json_encode(array(''var1' => val1, 'var2' => val2 ) );
}
}
nibra - I use this in all my joomla sites and its working perfect. your comment was wrong, pease give me my credit back

Adding autoresize to server side generated textarea using jQuery

Am using a plugin called "jQuery Autosize!" on my textareas. How can i make it autoresize my server side generated textareas because they generated when the page has already loaded.
This is the code that generates the server side textareas. resultErrorObj.node_html contains the server side generated textarea as shown below.
$(document).ready(function() {
$("#postUpdate").submit(function(event){
// setup some local variables
var $form = $(this),
// let's select and cache all the fields
$inputs = $form.find("input"),
// serialize the data in the form
serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.attr("disabled", "disabled");
// fire off the request to /form.php
$.ajax({
url: base_url + "ajax/post_status_update",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
var resultErrorObj = jQuery.parseJSON(response);
if (resultErrorObj.status == 1)
{ $(resultErrorObj.node_html).hide().insertAfter('#activitiesStream').slideDown('fast');
}
else
{
alert(resultErrorObj.error);
}
},
// callback handler that will be called on error
error: function(jqXHR, textStatus, errorThrown){
// the error
alert("Error here " + errorThrown);
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
// prevent default posting of form
event.preventDefault();
});
});
Thank you!
The website for Autosize (http://jacklmoore.com/autosize) shows that you can manually trigger the autosizing.

Resources