Create PDF with Ajax - javascript

I am using FPDF to create my report.
$pdf = new Report('P','mm','A4', $_POST);
$pdf->AddPage();
$pdf->Output('file.pdf','I');
And I use ajax to make requisition to the PHP.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
window.open(data);
})
I want to show the report in a new tab

I think you should success key. So it would be something like this
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id },
success: function(data){
var blob = new Blob([data]);
window.open(URL.createObjectURL(blob));
}
})

Resolved:
I did the different way:
In my report PHP, I generate one temporay file, passing the parameter 'F'.
$pdf->Output('file.pdf','F');
In Jquery Ajax I opne the file, rather than open the data retorned of ajax request.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
var fileName = "file.pdf";
$('#modalRel').modal('show');
var object = "<object data=\"{FileName}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
object += "If you are unable to view file, you can download from here";
object += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
object += "</object>";
object = object.replace(/{FileName}/g, "../Files/" + fileName);
$("#body-rel").html(object);
})
I hope to have helped who one day to need.

Related

Jquery and AJAX post to php data attribute?

Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});

How to Load a view Codeigniter using post and ajax?

My Javascript Code is like this :
$(".booking_hotel").click(function(){
var id = this.id;
$.ajax({
type: "POST",
url: base_url + 'hotel_booking/hotel/hotel_booking',
data: id
});
});
Function in my controller is like this :
function hotel_booking()
{
$data = $this->input->post();
$data = array(
'hotel_request' => $data,
);
$this->load->view('hotel_booking/booking_hotel_view',$data);
}
It not successful to load view. But in console firebug(tab html), the view could appear.
How to load view booking_hotel_view when class .booking_hotel clicked?
Thank you
The view from ajax comes to you as ajax response. You have to put it in your desired place.
Let you have div with id="my_div" and you want to show your view in this div. So your code will be
$(".booking_hotel").click(function(){
var id = this.id;
$.ajax({
type: "POST",
url: base_url + 'hotel_booking/hotel/hotel_booking',
data: id
}).done(function(response){
$('#my_div').html(response);
});
});
try this. It will reload/redirect to you hotel_booking/hotel/hotel_booking. i.e load your booking_hotel_view
$(".booking_hotel").click(function(){
var id = this.id;
$.ajax({
type: "POST",
url: base_url + 'hotel_booking/hotel/hotel_booking',
data: id
}).done(function(response){
window.location.href = "hotel_booking/hotel/hotel_booking";
});
});
As you doing nothing with your ajax post data you may use as
$(".booking_hotel").click(function(){
window.location.href = "hotel_booking/hotel/hotel_booking";
});

i can't upload images using Ajax

I've been trying to add a new product using ajax and bootstrap (modal) and when I press the save changes button, I get Undefined index in all the fields.
Here's my ajax code:
$('#save').click(function(){
var nombre = $('#nombre').val();
var desc = $('#desc').val();
var precio = $('#precio').val();
var stock = $('#stock').val();
var tipo = $('#tipo').val();
var data = new FormData();
jQuery.each(jQuery('#imagen')[0].files, function(i, file) {
data.append('file-'+i, file);
});
var datas="nombre="+nombre+"&desc="+desc+"&precio="+precio+"&stock="+stock+"&tipo="+tipo;
$.ajax({
url: "php/newproduct.php",
data: {datas, data},
cache: false,
contentType: false,
processData: false,
type: "POST"
}).done(function( data ) {
$('#info').html(data);
viewdata();
setTimeout(function() {
$('#myModal').modal('hide');
}, 500);
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
});
});
data: {datas, data},
doesn't seem to be proper javascript syntax and I don't think you can mix different data object.
You can't mix FormData and an URL encoded string, which in your case isn't event properly encoded and you will have problems, if any of the values contains &.
The easiest way to upload using AJAX would be, if you initialized the FormData object with your form
var data = new FormData($("#form").get(0));
and then just used
data: data,
in your AJAX call
If you really need to add the fields manually, you need to add them to the FormData object
data.append("nombre", nombre);
data.append("desc ", desc);
data.append("precio ", precio);
data.append("stock ", stock);
data.append("tipo ", tipo);

Passing javascript variables to another php page

I have a select list where in using javascript i get the selected values i want this selected values to pass through php file init.php so that i can use those variables in mysql query.
my javascript code is as follows:
$(document).ready(function(){
var e = document.getElementById("product");
var pro = e.options[e.selectedIndex].text;
alert(pro);
});
$('select').change(function(){
var e = document.getElementById("city");
var cit = e.options[e.selectedIndex].text;
alert(cit);
I have used ajax to send variables to init.php. my ajax code below is not working,can anyone tell whats the issue in this code:
$.ajax({
url: 'init.php',
type: 'POST',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(data);
}
});
and in init.php i have written :
<?php
$var1 = $_POST['y'];
$var2 = $_POST['x'];
$result = "Select amount from ". _DB_PREFIX_ ."demo_detail where product = '". $var1 ."' and city = '" . $var2 . "' ";
//echo json_encode($result);
Can you alter the url line to include the / to make sure that you're referring init.php relative to the root of your directory?
So it should look like this:
$.ajax({
url: '/init.php',
type: 'POST',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(data);
}
});
I don't know enough to say for sure but there's a chance that AJAX is making a POST request to the wrong URL.
Have you tried to pass absolute as well as relative path in url. What I mean is
have you tried using:
url:'localhost:xxxx/myapp/init.php'
or
url:'/init.php'
If you're passing variables into the data parameter in Ajax, they don't have to be in quotes.
$.ajax({
url: 'init.php',
type: 'POST',
data: { x: cit, y: pro },
success: function(data) {
console.log(data);
}
});
Use Query String. HTML5's Session Storage can also help you.
Try to replace your script code with following and see if it makes a difference
$(document).ready(function(){
$('select').change(function(){
var e = document.getElementById("product");
var pro = e.options[e.selectedIndex].text;
alert(pro);
var e = document.getElementById("city");
var cit = e.options[e.selectedIndex].text;
alert(cit);
$.ajax({
type: 'POST',
url: 'init.php',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(data);
}
});
});
});

how to get data in the success of ajax

I have the following ajax function:
reader.onload = function(event){
var fd = new FormData();
var Name = encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
console.log("name = " + Name);
fd.append('fname', Name);
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false,
success: function(data){
//console.log(data);
$.ajax({
type: 'POST',
url: 'readFile.php',
data: {"fileName":fileName},
success: function(data){
console.log(data);
}
});
}
});
};
first question: I want to retrieve the data from the second success function to use it later in the code.how could that happen?
second question: the data is an audio file.Is there is a special way to get audio data, or we can get it the same way as any data?In my php server side of the second ajax, I'm reading an audio file and want to use its data.I did simple file open and get contents.does that work for audio files?
server-side code:
<?php
$fileName=$_POST["fileName"];
$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;
This is a bad practice in general, but what you could do is specify a global variable at the start, and then assign data to that variable inside the success. The issue with this is that you can't be certain that the ajax has completed and your variable has been set, before you need to use it.
var mySuccessVar = null;
...
success: function(data) {
mySuccessVar = data;
}
... // later in the code:
if (mySuccessVar != null) {
yourFunction(mySuccessVar);
}

Categories

Resources