ajax - pdf in new tab - ajax

I'm using Laravel. I get a PDF after post method and I make this request with Ajax. How can i display this PDF in new tab when success. When I don't run the codes with Ajax, it works. But when I want to run it with Ajax, I don't know how to display the PDF in a new tab.
I tried returning the PDF but it didn't work. Where am I missing?
Route:
Route::get('/test',[TestController::class, 'pdftest'])->name('test');
My Controller:
$dompdf = new PDF();
$dompdf = PDF::loadView('myPDF', $data);
$customPaper = array(0, 0, 288.64, 419.53);
$dompdf->setPaper($customPaper, 'portrait');
$content = $dompdf->output();
file_put_contents('label2.pdf', $content);
$pdf = new \Clegginabox\PDFMerger\PDFMerger;
$data = base64_decode($r->labelData);
file_put_contents('label1.pdf',$data);
$pdf->addPDF('label1.pdf', 'all');
$pdf->addPDF('label2.pdf', 'all');
return response()->$pdf->merge('browser', 'LABEL'.$order->orderNumber.'.pdf', 'P');
Ajax:
$.ajax({
url:"{{route('test')}}",
type:"post",
data:{
orderId:orderId,
weight:weight,
_token:'{{ csrf_token() }}'
},
success:function(response){
window.open("{{route('test')}}", "_blank");
},
error: function(response) {
console.log(response);
});
}

There is no assurance you can change user settings, it may work in your tests but not in the WildWestWeb. here are different examples.
Here user settings ensure no popups are allowed. I pressed "try it" 10 times and they did NOT open a new tab. Security is set to not allow Window.Open e.g. "Open new window."
Here the user settings in a different browser result in a new window. This is the correct behaviour of Window.Open it is not NewTab.Open
In this poor "Edge case" it may work if the user has not bothered securing the browser and default is open new window in a tab.

Related

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

MVC4: How to force browser's default download dialog when using Ajax

MVC4: goal: when user clicks link : create CSV-file type of data in memory and present user with browser's default download dialog to allow user to save as CSV file on his system.
When using code below: browser's default download dialog does Not display (tested in Chrome and IE). Visually nothing happens as result of user's click on the link.
How to force browser's default download dialog in this case ?
MyView.cshtml
<div>
#Html.Partial("_MyTableView", Model)
</div>
#section scripts{
<script type="text/javascript">
function downloadMyCSV() {
alert("start download"); // pops-up
$.ajax({
type: "POST",
url: "#Url.Action("DownLoadMyCSV", "Home", new { Area ="MyArea" })",
data: {},
traditional: true,
success: function (data) {
alert(data); // shows data as commadelimited string
}
});
}
</script>
}
_MyTableView.cshtml
Download my CSV
HomeController.cs
public FileContentResult DownLoadMyCSV()
{
string csv = "John, Steven, Smith";
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "myreport123.csv");
}
How to force browser's default download dialog in this case ?
Thank you
there are only 2 ways that we have gotten the csv to fire. first was a postback which redirects to the csv download but that isn't ideal. the second way is a link with a blank target. something like this
Download Links(csv)
a new page won't open but the download dialog will be fired. Everything else we attempted would call the method on the controller but the download dialog never showed on the ui. Hope this helps

Prestashop: How to submit data from adminpanel template to Admin Controller?

