passing javascript parameter to asp.net - javascript

I have a Javascript function and i want to pass a parameter from javascript to asp.net. my sample code like below:
function ConfirmMessage(message) {
var msg = "<%= Efe.UI.WebApplication.AppCode.HelperClass.GetScreenMessage(message); %>"
alert.confirm(msg);
}
But I am getting error at "message" parameter. The error is:
The "name" does not exist in the current context.
How can I pass parameter from javascript to asp.net?

You cannot pass parameter from javascript to server side at inline code.
You should use jquery ajax for that.
var message = "value";
$.get(
url: "/yoururl/GetScreenMessage",
data: {message : message},
success: function(data){
alert(data);
});

You're trying to dynamically call a server side function with a parameter, but the <%= %> part is actually a Response.Write. So, during the page load the page will try to render with the Efe.UI.WebApplication.*xxx* method's output.
That won't work.
You'll need a different solution all together. Most likely you'll want to use a "REST-like" service call to get the result of the "message" parameter. I would suggest you take a look at AJAX : http://msdn.microsoft.com/en-us/library/bb398874%28v=vs.100%29.aspx and http://www.codeproject.com/Articles/29400/Ajax-Quick-Start-FAQ

Related

Pass data from JavaScript function as an object parameter to #Html.Action() C#

Here is what I am trying to do. I want to be able to call an html action and pass in some data as an object parameter. The only thing is this data needs to be returned from a javascript function.
Here is what I am trying to do:
#Html.Action("someAction", "someController", new { passedData = GetDropDownData() })
<script>
function GetDropDownData() {
var data = "test";
return data;
}
</script>
Basically I am trying to pass some drop down data from a control to a partial view being rendered with the #Html.Action(). I want to be able to pass this string to the partial view somehow so I figured I could use JS to pull the drop down data and return it as an object parameter when rendering the page?
Let me know if you have any suggestions or a better way to go about this.
Thank you!
This is not possible the way you're doing it, because razor views are compiled on server side, while javascript is client side. Therefore, the views are already compiled, while javascript runs during runtime. One way to do it is to use ajax to pass variables from javascript to an action in the controller as query parameters or body values. You could achieve that by creating a button or link:
<a href='#' id='clickMe'>Click me</a>
And hooking up jQuery to do the job:
<script>
$(document).ready(function(){
$('#clickMe').click(function(){
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: {
passedData: GetDropDownData()
},
success: function(response){
$('#placeholderForPartialView').html(response);
}
});
});
});
</script>
It would look something like this depending on your method (GET or POST) type.
Here I assume that you return Partial view as a result and replace the contents of #placeholderForPartialView div with the returned view. Please correct me if I'm wrong.

How to pass parameters from front end to python script

