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

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.

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.

Error on javascript queryselector

I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.
Here the main javascript
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.
<input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">
I tried 2 functions call.
document.getElementByName("satisfaction_case_number").value = getParameterByName("case")
and
document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")
I have to say I'm kinda blind here. Any flag would be appreciated.
Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.
I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks
Wait till the window has loaded then execute it;
window.onload = function () {
document.getElementsByName("satisfaction_case_number")[0].value = getParameterByName('case');
}
The form is being dynamically generated after the rest of your content has loaded, It's unreliable to rely on timing as connection speeds can vary, using
window.onload will ensure the page is fully loaded before executing.
I tested this by throttling my browser connection to "Slow 3G" and it still worked, Your original piece of code that selected the element by name wasn't selecting the first entry in the NodeList, to do this you need to add [0] before the .value
You can try document.querySelector('input[id *= satisfaction_case_number]').value = 'example'
setTimeout(function () {
var input = document.querySelector('[id^="satisfaction_case_number"]');
input.value = getParameterByName('case');
input.dispatchEvent(new Event('change'));
}, 1000);
or try to modify the code that creates HubSpot form:
hbspt.forms.create({
// ...
onFormReady: function () {
var input = document.querySelector('[id^="satisfaction_case_number"]');
input.value = getParameterByName('case');
input.dispatchEvent(new Event('change'));
}
});

Show image after button click

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);
}

print or show current value of variable in console.log

With the below; I am attempting to capture form field contents on click of submit button. However when I go to test it and console.log the variable I just get the HTML of the form field. Any pointers. Or I get uncaught reference error, the variable is not defined.
Mark-Up wise: I'm using input type text and input type radios.
$(document).ready(function(){
$('#submitS').click(function(){
var firstName01 = document.getElementById('firstName').value;
var firstName02 = document.getElementById('firstName2').value;
var lastName01 = document.getElementById('lastName').value;
var lastName02 = document.getElementById('lastName2').value;
var iphone01 = document.getElementById('iphone').value;
var android01 = document.getElementById('android').value;
var iphone02 = document.getElementById('iphone2').value;
var android02 = document.getElementById('android2').value;
});
});
Try using .textContent instead of .value

Take Postcode to New Field in New Window

I have a read only field on a html field which has a name of _Dataaddr_postcode I now need to capture this data and pass it into a new window which loads another file (proxcomp.asp) and use the data in a field on this page the field has an ID of inpAddr.
I have this code so far
<script type="text/javascript">
var pcodeStart = document.getElementbyId("_Dataaddr_postcode");
var newWindow;
function makeNewWindow( ) {
if (!newWindow || newWindow.closed) {
newWindow = window.open("../hpwprox/proxcomp.asp","sub","status=0,title=0,height=600,width=800");
setTimeout("writeToWindow( )", 50);
} else if (newWindow.focus) {
newWindow.focus( );
}
}
</script>
<input type="button" value="Create New Window" onclick="makeNewWindow();" />
Can someone tell me how to achieve this with some sample code?
Thanks
Justin.
Passing just that one field as a form input to the server-side script:
var genForm = document.createElement("form");
genForm.target = "sub";
genForm.method = "get"; // or "post" if appropriate
genForm.action = "../hpwprox/proxcomp.asp";
var genInput = document.createElement("input");
genInput.type = "hidden";
genInput.name = "inpAddr";
genInput.value = pcodeStart.value;
genForm.appendChild(genInput);
document.body.appendChild(genForm);
if(!newWindow || newWindow.closed) {
window.open("", "sub", "status=0,title=0,height=600,width=800");
} else if(newWindow.focus) {
newWindow.focus();
}
genForm.submit();
If you wish to use client-side code to set a textbox in the pop-up rather than server-side code, you need to do it from the pop-up window to avoid the delay you would add otherwise and the page's load time from "racing" each other. In JavaScript, global variables are properties of the window object they exist inside of, and window.opener gives the window that opened this one. Note that because of the same-origin policy, the two windows need to have the same protocol, hostname, and port number in their URLs.
// Using the variable referring to the text box:
document.getElementById('inpAddr').value = window.opener.pcodeStart.value;
// Or even using getElementById directly:
document.getElementById('inpAddr').value = window.opener.document.getElementById('inpAddr').value
You can omit the window. part of window.opener if you want to, provided that you are using no variable called opener.
Maybe doing this:
newWindow.document.getElementById('inpAddr').value = pcodeStart;
Or from the open window:
document.getElementById('inpAddr').value = opener.document.getElementbyId("_Dataaddr_postcode").value;
Please read this great article!

Categories

Resources