I'm trying to make a custom page in the adminpanel of Prestashop where the shopowner can fill in his upcoming events that will appear in a column in the header.tpl page. The templates and controller are working so far, with a structure based on an answer here at Stack Overflow:
How to create a new page in prestashop admin panel?
Now I have made in the content.tpl (with the added custom JavaScript and CSS files) the form with the input fields. The next step is to send it to the controller to save it in the database. But I'm stuck this part. I can't find how I can nicely submit the form to the controller. First I tried it with an Ajax function but I couldn't find the right way. Also without Ajax no success.
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseUri + '?rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
data:{
processEvents: true,
ajax: 'true',
controller: 'AdminEvents',
token: static_token
},
//success: function(jsonData){
//}
});
This is an example of an Ajax function that I tried. My questions:
How does other tpl or js files receive the baseUri, where is that
variable set?
What is the function of the ?rand date and time in that line? A kind
of security token?
What is the url of the controller? Also the url when I use
I guess the processEvents : true and Ajax : true is for security
reasons and to check if the form is submitted by Ajax or not?
Why is it necessary to send the controller name?
Where does the token come from?
Questions about the controller:
Which (Prestashop default functions) can or do need to use? For
example:
if (Tools::isSubmit('name')){
etc.
if (Tools::getValue('create_account')){
etc.
Can I use that functions anywhere or maybe only in an Init function?
A lot of questions, feel free to answer only a part of it, I just need a good push in the right direction, searching and reading in the online documentation and on the internet doesn't brought me the solution and brainwashed me a little.
EDIT:
I made a little progress by myself:
Where does the token come from?
What is the url of the controller? Also the url when I use
With the tools getAdminTokenLite and the controller name I generated the controller url:
$token = '?controller=AdminEvents&token='.Tools::getAdminTokenLite('AdminEvents');
The url to post to is the token plus the domain, admin directory and index.php.
With the tool getValue I get the POST data like in PHP with $_POST["name"].
Tools::getValue('event_name')
So its working but I guess it can be better with other Presta default tools.
I know that it's very late to answer you, but for sure it will help other mates with same problem.
Here is an example about how to implement ajax calls in Prestashop 1.6 on Admin panel using ANY Controller from BackOffice (if you want also, you can use ajax.php controller, but I'm using for this AdminImportController() )
tpl part:
$('#mybtn').click(function(e) {
var data = $('#datalist').val();
// Ajax call with secure token
$.post( "{$current|escape:'html':'UTF-8'}&token= {$token|escape:'html':'UTF-8'}",
{ ajax: true, action: "MyFunction", mydata: data } );
  });
And in admin controller side:
public function ajaxProcessMyFunction()
{
// Get param
$mydata = (int)Tools::getValue('mydata');
$answer = 0;
if( $mydata > 0 ) {
$this->importProfList = Db::getInstance()->executeS(
"SELECT * FROM .... LIMIT 1"
);
...
$answer = $someOperationResult;
}
// Response
die(Tools::jsonEncode(array(
'answer' => htmlspecialchars($answer)
)));
}
Tested and working like a charm.
Regards

Magento add to wishlist via ajax is not working with secure url (SSL installed)

I am using magento add to wishlist via ajax
it's working fine but after install SSL on server and make secure magento checkout pages from admin.
It give me not any response from ajax (302 Found).
But if i open this url in new tab then it's working fine.
When i use https in request url then it gives me the following html response "Reload the page to get source for: REQUEST URL" and without https there is no response to display.
here below the code which i used for :-
function additemtowishlist(wId,pId)
{
var wishlisturl = 'wishlist/index/ajaxadd/product/'+pId;
var wishlistparam = '/?wishlist_id='+wId;
var url = '<?php echo Mage::getUrl("",array('_secure'=>false))?>'+wishlisturl+wishlistparam;
new Ajax.Request(url, {
dataType: "json",
onSuccess: function(response){
if (typeof(response.responseText) == 'string') eval('data = ' + response.responseText);
if (typeof data.product_id != 'undefined') {
var htmltoshow = '<div class="messages successmessage"><div class="success-msg"><span>'+data.message+'</div></div>';
jQuery("#wishlistresulthome-"+data.product_id).html(htmltoshow);
jQuery("#customwishlist-"+data.product_id).css('visibility','hidden');
}
else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
}
});
}
Thanks in advance.
Hello Simranjeet you may try this :-
function additemtowishlist(wId,pId)
{
var wishlisturl = 'wishlist/index/ajaxadd/product/'+pId;
var wishlistparam = '/?wishlist_id='+wId;
var url = '<?php echo Mage::getUrl("",array('_secure'=>false))?>wishlist/index/ajaxadd/product/';
new Ajax.Request(url, {
method: 'post',
parameters: {'wishlist_id':wId,'product_id':pId },
onSuccess: function(response){
if (typeof(response.responseText) == 'string') eval('data = ' + response.responseText);
if (typeof data.product_id != 'undefined') {
var htmltoshow = '<div class="messages successmessage"><div class="success-msg"><span>'+data.message+'</div></div>';
jQuery("#wishlistresulthome-"+data.product_id).html(htmltoshow);
jQuery("#customwishlist-"+data.product_id).css('visibility','hidden');
}
else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
}
});
}
I discovered that ajaxToCart has ssl functionality built into it, but if the theme developer was lazy they may have neglected to include the code that tells ajaxToCart that ssl is enabled. I found it in the following code from ajax_cart_super.js.
function ajaxToCart(url,data,mine) {
var using_ssl = $jq('.using_ssl').attr('value');
if(using_ssl==1) {
url = url.replace("http://", "https://");
}
..
..
}
As you can see, ajaxToCart will replace the http with https, but only if there is an element with the class using_ssl and value=1. The developer who made my theme didn't include that element, so when the ajax request points to an unsecure page that should be secure, the ajax response won't work in jquery.
So for me, the quick fix was to just add this element onto my pages. I know this site will always have ssl enabled so I simply hard coded it into my template as shown below.
<input type="hidden" class="using_ssl" value="1" />
Once that was there, the javascript picked up the value and did the replacement. So now it works fine for me by just adding that into the template. If you are a theme developer and you want users to be able to switch this on and off, you may want to check against the settings in the admin. Although you may be on an insecure page, it will tell you if ssl is enabled in the backend, which would require this fix to be added.
I haven't tested the following but I think it would look something like this...
if(Mage::app()->getStore()->isCurrentlySecure()){
echo '<input type="hidden" class="using_ssl" value="1" />';
}
BTW, after years of appreciating stackoverflow solutions, I am making my first post here. Thanks to all contributors, the help is great and I'll try to pay it back now. :)
Try update your javascript url variable, by setting _secure to true value.
please try with below with your wishlist url just change instead of my custom action
Mage::getUrl('',array('_secure'=>true))
I think that gets you the base secure url, I believe.
Mage::getUrl('customer/account/login',array('_secure'=>true))
Will get you to the login page. In other words,
Mage::getUrl('module/controller/action',array('_secure'=>true))

Ajax send parameters through url

I'm new with ajax and thought i'd be a fun experiment to put into my project. I've created my own lightbox type feature to send a message on a website I'm creating. When the user clicks "Send Message", that's when the lightbox appears, and at the top I'm trying to get it to say "Send message to User", where User is the name of the user they're sending a message too. My lightbox html elements are actually on a seperate webpage, which is why I'm using ajax. this is what I have so far, and can't seem to figure out what the problem is:
user.php page
<div id = "pageMiddle"> // This div is where all the main content is.
<button onclick = "showMessageBox(UsersName)">Send Message</button>
</div>
Note: The username passes correctly into the javascript function, I have checked that much.
main.js page
function showMessageBox(user){
alert(user); // where i checked if username passes correctly
var ajaxObject = null;
if (window.XMLHttpRequest){
ajaxObject = new XMLHttpRequest();
}else if (window.ActiveXObject){
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (ajaxObject != null){
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.send("u="+user);
}else{
alert("You do not have a compatible browser");
}
ajaxObject.onreadystatechange = function(){
if (ajaxObject.readyState == 4 && ajaxObject.status == 200){
document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText;
// use jquery to fade out the background and fade in the message box
$("#pageMiddle").fadeTo("slow", 0.2);
$("#messageFormFG").fadeIn("slow");
}
};
}
message_form.php page
<div id = "messageFormFG">
<div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div>
</div>
Note: When accessing this page directly through the URL, giving it a parameter of u and a value, it displays correctly
Use jQuery.ajax();
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
url: "message_form.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
freakish way to do it (old school) :)
anyway i think the problem may be that you are loading an entire html page to a div! meaning tags and stuff, a good way to understand what's wrong would be to use a debugger and see what comes in ajaxObject.responseText.
Hope this helps.
Btw convert to jQuery ajax!! saves you loads of time =)
I believe that you need to add a request header prior to sending your data. So you'd have this:
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObject.send("u="+encodeURIComponent(user));
Instead of what you have.
However, it may be a good idea to allow a library to do this for you. It looks like you already have jQuery loaded, so why not let it handle your AJAX requests instead?
I figured it out after watching some ajax tutorials from bucky :) aka thenewboston. If I'm using the GET method, i just had to add the parameter to the end of the url in the .open function, instead of passing it through the send function (like you would a post method).
if you want to send number of field values using ajax.you can use serilalize function.
Example:
jQuery.ajax({
url: 'filenamehere.php',
type: 'post',
data: $("#formidhere").serialize(),
success: function(data){
..//
}
});

Resources