How to pass values to an external Javascript script from ASP.NET - javascript

I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag... Here is what is in the controller:
public ActionResult KPI()
{
if (Session["OrganizationID"] == null)
{
return RedirectToAction("Unauthorized", "Home");
}
else
{
int orgId;
int.TryParse(Session["OrganizationID"].ToString(), out orgId);
var user = db.Users.Find(User.Identity.GetUserId());
var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
var reports = db.Reports.ToList();
try
{
var org_reports = (from r in reports
where r.OrganizationID == organization.OrganizationID
select r).ToList();
var kpi = new KPI(org_reports);
var jsonKPI = JsonConvert.SerializeObject(kpi);
ViewBag.orgData = jsonKPI;
}
catch (ArgumentNullException e)
{
return RedirectToAction("Unauthorized", "Home");
}
}
return View();
}
From the View I've tried using hidden values, and also just passing them in as parameters when calling the script:
<input type="hidden" id="orgData" value=#ViewBag.orgData>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
I then want to read this value in my JS script and parse it into JSON from the string:
function myFunction(){
var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
var test2 = JSON.parse(orgData); // Doesn't work
}
It doesn't appear that any of these methods are working. What is my mistake here?

You should use Html.Raw, to avoid ASP.NET to escape your value:
orgData = #Html.Raw(ViewBag.orgData);
Also, if this is a Json, it is also a valid JS object, so you don't need to parse, it already is a JS Object.

It looks like you forgot the quotes.
<input type="hidden" id="orgData" value=#ViewBag.orgData>
should be
<input type="hidden" id="orgData" value="#ViewBag.orgData">
Also the code inside your script tag will never get executed because the script tag has a src attribute on it. Code inside script tags with src attributes never gets executed.
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
should be changed to
<script type="text/javascript" src="~/Scripts/KPIs.js" />
<script>
orgData = #ViewBag.orgData;
</script>

I solved it! Pass the KPI model through the view and then it's as easy as:
var orgData = #Html.Raw(Json.Encode(Model));
Thanks to all to offered help.

Related

How to pass laravel request data to java-script if validation failed

laravel Controller
if($validator->failed())
{
return redirect()->back()->with(['errors'=>$validator->errors(),'input'=>$request]);
}
JavaScript file
<script type="text/javascript" >
var registrationErrors = #json($errors);
var input= #json($input);
</script>
In this case registrationErrors it's working fine but input return error like
Action Facade\Ignition\Http\Controllers\ExecuteSolutionController not defined.
If pass only one argument in with() function that should be work fine.
Laravel Controller
if($validator->failed())
{
$data=["errors"=>$validator->errors(),
"input" => $input
];
return redirect()->back()->with('data',$data);
}
Java Script
<script type="text/javascript" >
var data = #json($data);
</script>
My issue is solved, this way is perfectly working

How can I populate an embedded website form with URL parameters using Javascript?

I have a Zoho form embedded on a Squarespace site and I need to populate some fields with URL parameters in Javescript. I'm using the following code to get the parameters:
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
and then to set the parameters to variables:
var campaign1 = getUrlVars()["campaign"];
alert(campaign1);
So that gets the parameter named 'campaign' in the url and assigns it to 'campaign1'. The alert is just to show that it is working, and it is. Then I want to run this:
<script type="text/javascript" src="https://forms.zohopublic.com/....j7Q?campaign="+campaign1 id="ZFScript"> alert(campaign1); </script>
But no matter what I do I can't get that part to reference the variable in the 'src=' section, but I can reference it in the 'alert(campaign1);' immediately after.
I also tried this, which was meant to save the whole URL to a variable named 'site' and just run 'src=site', but that didn't work either.
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1
</script>
<script type="text/javascript"
src=site id="ZFScript"> alert(site);</script>
Your issue is that you are trying to write some js code where it is not parsed/rendered/executed.
The js code will be executed inside <script> tags or onEvent attributes. For instance onclick or onload.
So what you want to do is execute some js code inside a script tag that will generate a script tag with the dynamic src attribute you are trying to achieve. This is a way of doing it:
<script type="text/javascript">
// [...]
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1;
// create a script node
var scriptElement = document.createElement('script');
// set its src attribute
scriptElement.setAttribute('src', site);
// add you new script node to your document
document.body.appendChild(scriptElement);
</script>

How to call external javascript function to ClientSideEvents.Click event?

