Send pdf from python(pyramid) to jquery ajax - javascript

how to send PDF file that can be rendered to jinja2??
write both codes (.py) and (.js) if possible.
here is my ajax code
$("#print").click(function(event) {
$.ajax(
{
type: "POST",
url: "/printledgerreport",
global: false,
async: false,
dataType : 'json',
//contentType : 'application/pdf'
data: {"backflag":0,"accountcode":$("#accountcode").val(),"calculatefrom":$("#calculatefrom").val(), "calculateto":$("#calculateto").val(),"financialstart":sessionStorage.yyyymmddyear1,"projectcode":$("#projectcode").val(),"monthlyflag":false,"narrationflag":false},
beforeSend: function(xhr)
{
xhr.setRequestHeader('gktoken',sessionStorage.gktoken );
},
success: function(data){
window.open("ledgerReport.pdf");
}
});
});
please tell me how to write pyramid code
Now here is my new pyramid code:
#view_config(route_name="printledgerreport", renderer="")
def printLedgerReport(request):
filepath = ("ledgerReport.pdf")
response = FileResponse(filepath)
response.headers['Content-Disposition'] = ("attachment; filename=ledgerReport.pdf")
return response

Try this. I'm on my 5th margarita. It should work. :) Remember to add route for "download_PDF".
#view_config(route_name="download_PDF", renderer="")
def download_view(request):
filepath = ("pathtomyfile/test.pdf")
response = FileResponse(filepath)
response.headers['Content-Disposition'] = ("attachment; filename=test.pdf")
return response
Whoops. This just downloads the file. Maybe you can make it work with jinja. Again. too many margaritas: )

Related

How to show AJAX response data on a website

