Issue with accessing jinja python list in javascript - javascript

I have a python list called "devices" that looks something like this:
[{
'Version': 'V14E',
'DeviceID': 'e00fce68281671574f416a8c',
'TerminationDate': '2050-12-31',
'Latitude': 31.322139613573903,
'ActivationDate': '2021-01-04',
'Longitude': -101.93960164357534,
'DeviceName': 'Hans_Gruber-1'
}, {
'Version': 'V14E',
'DeviceID': 'e00fce68e1265e12e12fa02a',
'TerminationDate': '2050-12-31',
'Latitude': 31.32151602493975,
'ActivationDate': '2021-01-04',
'Longitude': -101.93948944894449,
'DeviceName': 'Hans_Gruber-2'
}]
In my flask app, I pass this list to my html file by the name "devices_test" using json.dumps() to correctly format the data to be used in java script.
return render_template("json_form.html",
devices = devices, components = components, operator = operator, name = site_name,
devices_test = json.dumps(devices))
Here is me trying to test out an answer I have seen on another post here via the "data" variable:
function update_device_form(strDevice) {
var data = {
{
devices_test | safe
}
};
var device_index = document.getElementById("devices").selectedIndex;
if (device_index == 0) { //IOW if no device is selected
document.getElementById("device_id").value = "";
} else {
document.getElementById("device_id").value = '';
}
But I get errors such as "Declaration or statement expected" and "Property assignment expected" and "',' expected". What am I doing wrong here?

You can use string to remove the error var data = "{{devices_test|safe}}"
Now data is not javascript object, it is a string, you need to use JSON.parse and also replaceAll.
var data = "{{devices_test|safe}}"
var data = data.replaceAll("'",'"') // replace single quote to double
var data = JSON.parse(data)
one line
var data = JSON.parse("{{devices_test|safe}}".replaceAll("'",'"'))

Related

Pass Javascript nested array to PHP using Ajax in external Javascript file

I want to pass a nested javascript array that is dynamically generated to a php file to later insert it into the database.
The array is dynamically generated inside a Javascript file. Now i want to pass that array to a php file that will insert that data dynamically into a database.
I have found multiple examples of this question on stackoverflow but none suit my situation (they are all working from inside an HTML file).
The array I am trying to pass:
1. 0:
1. cleintDate:"31/08/17"
2. cleintExpirydate:"29/11/17"
3. cleintState:"Department"
4. clientCode:"clientcode"
5. clientName:"Name"
6. messages:Array(2)
1. 0:
1. messageClient:"Name"
2. messageDate:"2017-08-31T00:00:00"
3. messageSubject:"subject "
4. messageText:"messageText "
5. messageTime:"13:22"
6. messageType:"link"
7. __proto__:Object
2. 1:
1. messageClient:"Name"
2. messageDate:"2017-08-31T00:00:00"
3. messageSubject:"subject "
4. messageText:"messageText "
5. messageTime:"13:22"
6. messageType:"link"
7. __proto__:Object
3. length:2
**Note:**The above example contains 2 messages inside the array but there are examples of 54 messages inside the array. (Text of array slightly edited to hide personal information).
How I generate this array:
matches[0].forEach(function(match, index) {
var cleintcode = /<div\s*class="t_seg_codCliente">(.*?)<\/div>/.exec(match)[1];
var cleintname = /<div\s*class="t_seg_nomCliente">(.*?)<\/div>/.exec(match)[1];
var taxId = /<div\s*class="t_seg_nifCliente">(.*?)<\/div>/.exec(match)[1];
var date = /<div\s*class="t_seg_fechaPresCliente">(.*?)<\/div>/.exec(match)[1];
var state = /<div\s*class="t_seg_estadoCliente">(.*?)<\/div>/.exec(match)[1];
var expirydate = /<div\s*class="t_seg_fechaCadCliente">(.*?)<\/div>/.exec(match)[1];
var communications = /<div\s*class="t_seg_comCliente"><a .*;">(.*?)<\/a>/.exec(match)[1];
var comclient = /<div\s*class="t_seg_comCliente"><a href="javaScript:popupComs\('(.*?)'/.exec(match)[1];
var messages = "link" + comclient;
var html1 = httpGet(messages);
const cleanupDocString = html1.replace(/(?:<!--|-->)/gm, '');
parser = new DOMParser();
htmlDoc = parser.parseFromString(cleanupDocString, "text/html");
var communicationsvalue = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[0].textContent;
if (communicationsvalue.indexOf('No existen comunicaciones asociadas a este cliente.') !== -1) {
console.log("This chat does not contain any communiction!");
} else {
var adiv = document.createElement("div"),
msgs = [],
trs;
adiv.innerHTML = cleanupDocString;
trs = adiv.querySelectorAll('tr[bgcolor="#FFFFFF"]');
trs.forEach(function(tr) {
var d = [];
tr.querySelectorAll("td")
.forEach(function(td) {
var img = td.querySelector("img"),
src = img && img.attributes.getNamedItem("src").value;
d.push(src || td.textContent);
});
msgs.push(d);
});
var mappedArray = msgs.map((msg) => {
return {
messageDate: msg[0],
messageTime: msg[1],
messageType: msg[2],
messageClient: msg[3],
messageSubject: msg[4],
messageText: msg[5]
}
});
var messageData = [{
clientCode: cleintcode,
clientName: cleintname,
taxID: taxId,
cleintDate: date,
cleintState: state,
cleintExpirydate: expirydate,
messages: mappedArray
}];
console.log(messageData);
}
});
The code I am trying to use to pass the array:
$.ajax({
type: "POST",
url: "../php/messageProcessing.php",
data: {
"id": 1,
"myJSArray": JSON.stringify(messageData)
},
success: function(data) {
alert(data);
}
});
The error it gives me:
Uncaught ReferenceError: $ is not defined
at ProcessAJAXRequest (getPagesSource.js:126)
at getPagesSource.js:139
at Array.forEach (<anonymous>)
at DOMtoString (getPagesSource.js:62)
at getPagesSource.js:150
Summary:
How do i pass a Javascript array with Ajax (or any other solution) from a external Javascript file.
And how do I dynamically get each piece of data from messages to insert into the Database.
Thanks for any piece of help!
The problem seems to be that you have used JQuery without including the JQuery library on the page. The JQuery library exposes a global variable $ and must be loaded into the global context before being used by other javascript files.
$.ajax({
type: "POST",
url: "../php/messageProcessing.php",
data: {
"id": 1,
"myJSArray": JSON.stringify(messageData)
},
success: function(data) {
alert(data);
}
});
You can fix this by including jQuery somewhere in the page from the cdn (lastest version):
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
Alternatively, if you were not intending to use a JavaScript library, you will have to look into how to use XmlHttpRequest to do what you are looking for. This is built into the javascript language itself.
how do I dynamically get each piece of data from messages to insert
into the Database?
You will receive a POST request in the PHP script with the myJSArray in the body. You will be able to access it via $_POST['myJSArray'], you will then need to parse it as JSON and then treat is as any other kind of PHP object.

Setting setRequestBody for Rest web services using Post method

Hi I'm trying to create a rest response using post method, I want to dynamically pass the variables instead of hard coding,But where i fail is,when I'm trying to to send an array as a parameter to the Rest web service using post method(example array ["CN=XXX_XX,OU=XXXXX,OU=1_XXXX XXXXity Groups,DC=XXXX,DC=local"]) and I know that there is a better way to do that Please find my code sample.This is the method that gives me a appropriate result.
First Method:(Works)
`
try {
var r = new sn_ws.RESTMessageV2('SailPoint_IdM', 'post');
var txt = "{\r\n\t\"workflowArgs\":\r\n\t{\r\n\t\"identityName\":\"SiamR\",\r\n\t\"appName\":\"Active Directory\",\r\n\t\"listEntitlements\":[\"CN=ER_CxxxK,OU=xxxxx,OU=1_xxxxxx Security xxx,DC=xxxx,DC=local\"],\r\n\t\"operation\":\"Add\",\r\n\t\"ticketNumber\":\"RITM1234567\"\r\n\t}\r\n}";
r.setRequestBody(txt);
var response = r.execute();
var ResponseBody = response.getBody();
var HTTPCode = response.getStatusCode();
gs.log(ResponseBody);
gs.log(HTTPCode);
} catch (ex) {
var message = ex.getMessage();
}
output:
Script: {"attributes":{"requestResult":{"status":"Success"}},"complete":false,"errors":null,"failure":false,"metaData":null,"requestID":"2c988d8c5bd47cf7015bebfb64cf01e6","retry":false,"retryWait":0,"status":null,"success":false,"warnings":null}
Script: 200
2n Method (Does not Work):
try {
var r = new sn_ws.RESTMessageV2('SailPoint_IdM', 'post');
r.setStringParameter('"listEntitlements"', '["CN=Exxx_xxxK,OU=xxxxion,OU=1_xxxxx Security xxxx,DC=xxx,DC=xxxx"]');
r.setStringParameter('"identityName"', '"SiarmR"');
r.setStringParameter('"appName"', '"Active Directory"');
r.setStringParameter('"ticketNumber"', '"RITM1234567"');
r.setStringParameter('operation', '"Add"');
//override authentication profile
//authentication type ='basic'/ 'oauth2'
//r.setAuthentication(authentication type, profile name);
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
gs.log(responseBody );
}
catch(ex) {
var message = ex.getMessage();
}
output:
Script: {"attributes":{"requestResult":{"errors":["An unexpected error occurred: sailpoint.tools.GeneralException: The application script threw an exception: java.lang.NullPointerException: Null Pointer in Method Invocation BSF info: script at line: 0 column: columnNo"],"status":"FAIL","GroupStatus":null,"AppStatus":null}},"complete":false,"errors":["Status : failed\nAn unexpected error occurred: sailpoint.tools.GeneralException: The application script threw an exception: java.lang.NullPointerException: Null Pointer in Method Invocation BSF info: script at line: 0 column: columnNo\n"],"failure":false,"metaData":null,"requestID":null,"retry":false,"retryWait":0,"status":null,"success":false,"warnings":null}
Script: 200
Im facing issue with this parameter as im trying to pass this as aray paramenter '["CN=Exxx_xxxK,OU=xxxxion,OU=1_xxxxx Security xxxx,DC=xxx,DC=xxxx"]'
Please suggest a way to implement this and to pass all the variables dynamically if suggesting first method
Below is one of my function, to handle dynamic parameters in either appear in request endpoint (url), headers or body;
For eg: parameter p
var p = {abc: 'def'};
and outbuond rest settings:
rest url = https://xxxx.sss.com/api/showme?name=${abc}
rest headers name = custom-header; value = ${abc}
rest body = {name: "${abc}"}
so it will replace all ${abc} to 'def'
_.isNullOrEmpty - check is obj, string or array is null or empty;
_.loop - loop an obj or array, pass in function(nm/i, val) {}
_.isArray - to check if is array
_.str - convert anything to string
_.rpl - replace all string A to B
restParameters: function (restRequest, obj, endpoint) {
var _ = this;
if ((_.isNullOrEmpty(restRequest)) || (_.isNullOrEmpty(obj))) return;
if (_.isNullOrEmpty(endpoint)) endpoint = restRequest.getEndpoint();
var body = restRequest.getRequestBody();
var headers = restRequest.getRequestHeaders();
_.loop(obj, function(nm, val) {
if (_.isArray(val)) {
val = (_.isNullOrEmpty(val)) ? '[]' : JSON.stringify(val);
} else val = _.str(val);
//for my case my array pass in as string become: "[\"1\", \"2\"]"
//comment below if pass in as object
if (val.contains('"')) val = _.rpl(val, '"', '\\"');
restRequest.setStringParameterNoEscape(nm, val);
var sch = '${' + nm + '}';
endpoint = _.rpl(endpoint, sch, val);
body = _.rpl(body, sch, val);
_.loop(headers, function (hn, hv) {
headers[hn] = _.rpl(hv, sch, val);
});
}, true);
restRequest.setEndpoint(endpoint);
restRequest.setRequestBody(body);
_.loop(headers, function (hn, hv) { restRequest.setRequestHeader(hn, hv); });
}

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

How get parametrs from json?

Full code:
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
});
in data i get json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
P.S.: All code php and jquery find here
Just set proper data type json, the default one is string.
And your data is directly under data variable!
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
}, 'json');
Another solution is setting proper header in you PHP response:
Content-Type text/javascript; charset=UTF-8
then jQuery Intelligent Guess, will set proper data type itself.
You can use parseJSON method, exposed by jQuery. This enables you to map the properties to a type, of sorts, such as:
var results = jQuery.parseJSON(jsonData);
for (int i = 0; i < results.length; i++) {
alert(results[i].name + ":" + results[i].date);
}
You may need to tweak the inputs and exact use of the outputs in accordance with your data and requirements.
getJSON() will parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON).
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
});
Another example:
Parse a JSON string.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" )
;

Passing Variable from JSON data

I am building a mobile app using Titanium for ios and I am having a tough time getting my arms wrapped around passing variables. I am using a combination of local database and remote database to deliver my data. In this case I want to pass the data on the tableViewRow selected. The label that displays the data I call "categorydescription". In my table.addEventListener, I want to pass that data as the title for the new window and I will pass that same data to my php file on the remote server. Here is the code I am trying to use:
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for (i = 0; i < json.cms_client.length; i++) {
client = json.cms_client[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var categorydescription = Ti.UI.createLabel({
text:client.catdesc,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(categorydescription);
tableData.push(row);
}
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: ??});
var catdesc = ??;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
table.setData(tableData);
Would someone be so kind to tell me what I need to put in place of the ?? in the 'title' and 'var catdesc' above?
Just add the category description and title to the row object itself:
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true,
categoryDescription : client.catdesc, //Add this
clientTitle : client.title // Add this
});
Now get them in the listener:
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: e.row.title});
var catdesc = e.row.categoryDescription;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});

Categories

Resources