PDF is not downloading in FPDF - php

i have a simple form when user submits form i send form data from ajax to controller where my pdf generated code is, but after successful ajax call PDF is not downloading
here is my controller code
$temp=TempInvoice::where('id',$id)->get();
$pdf = PDF::loadView('pages.pdf', ['data'=>$temp]);
$pdf->download('invoice.pdf');
and my javascript ajax
var data2=result
$.ajax({
type: 'POST',
url: '/tyre/api/pdf',
data: {data:j},
success: function (data) {
console.log(data);
},
})
can you please help me with this,
(for normal request it works fine but for ajax request it wont work)
can you please help me with any solution or should i submit form first and then generate pdf?
please let me know any inputs you want from my side,
any tips or comments

Replace this code with $pdf->download('invoice.pdf');
return $pdf->stream('invoice.pdf')
->header('Content-Type','application/pdf');
used stream function with header
The alternative way (As per my comment used return)
$pdf = PDF::loadView('pages.pdf', ['data'=>$temp]);
return $pdf->download('invoice.pdf');
Finally: make sure you you configure package properly. Reference for package configuration

Related

AJAX returning data from a PHP page with code inside

I got the following ajax where I want to send data from a < form > to a PHP page, where the data will be stored in a DataBase and then I will return a password generated in the PHP to the AJAX, but seems that I can't succeed
$.ajax({
type:'POST',
url:'register.php',
data:$('#form_register').serialize(),
});
I'm new to AJAX and every answer I saw was just a PHP page with a few lines of code, it's impossible to use the JSON response in a PHP page with more code?
If you want to return some data from your register.php, you have to output it in this file:
<?php
// register.php
/* Do whatever has to be done here */
echo json_encode(<your data-array here>); // Encode the data you want to return here
In your script where the ajax request is made you have to handle the response from register.php
$.ajax({
type:'POST',
url:'register.php',
data:$('#form_register').serialize()
}).done(function(returnedData) {
// Process the returnedData
});

pjax submit form URL redirection

