Show image after button click - javascript

I have a controller method that returns image in byte array, from MongoDB, and I want to show it in my view:
<HttpPost()>
Function ShowImage(id As String) As FileContentResult
Dim Handler = New MongoDBHandler()
Dim newString = id.Replace(vbLf, "").Trim().Replace("""", String.Empty)
Dim byteArray = Handler.ReadImage(newString)
Return File(byteArray, "image/png")
End Function
I have the javascript function:
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr("src", "/MyController/MyMethod/CardNumber");
$("#myModal").append($img);
}
The Table:
When the "Show" button click, on the table, the "No." cell (and is data) is sent to the JS function, and pass to the controller, then i try to create new image element with, and add it to my popup modal for show.
The problem is i cant get the controller response, and spent hours in google search for it, any solutions please?

try following and check if it work. Please verify that the controller name you are specifying in following URL is correct.
I am not sure that your controller name is "MyController". check it and change if it is wrong.
If following code doesn't work, send me the url it generated in comment
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr("src", "#(Url.Action("ShowImage","CreditCard"))/" + CardNumber);
$("#myModal").append($img);
}

Related

Laravel : How can load named route with dynamic arguments by javascript

I have a video player, I want after the end the video to run named route with arguments, I used this code. How can it work correctly?
function play_next() {
var orderId = $('#orderId').val();
var savedVidNum = $('#orderVideo').val();
var url = document.getElementById('player').src;
var filename = url.split('/').pop().split('#')[0].split('?')[0];
filename = filename.split('.').slice(0, -1).join('.')
if (filename < savedVidNum) {
alert('just play next');
} else {
// load route here
orderId = orderId.toString();
savedVidNum = savedVidNum.toString();
window.location.href = "{{URL::to('myroute/3/5')}}"-- -- - here I need to put orderId and savedVidNum
}
}
I see there a form tag under another form tag that's why your post method not working. you need to all HTML form element under one form tag and also need to add the #csrf field.

How to set variable value from javascript to JSP?

I need to draw a table dynamically depending on the data store in a database. When the first web page (validator.jsp) is loaded it goes to a dataBase and returns an ArrayList called cert. (cert hast Description, value, etc).
<% java.util.ArrayList<Certificate> cert = OperacionesVidaDollars.getCertificates();%>
After that when the page finishes loading, a javascript function is called (function drawCertificates). This function will draw as many tables as certificates the ArrayList has.
<script type="text/javascript">
window.onload = drawCertificates;
function drawCertificates(){
alert("page finish loading, staring to draw certificates");
var i;
for(i=0;i<<%=cert.size()%>;i++){
createTable(i);
}
}
</script>
As you can see in the function create table, the variable text is suppost to change depending on i
text = document.createTextNode("<%=cert.get(i).getDescription()%>");
In order to update that variable i, I first call the JSP setVariable, to update the counter and then I try to use it in getDescription like:
text = document.createTextNode("<%=cert.get(request.getAttribute("count")).getDescription()%>");
I have this setVariable.jsp
<%
int num = Integer.valueOf(request.getParameter("number"));
request.setAttribute("count", num);
request.getRequestDispatcher("VidaDollarsCC.jsp").forward(request, response);
Cookie cookie = new Cookie("countCookie",String.valueOf(num));
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
%>
In other JSP (validator.jsp)I have this javascript function who it supposed to change the variable value.
function setVariable(number){
alert("setting the number " + number);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
}
xmlhttp.open("POST", "setVariable.jsp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("number="+number);
}
In the same jsp (validator.jsp) I have this function to createTable(uniqID) where I need that the number is updated depending on the uniqID because I have an ArrayList which has some information that I want to be shown.
function createTable(uniqID){
setVariable(uniqID);
text = document.createTextNode("<%=cert.get(request.getAttribute("count")).getDescription()%>");
}
But is not working. Does someone knows why? How can I solve it? if you have other ideas that I can implement, that also would be great.
I am assuming that your AJAX call is successfully sending number to setVariable.jsp.
1) You have to realize that AJAX call is a different request and is different then the request you have in your validator.jsp page.
2) You cant write JSP expression from Javascript and have it being resolved to HTML since your JSP needs to be reprocessed by server side.
To answer to your question on how to solve this, we need to know what you are trying to do in the first place.
Update:
1) Looks like the uniqID and count are same number. Why not just use uniqID in your javascript.
2) Why not pass certificate description into the createTable too. Like so:
<% java.util.ArrayList<Certificate> cert = OperacionesVidaDollars.getCertificates();
StringBuilder jsCerts = new StringBuilder("[");
boolean first = true;
for (Certificate cr : certs){
if (!first) jsCerts.append(",");
first = false;
jsCerts.append("\"").append( cr.getDescription() ).append("\"");
}
jsCerts.append("]");
%>
<script type="text/javascript">
window.onload = drawCertificates;
function drawCertificates(){
alert("page finish loading, staring to draw certificates");
var certArray = <%=jsCerts.toString()%>;
var i;
for(i=0;i<certArray.length;i++){
createTable(i, certArray[i]);
}
}
</script>
function createTable(uniqID, desc){
setVariable(uniqID);
text = desc;
}
The point here is that you need to write all the necessary data into the HTML to be able to use it in JavaScript, you cant access request attributes from JavaScript.

String manipulation/extract a substring & PDF file produced from a HTML file using iTextSharp, a .NET PDF library for creating the PDF file

I have an issue with using iTextSharp and String manipulation/extract a substring that contains “[number]” and producing the PDF file. My previous question was posted here:
String manipulation & PDF output file
I am using this function to extract the substring that contains "[..]"
<script>
</script>
<script>
function extract() {
var str = "van4[15]";
return str.substring(0, str.lastIndexOf("["));
}
document.getElementById("demo").innerHTML = extract(); </script>
It is a: ASP.Net MVC webpage. The view has a grid with Location , RoomName.... and a checkbox for PDF printing. The records/data on the grid comes from SQL db. This Location field data contains for couple of records at the end "[number]". If the user select the checkbox for one record after clicking on "Print into PDF " button should produce the PDF file.
I am using string contents = System.IO.File.ReadAllText(HTMLFilePath) to read the file where Location, RoomName. It is part of this Html file.
The code behind Print button starts with:
public ActionResult ReportsPDF(PrintFormReportModel Obj) { string HTMLFilePath = Server.MapPath("~/Views/Reports/RoomSignReport.htm");
Where this file RoomSignReport.htm is the one that I am trying to modify by extracting the substring that contains[..] form the Location data ). The task is to extract the substring that contains [number] , the reason why I came up with idea of using the function extract(). Unfortunately using the <script> function extract(..</script> displays at the top of PDF file the content of <script> tag instead of displaying the result here : <p id="demo"></p>
I solve this task by myself. For anyone that might need help with this topic, I am adding the code snippet here:
if (ReportList.Count > 0)
{
PdfWriter writer = PdfWriter.GetInstance(Report, new FileStream(FullPath, FileMode.Create));
Report.Open();
try
{
if (ListRoomSign.Count > 0)
{
foreach (var ObjReportList in ReportList)
{
foreach (var ObjRoomSignList in ListRoomSign)
{
.....
string contents = System.IO.File.ReadAllText(HTMLFilePath);
//Remove square brackets value from room name
if (ObjReportList.Location.Contains("["))
{
ObjReportList.Location = ObjReportList.Location.ToString().Substring(0, ObjReportList.Location.ToString().LastIndexOf("["));
}
//
contents = contents.Replace("[RoomName]", ObjReportList.Location);
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
foreach (var htmlElement in parsedHtmlElements)
{
Report.Add(htmlElement as IElement);
}
Report.NewPage();
}
}
}
Report.Close();
}
catch (Exception)
{
FullPath = string.Empty;
}
}
return FullPath;

Passing a Javascript variable to C# code in <script> section

var code = $('#hastane').val();
var url = '#Url.Action("HataIstatistikleriExcel", "Reports", new
{
baslangicDonem = Model.BaslangicDonem,
bitisDonem = Model.BitisDonem,
hospitalCode = code
})';
window.open(url);
I can't pass code variable to Url.Action... "It shows cannot resolve code"
Quickest way to solve it by adding a placeholder in MVC built URL then replace that value dynamically using javascript while click event is triggered as shown below.
$("#expHastaneAna").click(function () {
var code = 'dynamicCode';
var url = '#Url.Action("HataIstatistikleriExcel", "Reports", new
{
baslangicDonem = Model.BaslangicDonem,
bitisDonem = Model.BitisDonem,
hospitalCode = "{0}"
})';
url = decodeURI(url);
url = url.replace("{0}", code);
url = decodeURI(url);
console.log(url);
});
You cannot directly access Server side variable in JavaScript. First you have to assign it's value to hidden field and then get value from that hidden field in JavaScript.

Oracle APEX & JavaScript - Passing name of textfield in function NOT value

I have a function that will need the Name of a textfield, like P12_ACCOUNT_ID But when I call a function on that page with: callMyFunction('P12_ACCOUNT_ID'); it will pass the value of this textfield on to the function.
Is there a way to create a link to URL which will be javascript, and make P12_ACCOUNT_ID a varchar?
Just to be clear: I want my function to work with the varchar: 'P12_ACCOUNT_ID' and not with the value of that textfield.
This is the function to be called in which I want my page item to be loaded.
The link to this function now is: javascript:callMyPopup('P12_ACCOUNT_ID') but when it retrieves the content of this textfield and doesn't pass the string on by itself.
<script language="JavaScript" type="text/javascript">
function callMyPopup (paramItem) {
var hiddenField = document.getElementById(paramItem).value;
var url;
url = 'f?p=&APP_ID.:3:&APP_SESSION.::::P3_HIDDEN:' + hiddenField;
w = open(url,"winLov","Scrollbars=1,resizable=1,width=800,height=600");
if (w.opener == null)
w.opener = self;
w.focus();
}
</script>
As provided by Jeffrey Kemp but he didn't post an answer and I do want to close this question:
In Apex you can get the value of an item using $v(paramItem).

Categories

Resources