How to pass python string to javascript as string in Django? - javascript

I have a python string which is javascript code and I want to pass this string to javascript as string too.
My idea is to pass python string to javascript string and then use eval() function in javascript to turn that string to actual code and execute it.
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
return render(request, "app/login.html", {'success': success})
var code = "{{success}}"
console.log(code) // return Uncaught SyntaxError: Invalid or unexpected token
I have also tried pass the string as json like this
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
success = json.dumps(success)
return render(request, "app/login.html", {'success': success})
var code = JSON.parse("{{success|safe}}");
console.log(code) //return Uncaught SyntaxError: missing ) after argument list
Last thing that I have tried is
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
return render(request, "app/login.html", {'success': success})
<h3 id="success_id" hidden>{{success}}</h3>
<script>
var code = $("#success_id").text();
console.log(code) //return window.location = "{% url 'home' %}"
// if i do this
var code = "window.location = '{% url 'home' %}'";
console.log(code) // return window.location = /app/home/
// I want it to return the url like /app/home
</script>
How can I do this?

Ok in essence what you want to do is using Django to pass data to js?
That has to to do with Django creating a Json Response which the JavaScript will then make a request , in essence you are working with some API.
your view code where you wrote the render function won't need that anymore...
Something like
JsonResponse({'success':success})
will be needed , after importing the JsonResponse from 'django.http'
Then at the js file, you will have to use Ajax to call that url with it's required method to get the data needed.
in your script tag , you will then need something like this
const xhr= new XMLHttpRequest ()
xhr.open('django_url', 'method')
xhr.onload = function () {
const msg = xhr.response.success
}
xhr.send()
If you are familiar with fetch or axios you can as well use any library of your choice.
the django_url refers to the url that connects that view
the method refers to the http_method, either a 'GET' or 'POST' (most commonly used) .

Related

webscraping logins with javscript and ajax

i'm stuck trying to get viewstate data to pass for form authentication. heres my code:
import scrapy
from scrapy_splash import SplashRequest, SplashFormRequest
class BrpSplashSpider(scrapy.Spider):
name = 'brp_splash'
allowed_domains = ['brp.secure.force.com']
# start_urls = ['http://brp.secure.force.com/']
script = '''
function main(splash, args)
url = args.url
assert(splash:go(url))
assert(splash:wait(1))
return splash:html()
end
'''
def start_requests(self):
yield SplashRequest(
url='https://brp.secure.force.com/login',
endpoint = 'execute',
args = {
'lua_source':self.script
},
callback=self.parse
)
def parse(self,response):
yield SplashFormRequest.from_response(
response,
formxpath='//form',
formdata={
'AJAXREQUEST' : '_viewRoot'
'j_id0:j_id5' : 'j_id0:j_id5'
'j_id0:j_id5:Login1_Dealer_No': '******'
'j_id0:j_id5:Login1_UserName': '******'
'j_id0:j_id5:Login1_Password': '*********'
'j_id0:j_id5:j_id26': 'en'
'com.salesforce.visualforce.ViewState':
}
)
pass
inspecting the webpage and looking at the form data i can see a huge string that is the viewstate data. its not in the html. where is it and how do i reference it?
thanks for looking,
jim
the object i'm looking for is in the login page. i was looking for it after logging in. newbie learning curve mistake

Json Ajax Response from Django Application

