how to pass a variable from vb to javascript - javascript

I have server-side VB code to retrieve an access_token and save it in the session. I want to make the token available client-side so I can use it to send an ajax request.
I tried to set the token in a hidden field. This works. The token shows in the field when I check via the browser dev tools.
I then tried to get the hidden field value in javascript with getHiddenValue(). This does not work. getHiddenVaue() does not execute. But when funciones.RedirigiraUsuario() is commented out, getHiddenValues() works.
RedirigiraUsuario() has a switch case to redirect a view depending on the profile
The vb code to set the token looks like this:
Dim url As String = funciones.getPropiedad(Me.Page, "urlWebApi") &
"recuperarToken"
Dim data As New NameValueCollection()
data.Set("grant_type", "password")
data.Set("username", funciones.reemplaza_caracteres(txt_login.Text))
If ViewState("ESADMIN") Then
data.Set("password", NegUsuario.get_GEN_claveUsuarios())
Else
data.Set("password", contraseƱa)
End If
data.Set("clientid", "2")
'data.Set("idperfil", "63")
Dim sJson As String = funciones.ObtenerJsonWebApi(url, data)
If Not sJson = Nothing Then
Dim json As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(sJson)
Session("TOKEN") = "Bearer " + json("access_token")
'setting the token in hidden field
inputToken.Value = "Bearer " + json("access_token")
'here is the problem, this does not works, maybe the postback is the guilty
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ShowStatus", "javascript: getHiddenValue();", True)
End If
funciones.RedirigiraUsuario(Me)
Javascript code :
<script type="text/javascript">
$(document).ready(function () {
$('#div_login').hide();
$('#div_login').fadeIn(1500);
document.getElementById('div_login').scrollIntoView();
});
function incorrecto() {
$("#div_login").addClass('go');
}
function getHiddenValue() {
console.error("asdasdasdasda")
let hdnField = document.getElementById('<%= inputToken.ClientID %>').value;
showNotificacion("asdas",'info', 'center', 'top',200)
localStorage.setItem("PabToken", hdnField)
sessionStorage.setItem("PabToken", hdnField)
return true
}
</script>
How can I execute the getHiddenValue() function before postback, or get the token saved in the server-side?
Edit
Public Shared Sub RedirigiraUsuario(ByRef pagina As Page)
Select Case pagina.Session("PERFIL")
Case "1", "2", "3", "4", "5", "N"
pagina.Response.Redirect("~/Default.aspx")
Case "6"
pagina.Response.Redirect("~/FormMantenedor/MAN_JefeEspecialidad.aspx")
Case "7"
pagina.Response.Redirect("~/BUS_General.aspx")
Case "8"
pagina.Response.Redirect("~/FormPabellon/GST_Detalle_Post_Anestesia.aspx")
Case "9"
pagina.Response.Redirect("~/FormTabla/ING_Tabla.aspx")
Case "10", "11", "12", "15"
pagina.Response.Redirect("~/FormPreTabla/GST_Pre_Tabla.aspx")
Case "14"
pagina.Response.Redirect("~/GST_Camas.aspx")
Case "13"
pagina.Response.Redirect("~/FormPabellon/REP_Pabellon.aspx")
End Select
End Sub

I'm not sure. I need to repeat this: I'm not sure.
But my best guess is the problem is this line:
document.getElementById('<%= inputToken.ClientID %>')
What I think is happening is if funciones.RedirigiraUsuario(Me) results in a redirect, the <%= inputToken.ClientID %> expression will not resolve correctly.
To fix this, you need to set the clientID somewhere the javascript will be able to retrieve it before doing anything might cause a redirect.
The other potential issue is the reliance on ScriptManager.RegisterStartupScript(). It's possible a redirect will have the effect of resetting the script manager.
I think it's likely both issues are in play.
At very least you should be able to use the browser dev tools to find the function: does it have the correct clientID? Is it there at all?
Unfortunately, it's been far too long since I used Web Forms regularly. My recollection of how that all fits together is no longer clear, so this is as much help as I can give.

Related

VBA XMLHTTP request doesn't capture dynamic HTML response

