I'm facing the following issue with vue.js2.
After submitting a form, I want to refresh image src.
When the form is submitted, a new image with a chart is generated in the back-end.
This new chart image replaces the old one, however, the URL stays the same.
To update image, I'm using v-bind on image src and bind it to one of the data variables.
The starting image which is displayed before submitting the form is placeholder.jpg.
After receiving a response, I call changeChart method to update it with graph.jpg.
This action works and image is updated
The problem I'm facing here is when I update one of the values and click submit again, the image does not change.
However, when I click clear method first and set chart_url to placeholder.jpg again on next submit, image changes properly.
<v-img
v-bind:src=this.chart_url
</v-img>
<script>
export default {
name: "CenterComponent",
data: function () {
return {
value1: "",
value2: "",
value3: "",
output: null,
chart_url: "http://127.0.0.1:5000/media/pictures/placeholder.jpg",
}
},
methods:{
clear(){
this.value1 = "";
this.value2 = "";
this.value3 = "";
this.output = "";
this.chart_url = "http://127.0.0.1:5000/media/pictures/placeholder.jpg";
},
changeChart(){
this.chart_url = "http://127.0.0.1:5000/media/pictures/graph.jpg"
},
submitForm(){
fetch("http://127.0.0.1:5000/predict",{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
value1: this.value1,
value2: this.value2,
value3: this.value3
})
}
).then(response => {
if (response.ok) {
return response.json();
}
}).then(data => {
this.output = data["prediction"];
this.changeChart();
});
}
},
};
</script>
As you say, the first time you're submitting the form you actually change the url from 'placeholder.jpg' to 'graph.jpg', and on subsequent submits it remains as 'graph.jpg'.
This means that the browser is not going to fetch that image again every time it changes to 'graph.jpg' as it is cached. To make the browser fetch a new image you can try cache-busting by appending a random number to the end of the url in your changeChart method. You're effectively telling the browser that it doesn't have this image, so go fetch it.
changeChart(){
const randomNumber = Math.floor(Math.random() * 1000)
this.chart_url = `http://127.0.0.1:5000/media/pictures/graph.jpg?cachebust=${randomNumber}`
},
This will append a random number between 1-1000, but you could obviously improve this depending on your use case.
Alternatively, create a unique image name on the server when it is processed, and return this new name in the response of the POST call. That way you won't have this issue to start with.
Related
Note: when I upload small size image then the data refreshes and if the image is bigger like 1 mb then it doesn't refresh the data.
I have a add new product modal and when I open it as below:
<NewProduct v-if="showNewProduct" #close-modal="showNewProductModal" #success="showSuccessAlert"/>
and when I add the product and the modal is closed by emitting as below:
Products.addProduct(form)
.then(
this.$emit("closeModal"),
this.$emit("success"),
)
Then in the parent component the data is not refreshed and show the old data and if I refresh the page then it show the new data.
I get data as below in parent component:
data: function () {
return {
showNewProduct: false,
productList: [],
success: false,
};
},
mounted() {
this.getProductList();
},
methods:{
showSuccessAlert() {
this.getProductList(),
this.success = !this.success,
},
showNewProductModal() {
this.showNewProduct = !this.showNewProduct;
},
getProductList() {
User.getProductList()
.then((response) => {
this.productList = response.data;
});
},
}
My goal is that when the modal is closed then the productList should be updated as well with the newly added data without page refresh.
Add product API.
addProduct(form) {
return Api().post("/addProduct", form);
},
It is something related to asynchronous processing. Please, make sure you start fetching record only after the upload is completed.
Products.addProduct(form).then(() => { this.$emit("closeModal")} )
showNewProductModal() { this.getProductList()}
Products.addProduct(form).then(({data: product}) => {
//pass data to close model event
this.$emit("closeModal", product),
this.$emit("success"),
}
showNewProductModal(product) {
this.productList.push(product);
this.showNewProduct = !this.showNewProduct;
}
There is this one thing that is bothering me. I have this one line of code which uses the "v-if" tag, it is used to hide one of the menu items after you've used a setup tool.
The problem here is that when you load up the page, it will display the menu item for half a second first which should be hidden directly from the start. How can I achieve this?
Here is the code:
<li><button v-show="!configCompleted" class="btn" #click="setComponent('setup')">Setup</button></li>
beforeMount lifecycle hook:
beforeMount() {
this.setComponent(this.$route.params.page)
this.user = JSON.parse(localStorage.getItem('vue-laravel-ecommerce. d fuser'))
axios.defaults.headers.common['Content-Type'] = 'application/json'
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('vue-laravel-ecommerce.jwt')
axios.get('/api/shop').then( response => {
if ( response.data.length ) {
this.configCompleted = true
}
});
},
That's because you modify this.configCompleted when you get the response from api, which takes some time. You can probably just set the default value of it to true in data()
data() {
return {
configCompleted: true,
...
}
}
I've set up a treeGrid (the grid is the same) to get data through the ASP.NET WebAPI using their DataManager:
var categoryID=15;
var dataManager = ej.DataManager({
url: "/API/myrecords?categoryID=" + categoryID,
adaptor: new ej.WebApiAdaptor()
});
$("#treeGridContainer").ejTreeGrid({
dataSource: dataManager,
childMapping: "Children",
treeColumnIndex: 1,
isResponsive: true,
contextMenuSettings: {
showContextMenu: true,
contextMenuItems: ["add", "edit", "delete"]
},
contextMenuOpen: contextMenuOpen,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Normal', editMode: "rowEditing" },
columns: [
{ field: "RecordID", headerText: "ID", allowEditing: false, width: 20, isPrimaryKey: true },
{ field: "RecordName", headerText: "Name", editType: "stringedit" },
],
actionBegin: function (args) {
console.log('ActionBegin: ', args);
if (args.requestType === "add") {
//add new record, managed manually...
var parentID = 0;
if (args.level != 0) {
parentID = args.parentItem.TaxonomyID;
}
args.data.TaxonomyID = 0;
addNewRecord(domainID, parentID, args.data, args.model.selectedRowIndex);
}
}
});
The GET works perfectly.
The PUT works fine as I'm managing it manually because it's not called at all from the DataManager, and in any case I want to manage the update of the records in the TreeGrid.
The problem is with DELETE, that is called by the DataManager when I click Delete from the context menu over an item in the TreeGrid.
It makes a call to the following URL:
http://localhost:50604/API/myrecords?categoryID=15/undefined
and obviously, I get a 405 (Method Not Allowed)
The problem is given by the categoryID parameters that break the RESTful schema, and the DataManager is not able to understand that there is a parameter.
A possible solution could be to send this parameter as a POST variable but the DataManager is not able to do it.
Does anyone have a clue of how to solve it? it's a common scenario in real-world applications.
While populating Tree Grid data using ejDataManger, CRUD actions will be handled using inbuilt Post (insert), Put (update), Delete requestType irrespective of CRUD URL’s. So, no need to bind ‘removeUrl’ for deleting records.
And, in the provided code example parameter is passed in the URL to fetch data hence the reported issue occurs. Using ejQuery’s addParams method we can pass the parameter in URL. You can find the code example to pass the parameter using Tree Grid load event and the parameter is retrieved in server side using DataManager.
[html]
var dataManager = ej.DataManager({
url: "api/Values",
adaptor: new ej.WebApiAdaptor()
});
$("#treeGridContainer").ejTreeGrid({
load: function (args) {
// to pass parameter on load time
args.model.query.addParams("keyId", 48);
},
});
[controller]
public object Get()
{
var queryString = HttpContext.Current.Request.QueryString;
// here we can get the parameter during load time
int num = Convert.ToInt32(queryString["keyId"]);
//..
return new {Items = DataList, Count = DataList.Count() };
}
You can find the sample here for your reference.
Regards,
Syncfusion Team
The docs say that I should be able to set the page via DataTablesApiInstance.page(pageNumber), but I can't get it to work.
All the other API methods like search and order seem to work fine.
Here's my code:
$(document)
.on('preInit.dt', (ev, settings) => {
let tableId = ev.target.id;
let tableState = _.get(['datatables', tableId], history.state) || {};
let api = new $.fn.dataTable.Api(settings);
if(tableState.hasOwnProperty('page')) {
api.page(tableState.page); // <-- problem is here; page doesn't get set
}
if(tableState.hasOwnProperty('search')) {
api.search(tableState.search);
}
if(tableState.hasOwnProperty('order')) {
api.order(tableState.order);
}
const setState = (key, value) => {
history.replaceState(_.set(['datatables', tableId, key], value, history.state), '');
};
api.on('page', ev => {
let info = api.page.info();
// console.log('page', tableId, info.page);
setState('page', info.page);
});
api.on('order', ev => {
let order = api.order();
// console.log('order', tableId, order);
setState('order', order);
});
api.on('search', ev => {
setState('search', api.search());
});
});
The method is hit, but the page isn't set. Am I using the wrong API method? Is there another way to set the page before the data loads?
I'm using datatables.net#1.10.12.
If I defer the call to init instead of preInit then the correct page number is highlighted, but the data is still from the first page. If I add a 0ms delay on top of that (as below), it does work, but causes a 2nd data fetch + draw.
if(tableState.page) {
api.on('init', ev => {
setTimeout(() => {
api.page(tableState.page).draw('page');
}, 0);
});
}
How can I set the page without incurring a 2nd ajax request?
You can use displayStart option to define the starting point for data display when using DataTables with pagination as recommended by the author of jQuery DataTables.
It works correctly with table in server-side processing mode and only 1 Ajax request is performed.
var table = $("#example").DataTable({
"processing": true,
"serverSide": true,
"ajax": "/test",
"displayStart": 200
});
From the documentation:
Note that this parameter is the number of records (counting from 0), rather than the page number, so if you have 10 records per page and want to start on the third page, it should be 20 rather than 2 or 3.
This doesn't (directly) answer the question of how to set the page in the preInit, but it solves my problem.
We can use the stateLoadCallback to load the state (including page) from the history API instead of using localStorage as the default implementation does (which will remember the state even when navigating away and then back again).
$.extend(true, $.fn.dataTable.defaults, {
stateSave: true,
stateSaveCallback: (settings, data) => {
let tableId = settings.nTable.id;
if(!tableId) {
// console.warn(`DataTable is missing an ID; cannot save its state`);
return;
}
history.replaceState(_.set(['datatables', tableId], data, history.state), '');
},
stateLoadCallback: settings => {
let tableId = settings.nTable.id;
if(!tableId) {
console.warn(`DataTable is missing an ID; cannot load its state`);
return;
}
return _.get(['datatables', tableId], history.state) || null;
}
});
I have problem very similar to this PDF Blob - Pop up window not showing content, but I am using Angular 2. The response on question was to set responseType to arrayBuffer, but it not works in Angular 2, the error is the reponseType does not exist in type RequestOptionsArgs. I also tried to extend it by BrowserXhr, but still not work (https://github.com/angular/http/issues/83).
My code is:
createPDF(customerServiceId: string) {
console.log("Sending GET on " + this.getPDFUrl + "/" + customerServiceId);
this._http.get(this.getPDFUrl + '/' + customerServiceId).subscribe(
(data) => {
this.handleResponse(data);
});
}
And the handleResponse method:
handleResponse(data: any) {
console.log("[Receipt service] GET PDF byte array " + JSON.stringify(data));
var file = new Blob([data._body], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
I also tried to saveAs method from FileSaver.js, but it is the same problem, pdf opens, but the content is not displayed. Thanks
I had a lot of problems with downloading and showing content of PDF, I probably wasted a day or two to fix it, so I'll post working example of how to successfully download PDF or open it in new tab:
myService.ts
downloadPDF(): any {
return this._http.get(url, { responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' })
}
}
myComponent.ts
this.myService.downloadPDF().subscribe(
(res) => {
saveAs(res, "myPDF.pdf"); //if you want to save it - you need file-saver for this : https://www.npmjs.com/package/file-saver
var fileURL = URL.createObjectURL(res);
window.open(fileURL); / if you want to open it in new tab
}
);
NOTE
It is also worth mentioning that if you are extending Http class to add headers to all your requests or something like that, it can also create problems for downloading PDF because you will override RequestOptions, which is where we add responseType: ResponseContentType.Blob and this will get you The request body isn't either a blob or an array buffer error.
ANGULAR 5
I had the same problem which I lost few days on that.
Here my answer may help others, which helped to render pdf.
For me even though if i mention as responseType : 'arraybuffer', it was unable to take it.
For that you need to mention as responseType : 'arraybuffer' as 'json'.(Reference)
Working code
downloadPDF(): any {
return this._http.get(url, { responseType: 'blob' as 'json' }).subscribe((res) => {
var file = new Blob([res], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}
Referred from the below link
https://github.com/angular/angular/issues/18586
Amit,
You can rename the filename by adding a variable to the end of the string
so saveAs(res, "myPDF.pdf");
Becomes
saveAs(res, "myPDF_"+someVariable+".pdf");
where someVariable might be a counter or my personal favorite a date time string.
This worked for me
var req = this.getPreviewPDFRequest(fd);
this.postData(environment.previewPDFRFR, req).then(res => {
res.blob().then(blob => {
console.clear();
console.log(req);
console.log(JSON.stringify(req));
const fileURL = URL.createObjectURL(blob);
window.open(fileURL, '', 'height=650,width=840');
})
});
Server side (Java/Jetty) : REST service that returns a File Response
The File Response itself will automatically be parsed into a pdf blob file by Jetty (because of the annotation #Produces("application/pdf") ), in other to be send to and read by the web client
#GET
#Path("/download-pdf/{id}")
#Produces("application/pdf")
public Response downloadPDF(#ApiParam(value = "Id of the report record")
#PathParam("id") Long id) {
ResponseBuilder response = null;
try {
PDFReportService service = new PDFReportService();
File reportFile = service.getPDFReportFile(id);
response = Response.ok((Object) reportFile);
response.header("Content-Disposition","attachment; filename="+reportFile.getName());
return response.build();
} catch (DomainException e) {
response = Response.serverError().entity("server.error");
}
return response.build();
}
Client side code (angular 2) : grab the blob and print it in a new browser tab
The key is to insure that you read the request reponse as a blob (as the server returned a blob; in my case)
Now, I tried so hard but I finally figured out that Angular 2 has not implemented any function to handle blob responses (neither res['_body'], nor res.blob() worked for me)
So I found no other workaround than using JQuery ajax to perform that file blob request, like following:
public downloadPDFFile() {
let fileURL = serverURL+"/download-pdf/"+id;
let userToken: string = your_token;
showWaitingLoader();
$.ajax({
url: fileURL,
cache: false,
headers: {
"Content-Type": "application/json",
"Authorization": "Basic " + userToken
},
xhrFields: {
responseType: 'blob' //Most important : configure the response type as a blob
},
success: function(blobFile) {
const url = window.URL.createObjectURL(blobFile);
window.open(url);
stopWaitingLoader();
},
error: function(e){
console.log("DOWNLOAD ERROR :", e);
}
});
}