I have a Django app that the views.py sends a json data to a javascript function on my html. The problem is that I can not access the elements of the data.
I tryied to use JsonParse but not sucess, for instance when I do
var other = JSON.parse(data_doc_pers['data_doc_pers']);
document.getElementById("text_conf4").innerHTML = other['doc_nome'];
I receive the following response: [object Object]
what I am doing wrong???
Here is my code
Views.py
...
json_string = json.dumps({'type_numeric':type_numeric,'type_prop':type_prop,'name':name,'Vinculo':Vinculo,'doc_nome':doc_nome})
return JsonResponse({'data_doc_pers':json_string})
HTML
$.get('{% url "page" %}',{'var':var}, function (data_doc_pers) {
var other = JSON.parse(data_doc_pers['data_doc_pers']);
document.getElementById("text_conf4").innerHTML = other['doc_nome'];
});
Problem solvend!
The error I was doing in javscript was to use var other = JSON.parse(data_doc_pers['data_doc_pers']); the correct should be only (data_doc_pers['data_doc_pers'].

Asp.Net MVC parameter is null when pass it from client side to controller

Javascript
I have a method as follows,
function OpenRecord(id ,module ,screen) {
var url = '#Url.Action("OpenRecord", "Management", new { id = "_id", module = "_module",screen = "_screen" })';
url = url.replace("_id", encodeURIComponent(id));
url = url.replace("_module", encodeURIComponent(module));
url = url.replace("_screen", encodeURIComponent(screen));
window.location.href = url;
}
Controller
public ActionResult OpenRecord(string id, string module, string screen)
{
Int64 someID = Convert.ToInt64(id);
/*some act**/
return RedirectToAction(screen, module, new { id = someId});
}
When I run this i get id and module but screen param is passed null. When i inspect client side on chrome dev tools, i see all the parameters on javascript method are filled and the final url in url variable as follows;
/Management/OpenRecord/112?module=Customer&screen=MUSTRTANML
I guess that amp&; entity spoils my controller to get the last param but i am not sure and i don't know how to solve this.
Thanks in advance.
Simply wrap your Url.Action in Html.Raw(). Or you can go with replacement approach further - url = url.replace("&", "&"). Whatever you like, personally I would proceed with Html.Raw
you need to construct your url string with values
var url = '#Url.Action("OpenRecord", "Management", new { id = "_id", module = "_module",screen = "_screen" })';
this is wrong, it should be
var url = '/Management/OpenRecord?id=' + _id + '&module='+ _module + '&screen='+ _screen;
the above will pass the values of the variables rather than names , you cannot execute Url.Action as part of JavaScript this is Razor code

Passing variable to Flask from Javascript and then loading template

In my Flask app--I'm pretty new to Flask--, I'm getting the values for client's latitude and longitude with Javascript and then passing a formatted string to a flask view. The view is supposed to pass the string to an online API and obtain a JSON object. It then converts it to a dictionary and displays certain values on a new page. I'm having trouble with loading the page from the view after I pass it the variables from the Javasctipt function. I know that it returns a result (I tried using Javascript's alertto display the resulting html), but return rendered_template() doesn't load the new page for some reason. I wonder if that's even possible to achieve. Thanks.
Javascript:
function getLocation(){
if("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(transferFile);
}
}
function transferFile(position){
var start = 'lat=';
var result = start.concat(position.coords.latitude, '&lon=', position.coords.longitude, '&format=json');
$.get(
url="phony",
data= result,
success=function(data) {
;
}
);
}
And here's the Flask part:
#app.route('/phony')
def phony():
query = request.query_string
url = <link to API> + query
location_dict = requests.get(url).json()
return render_template("phony.html", location_data = location_dict)
Your current call to $.get doesn't do anything with the result in the success callback
success: function(data) {
;
}
data contains the output from render_template('phone.html', location_data=location_dict). You need to add it to the page.
success: function(data) {
$('#some-selector').html(data);
}
That will replace the contents of an element matching #some-selector with the output. If the output contains a new HTML document (i.e., it's wrapped in an html tag), you'll want to replace the entire DOM. You can do that with something like
success: function(data) {
$('html').replaceWith(data);
}

How do I send data from JS to Python with Flask?

I'm making a website with Flask and I'd like to be able to execute python code using data from the page. I know that I can simply use forms but it's a single page that is continually updated as it receives user input and it'd be a massive pain in the ass to have it reload the page every time something happens. I know I can do {{ function() }} inside the javascript but how do I do {{ function(args) }} inside the javascript using js variables? So far the only thing I can think of is to update an external database like MongoDB with the js then use Python to read from that, but this process will slow down the website quite a lot.
The jQuery needs to get a list of dictionary objects from the Python function which can then be used in the html. So I need to be able to do something like:
JS:
var dictlist = { getDictList(args) };
dictlist.each(function() {
$("<.Class>").text($(this)['Value']).appendTo("#element");
});
Python:
def getDictList(args):
return dictlistMadeFromArgs
To get data from Javascript to Python with Flask, you either make an AJAX POST request or AJAX GET request with your data.
Flask has six HTTP methods available, of which we only need the GET and POST. Both will take jsdata as a parameter, but get it in different ways. That's how two completely different languages in two different environments like Python and Javascript exchange data.
First, instantiate a GET route in Flask:
#app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return jsdata
or a POST one:
#app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return jsdata
The first one is accessed by /getmethod/<javascript_data> with an AJAX GET as follows:
$.get( "/getmethod/<javascript_data>" );
The second one by using an AJAX POST request:
$.post( "/postmethod", {
javascript_data: data
});
Where javascript_data is either a JSON dict or a simple value.
In case you choose JSON, make sure you convert it to a dict in Python:
json.loads(jsdata)[0]
Eg.
GET:
#app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return json.loads(jsdata)[0]
POST:
#app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return json.loads(jsdata)[0]
If you need to do it the other way around, pushing Python data down to Javascript, create a simple GET route without parameters that returns a JSON encoded dict:
#app.route('/getpythondata')
def get_python_data():
return json.dumps(pythondata)
Retrieve it from JQuery and decode it:
$.get("/getpythondata", function(data) {
console.log($.parseJSON(data))
})
The [0] in json.loads(jsdata)[0] is there because when you decode a JSON encoded dict in Python, you get a list with the single dict inside, stored at index 0, so your JSON decoded data looks like this:
[{'foo':'bar','baz':'jazz'}] #[0: {'foo':'bar','baz':'jazz'}]
Since what we need is the just the dict inside and not the list, we get the item stored at index 0 which is the dict.
Also, import json.
.html
... id="clickMe" onclick="doFunction();">
.js
function doFunction()
{
const name = document.getElementById("name_").innerHTML
$.ajax({
url: '{{ url_for('view.path') }}',
type: 'POST',
data: {
name: name
},
success: function (response) {
},
error: function (response) {
}
});
};
.py
#app.route("path", methods=['GET', 'POST'])
def view():
name = request.form.get('name')
...
im new in coding, but you can try this:
index.html
<script>
var w = window.innerWidth;
var h = window.innerHeight;
document.getElementById("width").value = w;
document.getElementById("height").value = h;
</script>
<html>
<head>
<!---Your Head--->
</head>
<body>
<form method = "POST" action = "/data">
<input type = "text" id = "InputType" name = "Text">
<input type = "hidden" id = "width" name = "Width">
<input type = "hidden" id = "height" name = "Height">
<input type = "button" onclick = "myFunction()">
</form>
</body>
</html>
.py
from flask import Flask, request
app = Flask(__name__)
html = open("index.html").read()
#app.route("/")
def hello():
return html
#app.route("/data", methods=["POST", "GET"])
def data():
if request.method == "GET":
return "The URL /data is accessed directly. Try going to '/form' to submit form"
if request.method == "POST":
text = request.form["Text"]
w = request.form["Width"]
h = request.form["Height"]
//process your code
return //value of your code

Categories

Resources