How to pass parameters from front end to python script - javascript

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

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 run a python script inside javascript and refresh the view in django

I have a python script that takes in some data and manipulates it. However i need it to run on the client side inside the javascript to process some data and refresh the view.
The python file that manipulates data works well as I have tested it inside the IDLE shell
DataManipulation.py
class ModifyData(object):
#Bunch of functions to manipulate data
below is the function used to render the view with url '.../test' which also works perfectly.
views.py
def test(request):
template = 'app/test.html'
file = 'documents/Sample.csv' #File to be loaded
args = {'test': file }
return render(request, template, args)
After loading this page, i use a javascript library that displays the data on the page in a table, the user can then manipulate the data like multiply a column by 3, but where I am stuck is how to take my DataManipulation.py file to modify the data and updates the page with the updated column on a button click
Since executing python client side is not an option, you have two options.
re-write ModifyData in Javascript and use it client side.
When a user does something like multiply a column by 3:
Use client side JS to make an ajax request to the server
Have your server call ModifyData, and then return the data to the client
have client update view with new data
I would recommend porting your python code to JS, but if that isn't possible #2 will always work. How you implement will just depend on how you manage data in the client.
I think you should pass the data into template, and then use javascript to manipulate the data, after that you can use ajax to update your page without refresh, example:
<!--html-->
<button onclick="deleteUser({{ request.user.pk }})">Submit</button>
<!---->
function deleteUser(userid) {
var post_data = {
'userid': userid,
}
$.ajax({
type: "POST",
url: "/deleteuser",// the view function to post
data: post_data,
contentType: 'application/json;charset=UTF-8',
success: function(result) {
// do something after post
...
}
});
}
the view function:
# url(r'^/deleteuser$', views.delete_user)
def delete_user(request):
if request.method == 'POST':
# do something
userid = request.POST.get('userid')
user = User.objects.get(pk=userid)
# dict contain response data
response_data = {...}
# return response
return HttpResponse(json.dumps(response_data),content_type='application/json')

Accessing jquery data variable in ajax call in server side script

I have a few ajax calls in my app they all go to the same file server side. i want to know if I can use a variable... I want to have a way to distinguish the call from other calls and of course, use the variable to select which script in the file to send back to the client. I do not need to use the variable after the script has run in any way. Or am i going about this the wrong way?
for example this is one of my ajax calls
var variable1 = 'currentuser1var';
return $.ajax({
type: 'GET',
url: '/users/index',
data: {currentuser1var: variable1},
dataType: 'script',
});
then the script in my server side file would be
if (currentuser1var) { script here }
else if (currentuser2var) { script here }
...
I am not sure how to access the string, inside the object call. Do i need to access the object first then the string? Or just reference the variable some how.
EDIT Tried
if(typeof(currentuser1var) != "undefined") { script here }
to no avail.
If you were using PHP, your server side script would be:
if(isset($_GET['currentuser1var'])) {
... script to process the currentuser1var variable ...
} else if (isset($_GET['currentuser2var'])) {
... script to process the currentuser2var variable ...
}
Aj was right here I guess for php as I did not list what server side code I was using, but simply put, I changed my ajax call to
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentuser1var: 'variable1'},
});
where the key is currentuser1var and the value variable1 is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentuser1var=variable1. And in my destination file add my ruby code there to use the variables.

passing javascript parameter to asp.net

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

Getting rss feed with jquery and ajax

I found this site that allows to convert RSS feeds into json.
It also provides a way to specify a callback, so i think users are able to make jsonp calls to this web service.
However, i tried different ways to do that but none worked.
Here is my code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://www.blastcasta.com/feed-to-json.aspx',
dataType: "jsonp",
jsonpCallback: "loadRSS",
data: {
feedUrl: 'http://xml.corriereobjects.it/rss/homepage.xml',
param: "callback"
},
success: function (data) {
var list = "";
for (var propertyName in data) {
list+=data[propertyName];
}
console.log(list);
},
error: function(xhr, ajaxOptions, thrownError){
alert(ajaxOptions)
}
});
});
Whatever i try, the success handler doesn't get executed. I get error handler instead.
I tried with jsonpCallbak: "callback", jsonpCallback: "?", param: "callback" and other values too but without success.
I have to use ONLY javascript without the support any server side scripting language (no aps, no php, etc.)
Did someone get this service working in his site?
Any suggestion would be really appreciated!
I find jQuery JSON API not suitable for this kind of JSON response that provides BlastCasta service. It assigns JSON to a custom variable, specified in URL, and doesn't uses callback functionality JSONP operates with. For example this URL:
http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml&param=rssFeed will return following response:
rssFeed = { "rss": { "channel": /*...*/}}
So, script injection technic may be used:
/* URL of the BlastCasta service and his parameters:
feedUrl :== escaped URL of interest (RSS Feed service)
param :== javascript variable name which will receive parsed JSON object */
var url = "http://www.blastcasta.com/feed-to-json.aspx"
+"?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml"
+"&param=rssFeed";
/* since the service declares variable without var keyword,
hence in global scope, lets make variable usage via window object;
although you can write param=var%20rssFeed" in the URL :) */
window.rssFeed = null;
$.getScript(url, function() {
/* script is loaded, evaluated and variable is ready to use */
console.dir(window.rssFeed);
/* some feeds are huge, so free the memory */
window.rssFeed = null;
});
Update:
here's an example that works for your code:
$.getJSON("http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http://xml.corriereobjects.it/rss/homepage.xml&param=?", function(data) {
console.dir(data);
});
problem is, that I get some javascript errors with returning json:
see this jsfiddle

Categories

Resources