I have DevExpress().Button on a website which should take specific grid value from a focused row and pass it to external function.
Here is my button:
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnMyName";
settings.Width = 120;
settings.Height = 25;
settings.Text = "MyText";
settings.Styles.Native = true;
settings.ClientEnabled = true;
settings.ClientSideEvents.Click = "function(s, e) { gridView.GetRowValues(gridView.GetFocusedRowIndex(), 'MyValue', OnGetRowValues); }";
}).GetHtml()
I simply can't reach OnGetRowValues function - always get the same exception:
Uncaught ReferenceError: OnGetRowValues is not defined
I have the script in the same folder as my .cshtml file and tried to reference it with <script src=""></script> in relative and absolute way. I tried to put the code to function directly between script tags to the cshtml page but nothing works and I get always the same error. The only solution which so far worked was to put the entire script as assingment to ClientSideEvents.Click but because the OnGetRowValues function is big, it will become messy and downright unpractical solution. Any help will be appreciated.
Go through Client-Side Events documentation and implement using below example:
<script type="text/javascript" src="~/Content/js/index.js"></script>
<script type="text/javascript">
function ButtonClick(s,e)
{
gridView.GetRowValues(gridView.GetFocusedRowIndex(), 'ShipName', OnGetRowValues);
}
</script>
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnGetSelectedRowValue";
settings.UseSubmitBehavior = true;
settings.ClientSideEvents.Click = "ButtonClick";
}).GetHtml()
#Html.Action("GridViewPartial")
index.js
// Value contains the "EmployeeID" field value returned from the server, not the list of values
function OnGetRowValues(Value) {
// Right code
alert(Value);
// This code will cause an error
// alert(Value[0]);
}
Hope this help..

Posting form values securely from one page to another on client-side using pure Javascript and NO server-side technology

I need to POST form values from one page to another using Javascript.
Now, I know that I could use a server-side technology like ASP.Net or PHP to post values but I am not allowed to use any server side script.
I am aware that using the GET method, I can pass the form values as a query string but the values will not be passed securely (which is an important requirement!)
The conditions listed below:
This code should take the values that are posted to the page and
repost to target page. HTTP POST only (not get).
In no cases, even error, the request should not stop on this bridge page.
The script needs to handle multiple posted values.
Try to use standard javascript (no 3rd party library)
Script needs to work in IE, FF, Safari, most standard browsers
Can anyone please help me find a solution to this or point me to some resource that will help me find the soln? Thanks in advance. Below is the code for passing values as a query string. Can I modify this so that my above requirements are satisfied?
FORM
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function goto_page(page) {
var usbnum = document.getElementById('usbnum').value;
var usbcode = document.getElementById('usbcode').value;
var q_str = '?usbnum=' + usbnum + '&usbcode=' + usbcode;
var url = page + q_str;
window.location = url;
}
</script>
</head>
<form id="form1" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text" size="80" /><br />
USB Code: <input name="usbcode" id="usbcode" type="text" size="80"/>
</div>
Next
</form>
</body>
</html>
BRIDGE PAGE
<html>
<head>
<title>Bridge Page</title>
<script type="text/javascript">
function get_params() {
var url = window.location.href;
var q_str_part = url.match(/\?(.+)$/)[1];
var val_pairs = q_str_part.split('&');
var params = {};
for (var i = 0; i < val_pairs.length; i++) {
var tmp = val_pairs[i].split('=');
params[tmp[0]] = typeof tmp[1] != 'undefined' ? tmp[1] : '';
}
return params;
}
function write_params() {
var params = get_params();
var txt = 'Hello ';
for (var i in params) {
txt += params[i] + ' ';
}
var body = document.getElementsByTagName('body')[0];
body.innerHTML += txt;
}
function write_params() {
var params = get_params();
var num_container = document.getElementById('usbnum');
var code_container = document.getElementById('usbcode');
num_container.innerHTML = params.usbnum;
code_container.innerHTML = params.usbcode;
}
</script>
</head>
<body onLoad="write_params()">
</body>
</html>
POST data can only be handled by server side code. There is no way you can use them in your javascript without help from a server side code.
You can only use GET or you can think about cookies. But at other hand, why do you want to change current page?! you can use AJAX to load more data without refreshing and no need of posting or getting variables.

How to access javascript value in a4j

I need to set a Bean value with one javascript return value.
Something like:
<script type="text/javascript">
function getUserId(){
return 4;
}
</script>
<h:inputText name="lala" value="getUserId()"/>
Thanks
I solved it.
I was using a:jsFunction tag as it follows:
<script type="text/javascript">
function getUserId(){
var user = MyCompany.get_User();
return user;
}
</script>
<a:jsFunction action="#{user.performLogin()}" name="doSiteLogin" >
<a:actionparam name="uid" value="getUserId()"/>
</a:jsFunction>
If you use the property noEscape="true" on the a:actionparam ... it call your javascript code.

Categories