Show a pdf stream in a new window - javascript

I'm generating in a server a PDF document that I want to show then in the client. The server side looks like following:
ByteArrayOutputStream baos = generatePDF();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=file.pdf");
response.setContentLength(baos.size());
baos.writeTo(response.getOutputStream());
In the client, I have the following code to get retrieve the PDF:
$.ajax({
type: "POST",
url: url,
data: {"data": JSON.stringify(myData)},
success: function(data, textStatus, jqXHR) {
window.open("data:application/pdf," + escape(data));
},
error: function(jqXHR) {
showError("...");
}
});
It looks well, the new window is opened, but the PDF is not shown. It always appears an empty document.
Nevertheless, if the client looks like following, it works fine:
var form = $("<form target='_blank'>").attr({
action : myURL,
method : "POST"
});
var input1 = $("<input type='hidden'>").attr({
"name": "data",
value: JSON.stringify(myData)
});
form.append(input1);
$("body").append(form);
form.submit();
form.remove();
But I can't use the second way cause I need to manage the errors, and I can't do it using form.submit().
Any idea about what's happening with the PDF?

You can get base64 string of your pdf stream and pass it to response.
And your method change
$.ajax({
type: "POST",
url: url,
data: {"data": JSON.stringify(myData)},
success: function(data, textStatus, jqXHR) {
var pdfWin= window.open("data:application/pdf;base64, " + data, '', 'height=650,width=840');
// some actions with this win, example print...
},
error: function(jqXHR) {
showError("...");
}
});

Try using:
dataType: "application/pdf",
success: function(data, textStatus, jqXHR) {
window.open(escape(data), "Title", "");
},

I couldn't do this async, but this js returns the attachment ok for me:
$('<iframe src="url"></iframe>').appendTo('body').hide();
The browser then fires a save/view popup, which is fine for my requirements; no error handling though.
I think with your server side, you might want to return it as inline e.g. response.setHeader("Content-Disposition", "inline; filename=file.pdf");
You're setting the content length OK, it could be the success code will be firing twice, the first time at the beginning of the stream and the second time at the end.
Do let us know if you got this working.

Related

POST file data with AJAX is appending unknown jquery callback string

I'm building a configuration file web editor that lets the user edit settings in a textarea, converts the contents to a Blob file, and then POST the data to a remote API. For some reason, it's appending a random callback parameter and I have no idea where it's coming from...
http://ipaddr:8080/compile?callback=jQuery341029448751790349491588432312011&=1588432312012
Here is what the code looks like. If anyone can point me in the right direction, I would greatly appreciate it.
<script>
$(document).ready(function() {
$('#btnCompile').click(function(event) {
// Convert TextArea contents to a Blob file
var configText = $('#configuration').val();
configText = configText.replace(/\n/g, "\r\n"); // retain line breaks
var configFile = new Blob([configText], { type: "text/plain" });
var documentData = new FormData();
documentData.append('file', configFile, "configuration.cpp");
$.ajax({
url: "http://ipaddr:8080/compile",
method: "POST",
data: documentData,
dataType: 'jsonp',
crossDomain: true,
cache: false,
contentType: false,
processData: false,
success: function(data, textStatus, jqXHR)
{
alert('success: ' + textStatus);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error status: ' + textStatus + ' error message: ' + errorThrown);
}
});
});
});
</script>
You said dataType: 'jsonp' and so your request is subjects to the limitations of JSONP (including being a GET request, putting data in the query string, adding a callback argument, and being unable to set custom request headers).
If you don't want that (and everything about your code indicates you don't), don't use JSONP. It's a dreadful hack with a security risks that was superseded by CORS over a decade ago.

JSON request jumping directly to error statement despite having response data sent from server

Background :
this is a simple ajax request to fetch data from database, my query and server side code works just fine.
Problem :
When i put the GET URL in my browser it shows the correct JSON response, but firebug (Firefox extension) doesn't show any response, and the error message is logged.
alert('success'); doesn't show
$('#loadOrderDetails').click(function () {
var id = document.getElementById("order_id").value;
var dataString = 'order_id=' + id ;
alert(dataString);
$.ajax({
type: "GET",
url: "index.php?route=new/orders/GetOrder",
data: dataString,
cache: false,
dataType: 'json',
success: function (data) {
alert ('success');
// my code to show data in table..
},
error: function (req, status, err) {
console.log('something went wrong', status, err);
}
})
});
any suggestions?
thank you all, it seems that my problem was because of www , i solved it in server settings .