I'm trying to pass the parameters defined by a user in the front end to a python script being run on the server. I'm using a Django framework in the back end (probably too heavy for my purposes at the moment but wanted to give it a try). Here's the jQuery code I'm using to call the python fxn which is located at the defined url. The parameters I'd like to pass are in the data attribute.
bbviz.onStart = (function() {
$.ajax({
type:'get',
url:'http://localhost:8000/statview/simulation/',
data:{url:'blackch02', 'profile':'current', 'sims':1000},
async:'asynchronous',
dataType:'json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
And here's the Django view function:
def simulation(request):
out = batterSim.sim_season(url, profile, sims)
return out
I'm calling the batterSim module and running the sim_season function which has the same named parameters as the data attribute. The function then returns a json object that the front end would receive. So I'm trying to figure out how to take those parameters from the ajax function and use them in the python function.
You can use parameter in Django view by call
request.GET['profile']
request.GET['sims']
You should read more about Django request : https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.GET

AJAX call how to retrieve my javascript variable

I work with Rails 4 and basically I am searching a value on my html webpage traversing the DOM with jquery.
I store the value in a variable named key and I want to use this value to then make a request that would look like this :
Record.find(id: key).name
I perform an AJAX call and it works well (I checked it rendering status json ok). But now how can I use/retrieve the parameter key in my controller ?
I have a User and a Record model. In the app/views/usersdirectory I have the partial _form.html.erb in which I am doing some javascript.
var key = $('input#record_id').val();
And I want this variable to be available in the method search of my user controller, so that I can make a request with the parameter key.
So I am doing an AJAX call that looks like this :
$.ajax({
url: "/search",
type: "POST",
data: {
value: key
},
complete: function(){
console.log('success');
}
});
And in my config routes file I wrote this route :
post '/search' => 'users#search'
In my User controller I wrote the method like this :
def search
#record = Record.find(params[:key])
end
Is #record available in my partial ? How can I print in my view the result of my request ?
Can anyone tell me if I am doing right or wrong for my AJAX call ? Thanks for any help. If I forgot to mention any information you might need tell me and I'll edit my post.
I added a complete function in my AJAX call, that is supposed to show successif the AJAX call had been done and in my console log I have this message 'success' that appears
For 404 not found the url must be wrong.
And to get the param key in your controller you must change data to data: {key: key} or if you use data: {value: key} then your action must change the name of the param like #record = Record.find(params[:level])
Basically, you are not using the right param name in your controller which is why the issue arises. Hope it helps.
To answer your second question:
#GDMN, you need to get your basics right! Every ajax has a success and failure callback.You could return json from your action which will be used by success callback and you could do whatever you want from there. Essentially in rails you might want to render a js file like this
Create a file named search.js.erb and use your javascript code in it like below
$('.some_id_or_class').html("<%= #record.name %>")
that will simply replace the element of that class with the value that is returned by #record.name
put the full url
url: "http://yoursite.domain/search",

How to pass a javascript variable to server side method

I am facing issue like I am unable to pass the javascript variable to server side I am aware that it is not achieveable in this scenario so I tried like setting the value to the asp hidden field using jQuery and getting the value of the label in server side but unfortunately I am getting empty value for the hidden field. Help me on how to fix this
CODE
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID){
<%=RenderMethod(DataID) %> // How to pass javascript variable to server side
}
Hidden Field Approach:
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID){
$("#<%=hdnDataVal.ClientID %>").val(DataID);
alert($("#<%=hdnDataVal.ClientID %>").val(DataID)); // Here using javascript I can able to set the value and when I alert the value it is displayed
<%=RenderMethod(hdnDataVal.Value) %> // here the hiddenfield value is empty
}
<asp:HiddenField runat="server" ID="hdnDataVal" />
First of all... you should not mix server code and client code the way you're doing it.
It's a poor way to design your code. Try always to separate client and server code. They execute on different moments, places and under different circumstances... having them together will eventually draw you to difficult to debug errors.
I bet that the problem you're experiencing here is due to this way of coding.
You say on your code snippet that
<%=RenderMethod(hdnDataVal.Value) %> // here the hiddenfield value is empty
When your page is loading and server code is executed the code inside $(document).ready() is not fired yet, as it fires when your whole page finish loading. So, your RenderMethod is firing before you put any value inside the variable.
try using $.ajax();
var url = 'my-url.aspx';
$.ajax({
url: url,
type: 'POST',
data: {'variable_name': my_variable },
success: function(html)
{
alert('ok');
},
});
and receiver on the server-side:
string my_variable = Request.Form['variable_name'];
You can use a Page Method to make a server side call from client side. It's propably the easiest way to accomplish what you want.
First of all you need to include the Script Manager in your aspx page with Page Methods enabled:
<asp:ScriptManager ID="scrmgr" EnablePageMethods="true" runat="server" />
Now you can invoke the server side method and pass it the client side data you want, with sth like this:
<script type="text/javascript">
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID) {
PageMethods.RenderMethod(DataID, OnSuccess, OnError);
}
function OnSuccess(result) {
alert(result);
}
function OnError() {
alert('Some error has ocurred!');
}
</script>
OnSuccess function is invoked in case the server-side method has been succesfully called. Otherwise OnError function is invoked.
This is how the Page Method should be declared inside the .aspx.cs file:
[System.Web.Services.WebMethod]
public static string RenderMethod(string dataID)
{
return "Got here!";
}
If you place a breakpoint inside RenderMethod, then you can verify that client side data (i.e. value "4325") is correctly passed to it.

Call a ruby method with different parameters embedded in javascript

I have this ruby method:
def something(sometext, jsvariable, rubyobject)
return HTMLOBJECT
end
And I would like to call this method like this in a javascript function:
$("#someid").append('<% something("sometext", '/jsvar/', rubyobject) %>');
Its not working.I don't know how to call this method from a javascript function with proper
formatting of the variables. I don't really know the exact syntax for it.
Any help is much appreciated.
UPDATE: This is what I'm trying to do
function somejsfunc(){
$.ajax({
url: "/app/SomeController/someMethod",
data: {'something': something }
success: function(data){
var $response1 = $(data);
jsvar = $response1.find('#anotherselector').text();
$("#someid").append('<% something("sometext", '/jsvar/', #rubyobject) %>');
}
});
}
Please Note
def something
is a generic method which returns a HTML DOM element based on these parameters,along with
other data passed into it.Thanks.
You can not do this, because erb templates compiles before application startup. Use remote requests to take info from server if you want send some js parameters.
UPD: Something like this
$.ajax({
url: '/some_url',
data: { jsvar: jsvar },
success: function(data) {
$("#someid").append(data.sometext);
}
});
Normally our ruby runs on the server and your JavaScript runs in the browser, so calling one from the other is pretty much impossible. You may of course resort to Ajax as #uselesssmile suggester, but that involves a whole lot more than a simple method call. On the other hand you can compile your ruby to JavaScript using opalrb, then you can package it into your JavaScript on the client and call it directly.

Categories

Resources