I'm writting a Spring Boot applicaiton in which I have a website with a submenu with several computer games. When I click on an position in this submenu, I want server to send an image (by image I mean a path to the image) of this game as a response, and after the response comes back to my JS on a website, I want to show it on the website. What I have already done is sending a request to server, and selecting an image based on request data. I don't know how to send a response and use it on my website.
Here is my code:
Java:
#RequestMapping("/change-game")
public String changeGame(HttpServletRequest request, #RequestBody GameData data){
File file;
String game = data.getName();
switch (game) {
//some code which actually works. I removed it to save space
}
request.setAttribute("gameIcon", file);
return "index";
}
JavaScript:
$("#selectGameSubmenu li").click(function(e){
e.preventDefault();
var option = $(this).data("option");
console.log(option + " " + JSON.stringify({"option": option}));
$.ajax({
type: "POST",
url: "http://localhost:8080/change-game",
data: JSON.stringify({name: option}),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
HTML:
<img src="${gameIcon}" alt="${altGameIcon}"
style="width:100px;height:100px" class="gameLogoCenter"/>
I would add a new method that returns only the image path for your AJAX calls to consume.
For example
#ResponseBody
#PostMapping("/change-game-icon")
public String changeGameIcon(#RequestBody GameData data) {
File file;
String game = data.getName();
switch (game) {
//some code which actually works. I removed it to save space
}
return file.toString();
}
and in your JS
$.ajax({
url: '/change-game-icon',
method: 'post', // or "type" if your jQuery is really old
data: JSON.stringify({name: option}),
dataType: 'text',
contentType: 'application/json'
}).done(iconPath => {
$('img.gameLogoCenter').prop('src', iconPath)
})

Javascript Equivalent of Swift HTTPbody

I am looking for a way to put variables in to a AJAX get call, now i know the obvious way to do it would just be to add it too "data" like so
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication', favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});
But this goes to an api and the api also handles request from an iOS app which put the data into httpBody like so
let json: [String: Any] = ["userid":userID, "message":applicationtext.text, "favourid":selectedFavour]
let jsondatatosend = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = "myurl";
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsondatatosend
I believe the reason i did this origionally was it was messing up because of having strange characters in the URL so i had to send it through the body which all worked well, but now im trying to get a website to follow the same method on my api i would like it to be sent in the body from ajax so my php can do this function
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
I understand there are many ways for me to get around it in my php just use $_GET[' var '] instead of file_get_contents when it is sent from the AJAX of my website but i was wondering if there was a way of sending it into the body via ajax so i dont have to change the php file and then it is not sent through url's
so what i want to be able to do is something like this
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication'},
httpBody: {favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});

MethodNotAllowedHttpException when trying to post data to controller via ajax in laravel

I'm trying to send dynamically generated data to controller via ajax in laravel. When user select an option from the dropdown then along with selected option and other data should be sent to controller.
I've tried to send data to controller when an option from dropdown is selected. But every time i try this error,
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
and in the error
REQUEST_METHOD is GET
This is the where i call the ajax function
$(document).on('change', '.route-code-selector', function() {
var selectorID = $(this).attr('id');
addRoutePlanDetails(selectorID);
});
AJAX function
function addRoutePlanDetails(selectorID) {
var routePlanCode = document.getElementById("routeplanno").value;
var driver = $("#selectDriver").val().split('|');
var salesman = $("#selectSalesman").val().split('|');
var router_01 = $("#selectRouter01").val().split('|');
var router_02 = $("#selectRouter02").val().split('|');
var vehicle_no = document.getElementById("enterVehicleNo").value;
var route_code = document.getElementById(selectorID).value;
var date = document.getElementById("date").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: 'addNewRoute',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
}
Route
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
Route::get ('route-plan', 'RoutePlanController#index');
Route::get ('excludePorterRes', 'RoutePlanController#excludePorterRes');
Route::get ('retreiveRouteData', 'RoutePlanController#retrieveRouteCodeData');
Route::get ('retreiveUserData', 'RoutePlanController#retreiveUserData');
Route::get ('retreiveNewRouteData', 'RoutePlanController#retreiveNewRouteData');
Route::post('addNewRoute', [
'uses' => 'RoutePlanController#insertNewRoute',
'as' => 'addNewRoute'
]);
});
controller
public function insertNewRoute(){
$routeplan = new Routeplan;
$user_email = auth()->user()->email;
$routeplan->RouteplanCode = Input::get('routePlanCode');
$routeplan->RouteCode = Input::get('route_code');
$routeplan->DriverID = Input::get('driver');
$routeplan->SalesmanID = Input::get('salesman');
$routeplan->Routercode1 = Input::get('router_01');
$routeplan->Routercode2 = Input::get('router_02');
$routeplan->VehicleNo = Input::get('vehicle_no');
$routeplan->Date = Input::get('date');
$routeplan->Createuser = $user_email;
$routeplan->Status = 'TEMP';
$routeplan->save();
}
when user select an option all the data should be stored in the db.
Try it once
url: '{{ route('addNewRoute') }}',
The issue is here:
url: 'addNewRoute',
here you are calling the route in a wrong manner, use it like:
url: '{{ url('admin/addNewRoute') }}',
you have to call the url() method so that it can create the right url format and don't forget the addNewRoute is grouped under admin, so you have to append that to while calling it.
If ajax method is runs in external javascript file, you should define a url variable in the blade (generally it layout blade.) that using as ajax request url on the ajax call method. (before .js file is loaded);
Example var url = '{{ route('addNewRoute') }}'
$.ajax({
url: url',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
If you using ajax in the blade, you can use directly route as ajax request url.
$.ajax({
url: "{{ route('addNewRoute') }}",
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
You forgot / in your routes.
Route::group(['prefix' => 'admin'], function () {
Add / in admin/
Route::group(['prefix' => 'admin/'], function () {
Then you can try this in your ajax
url: '{{ url('admin/addNewRoute') }}',
or
url: 'admin/addNewRoute',
Try if this will work.
You have used prefix for your routes. So all your route in group will be prefix/uri.
So in ajax call you should url: '{{ url('admin/addNewRoute') }}', and change method to type
$.ajax({
url: '{{ url('admin/addNewRoute') }}',
type: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
In ajax for specifying HTTP Verb use type not method.
if your script is in blade file then use route() to set url in ajax:
$.ajax({
url: '{{route('addNewRoute')}}',
method: 'POST',
dataType: 'json',
...
});
Try this:
Please use url: '{{ route('addNewRoute') }}' instead of url: 'addNewRoute'.
As many of you said.. I changed method to type.. And it still didn't work. But then i looked at laravel logs (storage/logs) and from the logs i found that some of my controller syntax are incorrect. And that's why it still gave me the 500 error. After I changed the syntax and do the corrections. It worked !! Anyways thanks for helping guys! If anyone is getting this error even if your ajax is correct take a look at laravel logs.. Hope this helps someone.

Send form data to client side function to retrieve a page title

I'm attempting to pull the title from the metadata of a URL on the client side so it appears in real time (much like pasting a link on FB / Twitter). However I am struggling to load the url from an input and send the data to a function to make it read on console.log without having to submit the form yet.
Jade
form(method='post' action='/submit', class='plans', id='plans')
.form-group
label Do you have a link?
input.form-control(name='link', type='url', required='required', onchange='scrapeMetadata();', onkeyup='this.onchange();', onpaste='this.onchange();', oninput='this.onchange();')
JS
function scrapeMetadata(link) {
var url = link;
console.log(url)
};
Server-side, have the browser send the url via ajax and display that.
Like in this fiddle: https://jsfiddle.net/mo0qa8yk
function getTitle(url) {
try {
return new window.URL(url).host;
} catch(ex) {
console.error(ex);
return 'N/A';
}
}
window.scrapeMetadata = function () {
var url = $('#url').val();
$.ajax({
type: 'GET',
url: '//jsfiddle.net/echo/jsonp/',
data: {
url: url,
title: getTitle(url) //cheat , the server sould return {title:'...'}
},
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: show_response,
error: function(e) {
console.error(e.message);
}
});
};
show_response = function(obj) {
var result = $('#post');
result.html("");
result.append('<li>' + obj.title + '</li>')
};

Passing Parameters of AJAX POST to Grails Controller

I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.

Categories