PJAX's documentation states that Github uses $.pjax.submit() in submitting a Gist form. A desired feature of an ajax form submission which Github nicely implements is that the URL redirects from the form's action to a newly created URL (in this case, one containing the newly server-side created gist ID).
For example, from this:
https://gist.github.com/gists // form action
to this:
https://gist.github.com/tim-peterson/5019589 //assume this ID is generated server side
I've gotten this to work similarly on my site (i.e., the page itself redirects to the equivalent of https://gist.github.com/tim-peterson/5019589) but I can't redirect the URL (it stays like https://gist.github.com/gists).
Is this entirely a server-side issue (setting headers?) or is there something in pjax that I'm missing? I'm using a version of pjax I downloaded today so it can't be that i'm using a buggier version of pjax.
Did you find any solution to this?
I had the similar issue.
Basically you need to set X-PJAX-URL property in response header.
It's value should be same as Request URL.
In Laravel, I did it like this...
App::after(function($request, $response)
{
$response->headers->set('X-PJAX-URL', $request->getRequestUri());
});
There may be a more-elegant / proper way to do this with $.pjax.submit(), but this is the solution I've been using without any problems. I serialize the form inputs prior to submission, then POST them to my server. Then check the reply from the server to make sure I don't need to prevent the user from going forward before calling my PJAX to continue.
$("#save").click(function(e) {
e.preventDefault();
dataString = $("#form").serialize();
$.ajax({
type: "POST",
url: $("#form").attr("action"),
data: dataString,
dataType: "json",
success: function(data)
{
// Handle the server response (display errors if necessary)
$.pjax({
timeout: 2000,
url: data.url,
container: '#main-content'
});
}
});
});
It happens if response HTML doesn't contain initial PJAX container

Upload file using jQuery and Ajax

I have a form that I am sending to the server using jQuery $.post method. I am sending several fields with something like:
var myName = "Pedro";
var myDescription = "Description of Pedro";
$.post("~/insert_user", { name: myName, description: myDescription }, function(data){
alert("Successfully inserted " + data.name + " in DB");
}, "json");
This works great, as I take the values in insert_user.php and treat and insert the in the data base.
What if I need to add a field to my form to let the user upload an image?
How would I do that in my $.post call and how would I get it in the PHP?
I am using Symfony2.0, by the way, just in case it changes something. But the important part is how to add a file typed field to the ajax call.
Thanks in advance.
Pedro
You will find it would be a lot easier to use a pre built jquery plugin. My favourite is uploadify http://uploadify.com.
Its simple and easy to use and it will save you a lot of time trying to figure out a method of your own <>
$.post is the same as the code block bellow. In order for you to do what you need to you need to change it to use this atleast and then things will become simpler. So start by changing the $.post to this
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
Then add a parameter in the ajax block contentType : "multipart/form-data" or try mimeType (cant remember so clearly) and in the data : $("#form").serialize(), that should work.
please tell me if it didn't work
--NEW EDIT LOL-- Excuse my blind coding, you may need to test this
I did a bit more research and came across this. You need to build this array and add it to the data in your ajax block
var files = new FormData($('#fileinputid'));
jQuery.each($('#fileinputid')[0].files, function(i, file) {
files.append(i, file);
});
If what i read was accurate you should be able to pass that array with the rest of the ajax data. Although i am not completely sure how to add it to the serialized data.
Please test this and let me know. if it doesn't work ill do a full javascript script test for you and then post it here
This tutorial might help: Nettuts+: Uploading Files With AJAX
Make iframe and put form in it, submit the form and voila. Or you can use one of these AJAX File upload scripts
I finally used this:
http://malsup.com/jquery/form/#faq
It just works great for what I need.
Thank you guys for your help.

xhr return value from a php page

Ok guys im a bit stuck here. I usually use jquery to do this but i found out it cant be done with jquery so im doing it this way ok so this is my code
var url = ("upload.php?loc="+uplocation);
var xhr = new XMLHttpRequest();
if(xhr.upload){ // check if upload property exists
xhr.open("POST", url, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
And all it does is sends a file to a php page, but the php page doesn't upload the image which isn't what i want, so is their anyway of returning all the contents thats displayed on the page
if it was jquery i would do something like this
$.ajax({
type: "POST",
url: 'json/submitsongs.php',
data: loca,
success: function(data){
alert(data);
}
});
so my question is how to do return what ever is echoed on the php page and alert it(for debugging reasons).
thanks for your help
You would add an event listener for whatever event you desired (load, error, progress, etc). So in your case you would use the 'load' event which signifies that the file has finished loading:
xhr.addEventListener('load', onComplete, false);
The onComplete is your callback function which has the event as a parameter. This event contains the response text:
function onComplete(event) {
alert(event.target.responseText);
}
As of today, u can not upload async using Ajax.
Either use Iframes (like Google) or some nifty Flash (or Java) upload app.
Not sure, but might be HTML5 has a solution for that, but it won't be cross browser.

Calling PHP function when link is clicked

I have a PHP function
function ExportExcel()
{
// code
}
and a link on the page Download in Excel
<a>Download in Excel</a>
So what I want is when users clicks on that link, PHP function would be called and data will be downloaded in excel.
I may need to Ajax for that. How do I go about doing that ?
You could possibly just use a GET statement, so it would look something like this...
HTML
Download in Excel
PHP
function ExportExcel()
{
// code
}
if($_GET['init'])
{
ExportExcel();
}
here is the function i implemeted recently:
$('#toexcel').live("click",function() {
$.ajax({
url: "toExcel.php",
data: "sql="+encodeURIComponent(sql),
beforeSend: function(){
$("#wait").show();
},
complete: function(){
$("#wait").hide();
},
success: function(response){
window.location.href = response.url;
}
});
});
where sql variable actually stores sql query to the server,
and then toExcel.php if getting passed sql, submitting it to the server and outputs the result using PHPExcel() object.
EDIT
i think i understood what you trying to achieve. your ExporExcel() function already outputs the results you need, right? is so, then you can do it as follow:
$('#toexcel').click(function() {
$.ajax({
url: "toExcel.php", // should contain and _call_ you ExportExcel() function
beforeSend: function(){
$("#wait").show(); // this is loading img to show
},
complete: function(){
$("#wait").hide(); ;// this is loading img to hide once complete
},
success: function(response){
window.location.href = response.url;
}
});
});
first let me make sure you know php is only parsed when the page is first being distributed. If you click a link on the page, it has no idea the php function on the same page exists because the function only existed server-side while the code was being parsed. That being said, you can easily make a separate page called download.php and call your function on that page. Then your link can just link to that page.
If you want your custom download page to return to the user as an excel file, you can use custom php headers to convince the browser that it is downloading an excel file. (you'd have to specify the MIME type for excel files)
edit:
this would cause a download to start of an excel file created by your function call and activated by your link click. You don't need any JS or JQuery for this.
edit2:
here's example code for the download file to get you started
<?php
header("Content-type: application/excel");
print($data); /* print out the contents of the excel file here */
exit();
?>
If you do it like this, your php page will not redirect from your original page, but will bring up a download box from the browser instead. If your using csv files instead of xls files, you'll need to change the mime type.
you can handle the request in your js scrpit file
$("a").click(function(){
jQuery.ajax({
url: "path/to/controller",
type: "POST",
dataType: 'json',
data: {'mentod':'ExportExcel'},
success: successCallback,
error:failureCallback
});
});
Just provide link of that excel file in href of anchor , browser will download automatically
If your file form DB then providelink of excel.php , and in excel.php do processing of getting excel file and creation of it .
read this artical..do like that

Categories