I'm trying to get an image stored into a local filesystem. After that, I need to mount an html with this image from javascript.
So far, I'm getting the image with a servlet, and it's actually working as I can show the image in my JSP <img width="120" src="<%=IncVars.getParameter("ruta0")%>myImageServlet">
public class MyImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//get the file image
File image = IncFunctions.getLogoFile();
// Get content type
String contentType = getServletContext().getMimeType(image.getName());
// Init servlet response.
response.reset();
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
// Write image content to response.
Files.copy(image.toPath(), response.getOutputStream());
}
//...
}
I'm trying to do the same to mount the html from a js function, but I can't find the way to generate a html with this image in my js function:
function mountTicket(text, idControl, servletPath){
document.getElementById(idControl).innerHTML = parseTicket(texto, imagePath);
window.print();
}
function parseTicket(texto, servletPath){
var textHtml = "";
//Call the servlet
$.get(servletPath, function(data) {
textoHtml = "<img width='120' src=" + data + "/>";
textoHtml += "<br />";
});
//..
textoHtml += "<div";
if (estilo != ""){
textoHtml += " style=\"" + estilo + "\"";
}
textoHtml += ">" + contenido + "</div>";
return textoHtml;
}
The data var get from the servlet are bytes, and it seems the js doesn't know how to interpret it. I've also tried to pass the path of the image, let's say "C:\myDirectory\myImage.png", but as I expected, it couldn't find it and show it.
Any help would be appreciated. Thanks in advance.
The answer was easier than I thought. I don't need to call the servlet from my js code, I just need to add the image with the servlet path.
Something like this:
textoHtml = "<div><img src='" + servletPath + "'> </div>" ;
And the browser will show the image.
Hope it can help someone with similar "issues"
Related
Part of my index.html contains 3 buttons-anchors like this (There is some bootstrap as well)
Index.html
<a id="category1" href="html/auctionBay.html" class="portfolio-link" >
<a id="category2" href="html/auctionBay.html" class="portfolio-link" >
<a id="category3" href="html/auctionBay.html" class="portfolio-link" >
These buttons redirect me to the auctionBay.html which contains a div
auctionBay.html
<div id="result" class="container"></div>
What i need, is when i press a button from the above, to go to the auctionBay.html and accordingly to what was pressed, print the data from the appropriate table (category1-3) from my database into the 'result' div (it's important to be in the div).
I currently have a servlet that can do this statically when auction.html loads using an ajax call
var j = jQuery.noConflict();
function myFunction() {
j.ajax({
type : 'GET',
url : '../auctionsDisplay',
success : function(data) {
j("#result").html(data);
}
});
}
but only works if i specify the category manually.(antiques=category1 for example)
AuctionDisplay.java
public class AuctionsDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String result = "";
try {
Connection con = DBConnection.getCon();
String category = "antiques";
String query = "select id, name, price from " + category;
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
int i;
result = "";
boolean flag = rs.next();
while (flag) {
result += "<div class='container'><div class='row'><h1 id='antiques' class='category'>Antiques</h1></div><div class='row'>";
i = 0;
while (i < 4 && flag) {
ps = con.prepareStatement("select highestBidder, ends from auctions where itemId=?");
ps.setString(1, rs.getString("id"));
ResultSet rs2 = ps.executeQuery();
rs2.next();
String price = rs.getString("price");
if (rs2.getString("highestBidder") != null)
price = rs2.getString("highestBidder");
result += "<div class='col-md-3' portfolio-item>";
result += "<div class='w3-container w3-hover-shadow w3-center'>" + "<h2>" + rs.getString("name")
+ "</h2><div class='w3-card-20' style='width:100%'>"
+ "<input id='2' type='image' src='../img/portfolio/w3.jpg' data-toggle='modal' "
+ "data-target='#MoreInfo'style='width:90%;'>"
+ "<div class='w3-container w3-center responsive'>"
+ "<p style='padding:5px;'>Highest Bid: " + price + "\u20ac <br> " + "Ends at: "
+ rs2.getString("ends") + "<p></div></div></div></div>";
flag = rs.next();
i++;
}
result += "</div></div>";
}
} catch (Exception e) {
e.printStackTrace();
}
out.println(result);
}
I understand jquery, ajax, get-post requests, javascript (no php please), so how can i achieve what i want ? It's propably simple but it's confusing me
You can achieve what you want in javascript thanks to window.LocalStorage. Since you want your data from one page to be sent to another page(where the browser loads a whole new page which results in the loss of any data retrieved by the last page), via javascript you WILL need to make use of localStorage to get the desired results.
How to?
var j = jQuery.noConflict();
function myFunction(category_id) {
//use this id to fetch your appropriate data
j.ajax({
type : 'GET',
url : '../auctionsDisplay',
success : function(data) {
localStorage.setItem("category_result", data);
}
});
}
j('.portfolio-link').click(function(){
var category_id = this.id //this will give you the pressed <a>'s ID value
myFunction(category_id);
})
//then on document load retrieve the localStorage value you stored.
$(document).ready(function () {
if (localStorage.getItem("category_result") !== null) {
//feed the value to the 'results' div
j('#result').html(localStorage.getItem("category_result"));
}
}
Let me know if this helped
Background - I'm calling a JSON feed via jQuery's AJAX method. No issues here. One of the values in the feed points to an image URL on Instagram and I then render the image in html.
Here's the problem - most of the Instagram URLs come back fine and the image renders on my html page as expected but a couple of URLs return 404 errors and therefore render no image.
My question - is there a way to check for that 404 error and tell the code to do something else?
Code -
var $SS__image = j.mainasset;
$output += '<img src="' + $SS__image + '" />';
What I want to achieve -
var $SS__image = j.mainasset;
if($SS__image.ERROR === '404'){
$output = '';
}else{
$output = '<img src="' + $SS__image + '" />';
}
Is this possible? Thanks in advance!
How about
var $img = $("<img/>");
$img.on("error",function() {
$(this).remove();
});
$output.append($img);
$img.attr("src",$SS__image); // in this order
I have AngularJS application , and I send to download svc file on server like this :
public static void DownloadCSV(string csvFile, string fileName)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment; " +
"filename=" + fileName + ".csv;" +
"creation-date=" + DateTime.Now.ToString() + "; " +
"modification-date=" + DateTime.Now.ToString() + "; " +
"read-date=" + DateTime.Now.ToString());
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Write(csvFile);
HttpContext.Current.Response.End();
}
in client side I send to a webApi function called "exportToCsv" which use DownloadCSV function , in this way :
var p = document.createElement('a')
p.setAttribute('href', "myApp/exportToCsv" )
p.click();
My problem is that I want to present a loading icon to the user untill the file finish to download.
How can I do that?
Prepare an html with a loading icon(.gif probably) that is centered on screen, rest is shadowed maybe;
<div ng-show="loading" ng-include src="'loading.html'" ></div>
On JS side, before download start, set loading to true, when finished set it to false
$scope.loading = false; // when starts
$scope.loading = false; // when finished
I'm using AJAX to add more articles to a list of articles when you press a button. So my AJAX call returns data that includes a title, author and 1 to 3 images associated with the article. Below is the code I'm using to output it, but it feels VERY clunky.
What are the best practices for printing out HTML with JavaScript/jQuery in a scenario like this where I need to add many new tags with new information? Thanks for the help!
Also, I know some of the code isn't super well written because it's a first draft just to make stuff work, so please only answer this question with regards to printing out the HTML or things that will make printing the HTML easier
$j.getJSON(ajaxurl, {action: 'load_articles', issues: $issues}, function(data) {
if (data.message != null) {
alert(data.message);
return
}
list = $j('.all-articles ul');
for (i in data.articles) {
article = data.articles[i];
//Hides articles already on page
if ($j("#" + article.id).size() === 0) {
list.append('<li class="article-preview" id="' + article.id + '">' +
'<h3 class="article-headline">' + article.title + '</h3>' +
'</li>');
current = $j("#" + article.id)
current.append('<p class="authors"></p>');
authors = $j("#" + article.id + " .authors")
for (a in article.authors) {
authors.append(article.authors[a].data.display_name + " ");
}
current.append('<div class="images"></div>');
images = $j("#" + article.id + " .images")
for (i in article.image) {
text = "<div class='image-expand-container'>";
if (i == 0) {
text += ('<img id="' + article.image[i].id + '"class="selected" src="' + article.image[i].medium + '"></img>');
}
else {
text += ('<img id="' + article.image[i].id + '" src="' + article.image[i].medium + '"></img>');
}
text += '<div class="dashicons dashicons-editor-expand"></div></div>';
images.append(text);
}
}
}
There are a few approaches you can take.
As you're doing here, you can return data from your ajax call (e.g. as JSON) and then use a javascript function to generate the corresponding HTML by building strings. This, as you're finding, is often messy.
You can generate the actual HTML on the server side, and have the ajax call return an HTML fragment, which you insert into your DOM. This has the advantage that, if some of your HTML is loading when the page loads, and some is loading via ajax, you can use the same approach (PHP, XSLT, ASP.NET Razor, any kind of server-side templating) to generate all of the HTML.
You can use a javascript templating framework to turn your JSON data into HTML. If all of your HTML is being generated via javascript (e.g. in a single-page application) this may be your best bet.
I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>