Submit a form using Ajax

First, here is my code :
routes.php
$router->resource('vips','formController');
formController.php (im only posting the concerned function)
public function store(CreateVipRequest $request, Vip $vip, Pool $pool, Url $url)
{
$new_vip = $vip->create($request->except(['srv_hostname', 'srv_ip', 'srv_port','url']));
$pool->fill($request->only(['srv_hostname', 'srv_ip', 'srv_port']));
$url->fill($request->only(['url']));
/* Some more inserts on the database...*/
return redirect()->route('vips.show', [DB::table('vips')->max('id')]);
}
My code submits the form, and after some json requests to a distant Api (and some databases insertions) it redirects to the show view.
Now I want to add a second button that submits the form via Ajax.
Question : Is there a way to use the same function store ? I need it to be able to process both an ajax submit and a normal submit.
Submit form using ajax
$("#form-name").submit(function(ev){
ev.preventDefault();
var formURL = $(this).attr("action");
var postData = $(this).serializeArray();
$.ajax({
url: formURL,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR){
location.reload();
},
error: function(jqXHR, textStatus, errorThrown){
var errResponse = JSON.parse(jqXHR.responseText);
},
});
});
Yes, you can.
In your javascript you can do something like this (assuming you're using jquery):
// if you're using a form
var data = $('form').serialize();
// if data comes from elsewhere
var data = {foo: 'bar', ...};
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function (data) {
// Do something if everything went fine
},
error: function (jqXHR, textStatus, errorThrown) {
// Do something if something went wrong
},
});
Your controller will catch the data coming from the request as you are already doing.

How to show output in a div using partial rendering concept in MVC

I am using render partial concept in MVC. Its not showing the output in div. While debugging everything is OK (Showing Staus 200 OK) but its not going inside success block.Below is my jquery function.
function ShowNavigation() {
var jsonObj = {
'Display': 'Index',
taFormula: $('#taFormula').val()
};
$.ajax(
{
url: "/Home/Index",
type: "POST",
data: jsonObj,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
var message = data.Message;
$("#contentDiv").html(message).val();
}
});
}
My Controller code is:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var val = collection["taFormula"].ToString();
ViewBag.Output = GetValue(val);
return View();
}
Remove the datatype: "json" bit. You're receiving html back from the server, not json data, but because of that setting it's trying to parse it and failing. If you had an error callback function it would go into that.
Also, you don't need the .val() on $("#contentDiv").html(message).val();
Try adding an error handler to the ajax call and see if that gives you any more information:
error: function (xhr, status, error) {
alert(status + " : " + error);
}
Try this for your json object:
data: JSON.stringify(jsonObj),
You might need to include json.js for older browsers.

Why my jQuery ajax call is not successful

I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:
$.ajax({
url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
type: 'GET',
async: false,
dataType: 'application/xml',
data: {id: 43},
success: function(data) {
alert(data);
},
error: function(xhr, status, error){
alert('error happens');
}
})
I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.
I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.
Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?
----------------EDIT---------------
Hi, I changed to use localhost request like:
$.ajax({
url: 'http://localhost:8080/company-interface/the-id',
type: 'GET',
async: false,
dataType: 'xml',
data: {id: 43},
success: function(data) {
alert(data);
},
error: function(xhr, status, error){
alert('error happens');
}
})
But I got the same error... more suggestions please... thank you.
This is possibly due to cross domain access control. You are accessing the site which is on your machine which tries to connect to another website. This is not allowed unless you define Access-Control-Allow-Origin headers.
Also as #Craig said, content type as xml is needs to be changed.
Javascript is subject to the same origin policy. Your script running on localhost can't access COMPANY_DOMAIN.com.
Try Below code :
$.ajax({
url: 'http://localhost:8080/company-interface/the-id',
type: 'GET',
async: false,
dataType: 'text',
data: {id: 43},
success: function(data) {
// Assume response like..
// <note>
// <from>Jani</from>
// <to>Tove</to>
// <message>Remember me this weekend</message>
// </note>
xmlDoc = $.parseXML( data ),
$xml = $( xmlDoc ),
$message = $xml.find("message")
alert($message.text());
$("#xmlResonse").html($message.text());
},
error: function(xhr, status, error){
alert('error happens');
}
})
1302610001570 is for measuring response,
did you checked if the response create valid xml?
change your datatype to application/xml or text/xml
As the other comment suggests, is your URL on another domain? If not then try using relative URL's instead.

Categories