I am trying to get a specific dynamic figure from a webpage to excel, I managed to gather all the website get response into a "all" variable which I am supposed to parse to extract my numbers, except for when I check the string variable I can see everything but the required dynamic figure! :) "the attached phot shows the dynamic figure at the very instant was 2.19",
any ideas why I am capturing every thing, would be much appreciated, Thanks in advance
My thoughts:
1.I am guessing is the figures are injected by JavaScript or a server side that might be executing after my XMLHTTP request is processed maybe! if this is the case or else I need your expertise
the website doesn't response unless it sees a specific Html request header, so I might need to mimic the headers of Chrome, I don't know how they look like?
Please see below my code and a screenshot for the figure I would like to capture
'Tools>refrences>microsoft xml v3 must be refrenced
Public Function GetWebSource(ByRef URL As String) As String
Dim xml As IXMLHTTPRequest
On Error Resume Next
Set xml = CreateObject("Microsoft.XMLHTTP")
With xml
.Open "GET", URL, False
.send
GetWebSource = .responseText
End With
Set xml = Nothing
End Function
Sub ADAD()
Dim all As Variant
Dim objHTTP As Object
Dim URL As String
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
all = GetWebSource("https://www.tradingview.com/symbols/CRYPTOCAP-ADA.D/")
pos = InStr(all, "tv-symbol-price-quote__value js-symbol-last")
testString = Mid(all, pos, 200)
'I am supposed to see the dynamic figure within the TAG but it is not showing!!
Debug.Print testString
End Sub
HTML for Dynamic Required values
#Tim Williams This is a code using selenium (But it seems doesn't do the trick of getting the value)
PhantomJS Selenium VBA
Sub Test()
Dim bot As Selenium.PhantomJSDriver
Set bot = New Selenium.PhantomJSDriver
With bot
.Get "https://www.tradingview.com/symbols/CRYPTOCAP-ADA.D/"
.Wait 2000
Debug.Print .FindElementByXPath("//div[#class='tv-symbol-price-quote__value js-symbol-last']").Attribute("outerHTML")
End With
End Sub
Chrome VBA Selenium
It seems using PhantomJS doesn't work properly, so here's a Chrome version of selenium in VBA
Private bot As Selenium.ChromeDriver
Sub Test()
Set bot = New Selenium.ChromeDriver
With bot
.Start
.Get "https://www.tradingview.com/symbols/CRYPTOCAP-ADA.D/"
Debug.Print .FindElementByXPath("//div[#class='tv-symbol-price-quote__value js-symbol-last']").Text 'Attribute("outerHTML")
.Quit
End With
End Sub
Python Solution
And this is the working python code that my tutor #QHarr provided in comments
from selenium import webdriver
d = webdriver.Chrome("D:/Webdrivers/chromedriver.exe")
d.get('https://www.tradingview.com/symbols/CRYPTOCAP-ADA.D/')
d.find_element_by_css_selector('.tv-symbol-price-quote__value.js-symbol-last').text

Two Different Javascript Alerts before redirecting in ASP.NET

I want to show different alert messages using JavaScript. Here is my code, but my alert box will not show before the redirect. I tried the other examples provided but those are all using just one type of alert message. I use this ShowAlertMessage method to show other types of warnings as well, in which I don't want to redirect to any other page. Just give the user a warning.
If (user creates a new work order)
{
ShowAlertMessage("Property work order " + txtWorkOrderNumber.Text + " created successfully");
}
else
ShowAlertMessage("Property work order updated successfully");
Response.Redirect("~/DashBoard.aspx");
public static void ShowAlertMessage(string msg)
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
string script = "alert(\"'" + msg + "'\");";
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", script, true);
}
}
You're sending a Response.Redirect, which means your response does not have any content, but rather just the URL to redirect to.
In order to do what you're trying to do, you'd have to write out the javascript to the current page, then once the alerts fire, use javascript to move to a new URL.
Maybe something like the following:
string script = string.Format("alert('{0}'); window.location.href='{1}';",
msg, ResolveUrl("~/Dashboard.aspx"));
This is a common example of a problem with WebForms - it's very difficult to properly mix client and server code together to provide a good user experience, which is why I much prefer doing my user experience stuff completely in javascript, with AJAX to do most of the posts.

How to properly pass a JSON in rails

I am new to web development and rails as well. I created a web app for internal use in php and now am converting it to rails. Trying to find out what render does is difficult. For example I find definitions like this:
render(options = nil, extra_options = {}, &block) protected
Renders the content that will be returned to the browser as the response body.
It seems nobody told the author that you do not use a word in its definition.
I was trying to understand render because according to How to pass json response back to client that is a better way of doing the task than the approach I have tried. But without the other peices I do not know how to implement it.
Could be due to my lack of web experience so if anyone has any links to definitions thats may help please post them.
I get this error:
Error in GetData: JSON.parse: expected property name or '}' at line 2 column 3 of the JSON data
When I print the string in an alert box it appears as one long string so I do not know where "line 2" is. If I set the limit to 1 I get the same error which really makes "line 2" difficult to find.
Here is an example of the data I get back:
[{"DocumentNbr":"SS9230","DocumentRevision":""},{"DocumentNbr":"SS8640","DocumentRevision":"17"},{"DocumentNbr":"SS8618","DocumentRevision":"4"},{"DocumentNbr":"SS8630","DocumentRevision":"20"},
I don't know if the " is supposed to be spelled out as &quot or at least thats how it is displayed in the alert box. I do not know if thats normal or an error that is causing the JSON.parse to fail. Any other ways to check data besides the alert?
I have a javascript function to call 'GetData' in the view:
var wholeNumberData;
wholeNumberData = GetData('wholeNumber', wholeNumber);
Which looks like this (stripped down version):
function GetData(getType, param) {
var data;
var params;
params = 'wholeNumber=' + param;
data = SendRequest('wholenumber/index', params);
return data;
}
function SendRequest(source, params) {
var http = new XMLHttpRequest();
http.open("GET", source + '?' + params, false);
http.setRequestHeader("Content-type","application/json");
http.onload = function() {
//alert('in function');
}
http.send(params);
alert(http.responseText);//Works
return JSON.parse(http.responseText);//FAILS
}
The route wholenumber/index points to an index.html.erb cionatining this:
<% #list = Wholenumber.where("DocumentNbr LIKE ?", params[:wholeNumber] + "%").limit(10) %>
<%= #list.to_json(:only => [:DocumentNbr, :DocumentRevision]) %>
This is kind of an unusual way to do it, but you could just add html_safe to your to_json method and it should work how you have it.
<%= #list.to_json(:only => [:DocumentNbr, :DocumentRevision]).html_safe %>
If you want the control to render JSON, rather than trying to parse JSON from html, you can have the controller action do something like this:
def action
#list = Wholenumber.where("DocumentNbr LIKE ?", params[:wholeNumber] + "%").limit(10)
render json: #list.to_json(:only => [:DocumentNbr, :DocumentRevision])
end
The Rails Guides have a more thorough walkthrough of Rails rendering

Jquery submit adds flawed encoding [duplicate]

I want to send the variables itemId and entityModel to the ActionResult CreateNote:
public ActionResult CreateNote(
[ModelBinder(typeof(Models.JsonModelBinder))]
NoteModel Model, string cmd, long? itemId, string modelEntity)
with this javascript:
Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});
However, the url being send is
localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44
I want to send
localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44
How can I prevent Url.Action to put the & in front of the second variable that I want to send?
I didn't notice yesterday that you had & I thought that was the SO editor had changed that. Try wrapping your Url.Action() in a #Html.Raw() to prevent the Encode of &.
Or alternatively only Url.Action() the controller/action bit and pass the two parameters as post data rather than directly on the url, jQuery should sort out the &'s for you that way.
I think your problem is with Model.meta.PostAction - is that property a string?
If so then my guess would be that you're adding it to the page with either:
Razor: #Model.meta.PostAction
ASP view engine: <%:Model.meta.PostAction%>
Both of which automatically encode that string for you.
To fix it either use #Html.Raw()/<%= (both of which don't encode) or make the PostAction property an IHtmlString that knows that it's already been encoded:
string actionUrl = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});
Model.meta.PostAction = new HtmlString(actionUrl);

JavaScript in ASP.Net CodeBehind

I am having trouble with some javascript that I have added to the codebehind. The goal I am trying to achieve here is on the page load to do another postback. Now, you may find this odd, but there is method to my madness.
In my ASP.Net Wizard, I have a textbox that contains a date populated from another step. This date is then used to populate 3 other controls with financial information. It is necessary for these 3 other controls to be populated on the load of this step. Now I have tried to do simply on page_load, but this doesn't work as certain controls either don't exist or the date isn't in the textbox. I have also tried to do this on the page render method, but this didn't work either for the same reasons.
So, I have resorted to using javascript executing a double postback, but it is causing all sorts of problems.
Here is the code from the Page_Load :
Dim validateFinancial as String = "<script language='javascript'>window.onload = function() ( ValidateFinancialDate() { __doPostBack('<%= UpdatePanel2.ClientID %>'); return false; })</script>"
Page.ClientScript.RegisterStartUp(Me.GetType(), "MyScript", validateFinancial, false)
It is not firing and in the javascript error box you see in the bottom left hand corner of the browser it says missing ";". If I remove the javascript code and simply added it to the markup with the function name in the string it will work with errors, but this when posting to the webserver causes the AJAX controls to fail on the whole page.
Is there away of getting this to work, please?
Your problem is that
<%= UpdatePanel2.ClientID %>
will not be interpreted. at the time when you want your javascript to post back, ASP has already finished rendering your page. You're goin to have to find another way of passing your UpdatePanel2.ClientID value.
You shouldn't use <%= UpdatePanel2.ClientID %> on backend side. Get __doPostBack('<%= UpdatePanel2.ClientID %>') equivalent using ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty); replace your __doPostBack('<%= UpdatePanel2.ClientID %>') with return value of mentioned method.
More detailed:
Let's start from the beginning. You need postback to be initiated by UpdatePanel2 after page loaded on client.
The correct JS function pattern should be:
window.onload = function() { ValidateFinancialDate(); %Do postback%; return false;};
To obtain that %Do postback% function call for UpdatePanel2 we need to use ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty) backend method,
which will produce correct JS __doPostBack function call to make postback request initiated by UpdatePanel2 control.
So working example on C# will be as following:
string postbackReference = Page.ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty);
string validateFinancial = "window.onload = function() { ValidateFinancialDate(); " + postbackReference + "; return false;};";
Page.ClientScript.RegisterStartUp(this.GetType(), "MyScript", validateFinancial, true);
Please pay attention to true argument of RegisterStartUp method, this will wrap validateFinancial script contents into tags automatically.
But this workaround with double postback seems artificial for the problem you're trying to solve, if you provide more source code
we can find better solution.

Categories

Resources