From JavaScript to Objective-C with JSON - javascript

I have no idea how to properly 'return' this JSON object (in JavaScript):
function callback() {
var points = '{\"points\": [';
var params = polyline.getLatLngs();
var i;
for (i = 0; i < points.length; i++) {
params = params.concat('{\"latitude\": ', points[i].lat, ', \"longitude\": ', points[i].lng, '}');
if (i < points.length - 1) {
params = params.concat(', ');
}
}
params = params.concat('] }');
return JSON.parse(params);
}
I want to catch it with something like (Objective-C):
NSString *s = [self.webView stringByEvaluatingJavaScriptFromString:#"callback();"];
Obviously this results in a NSString, what I really want is NSData to do this (Objective-C):
NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONWritingPrettyPrinted error:&error];
So, how to properly return the JSON?

This should do it:
function callback() {
var params = polyline.getLatLngs();
var result = [];
var i;
for (i = 0; i < params.length; i++) {
result.push({latitute: params[i].lat, longitude: params[i].long});
}
return JSON.stringify({points: result});
}
Note that JSON.parse generates an object from a string, and JSON.stringify creates a string from an object. No need to do it manually.

Related

Save text from javascript variable to .txt file

I am trying this code, but can't get it to work, it says "The name "text" does not exist in the current context"
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){ var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
How can I make variable "textt" accessible?
Here is a full code:
private void button3_Click(object sender, EventArgs e)
{
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("var elems1 = document.getElementsByClassName('question-text')");
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
}
You might be looking for ContinueWith() which can be chained after ExecuteJavaScriptAsync().
In this example you need to use your JavaScript code as a function which returns anything (ex. textt). So I've created something like this:
var myScript = #"(function () {
var textt = "";
var elems1 = document.getElementsByClassName('question-text');
for(var i = 0; i < elems1.length; i++){
textt += elems1[i].innerText
}
return textt;
})();";
than I asynchronously evaluate it and catch the result which I am returning from that function:
var result = await CurBrowser
.GetMainFrame()
.EvaluateScriptAsync(myScript)
.ContinueWith(t => {
var result = t.Result; // your textt
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true)) {
outputFile.WriteLine(result);
}
});
this is just a suggestion of how it might work.

Outputting PHP string into a JS file causes syntax error

I'm trying to output a string into a JS file using PHP. Here's the PHP code
$embedded_form_js = "document.addEventListener('DOMContentLoaded', function(){
var parts = window.location.search.substr(1).split('&');
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split('=');
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
var ref = $_GET['ref'];
if (ref === 'undefined')
{
ref = 0;
}
}, false);";
I'm trying to write a JS file like so
$fp = fopen("FOLDER/FILE.js", 'w');
fwrite($fp, $embedded_form_js);
fclose($fp);
The problem is that when I try to write the JS file, this error happens.
syntax error, unexpected '(', expecting ']'
This is in reference to the line:
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
How can I remedy this?
use Nowdocs as it is single-quoted and won't try to interpret the $_GET
$embedded_form_js = <<<'EOS'
document.addEventListener('DOMContentLoaded', function(){
var parts = window.location.search.substr(1).split('&');
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split('=');
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
var ref = $_GET['ref'];
if (ref === 'undefined')
{
ref = 0;
}
}, false);
EOS;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

Encrypt & decrypt URL parameters in spring

I would like to encrypt URL GET parameters that all links will be something like below.
Encrypted in html:
home.htm?ecryptParam=aajsbjabsjvyhasyayasy
Actual:
home.htm?fName=samir&lName=vora
At the same time, in controller class it will have the decrypted value automatically and I can retrieve it from request. e.g.:
Link:
home.htm?ecrypt=SKJIIU86iuGkJGkJFHGBVBVn
Controller class:
request.getParameter("fName"); will return samir
Samir, If you passing value as encrypt format in url and you will retrieve using request param as encrypt format, and you will need to decrypt those values for that please refer this link "http://www.code2learn.com/2011/06/encryption-and-decryption-of-data-using.html". It might help.
While you really should handle security backend, simple text obfuscation can be easily achived in JavaScript.
Here is an example:
//Encrypter class
var stringEncrypter = (function() {
function stringEncrypter() {}
stringEncrypter.encrypt = function(str) {
str = str.toString();
var returnCode = [];
for (var strIndex = 0; strIndex < str.length; strIndex++) {
var element = str[strIndex];
//Push with bitwise offset (or remove the bitwise offset here and in decrypt)
returnCode.push(element.charCodeAt(0) << this.off);
}
//return a joined string
return returnCode.join(this.splitter);
};
stringEncrypter.decrypt = function(str) {
var list = str.split(this.splitter);
var returnCode = "";
for (var strIndex = 0; strIndex < list.length; strIndex++) {
var element = list[strIndex];
//Push with bitwise offset (or remove the bitwise offset here and in encrypt)
returnCode += String.fromCharCode(parseInt(element) >> this.off);
}
return returnCode;
};
stringEncrypter.encryptUrl = function(url) {
if (url.substr(url.indexOf("?") >= 0)) {
var str = url.substr(url.indexOf("?") + 1);
if (str.lastIndexOf("#") >= 0) {
str = str.substr(0, str.lastIndexOf("#"));
}
var params = str.split("&");
for (var paramIndex = 0; paramIndex < params.length; paramIndex++) {
var param = params[paramIndex].split("=");
param[0] = this.encrypt(param[0]);
param[1] = this.encrypt(param[1]);
params[paramIndex] = param.join("=");
}
url = url.substr(0, url.indexOf("?") + 1) + params.join("&") +
(url.lastIndexOf("#") >= 0 ? url.substr(url.lastIndexOf("#")) : "");
}
return url;
};
stringEncrypter.decryptUrl = function(url) {
if (url.substr(url.indexOf("?") >= 0)) {
var str = url.substr(url.indexOf("?") + 1);
if (str.lastIndexOf("#") >= 0) {
str = str.substr(0, str.lastIndexOf("#"));
}
var params = str.split("&");
for (var paramIndex = 0; paramIndex < params.length; paramIndex++) {
var param = params[paramIndex].split("=");
param[0] = this.decrypt(param[0]);
param[1] = this.decrypt(param[1]);
params[paramIndex] = param.join("=");
}
url = url.substr(0, url.indexOf("?") + 1) + params.join("&") +
(url.lastIndexOf("#") >= 0 ? url.substr(url.lastIndexOf("#")) : "");
}
return url;
};
return stringEncrypter;
}());
//Bitwise offset. Completely optional
stringEncrypter.off = 2;
stringEncrypter.splitter = "|";
//Encrypt a string
console.log(stringEncrypter.encrypt("Testing123"));
//Decrypt a string
console.log(stringEncrypter.decrypt(stringEncrypter.encrypt("Testing123")));
//Decrypt a url
console.log(stringEncrypter.encryptUrl("www.test.dk?test=45"));
//Encrypt a url
console.log(stringEncrypter.decryptUrl(stringEncrypter.encryptUrl("www.test.dk?test=45")));
//Decrypt a url with #
console.log(stringEncrypter.encryptUrl("www.test.dk?test=45#title1"));
//Encrypt a url with #
console.log(stringEncrypter.decryptUrl(stringEncrypter.encryptUrl("www.test.dk?test=45#title1")));

Prase query string from url javascript

my url look like http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1
now i am looking for a function where i will pass url and query string name then that should return value.
so i did it this way but not working.
function getQueryVariable(url,variable) {
var query = url;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
calling like this way
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert(getQueryVariable(x,'sort'));
alert(getQueryVariable(x,'sortdir'));
alert(getQueryVariable(x,'page'));
where i made the mistake?
EDIT
working code
$.urlParam = function(url,name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert($.urlParam(x,'sort'));
alert($.urlParam(x,'sortdir'));
alert($.urlParam(x,'page'));
https://jsfiddle.net/z99L3985/1/
thanks
may be the following will help
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1';
var queryVars = getUrlVars(x);
alert(queryVars['sort']);
alert(queryVars['sortdir']);
alert(queryVars['page']);
I just get this from somewhere else as well..
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
console.log(vars);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] === variable){return pair[1];}
}
return(false);
}
so far its doing its job.
with url: "http://urlhere.com/general_journal?from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2"
if im going to get the 'page' variable result would be : `2`
console.log(getQueryVariable('page'));
my query variable is only getting the search.substring(1) part of the the url so basically it only gets from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2 part of the url then from that it splits it and then return the value of the string parameter you specified on the function call getQueryVariable('page') for example.
Maybe this helps
var getUrlVars = function(url){
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == url){
vars =[];
}
return vars;
}
Then in your code
var params = getUrlVars("http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1");
console.log(params["sort"]) // FirstName

How do I build my JSON object using two parts when concatenated together produces the correct JSON data path

Is this possible to do, or how do I do it?
arrayElement = new Object();
JSONkey = jsonData.table[0].key; // key in table[0] is "ident/Lesson/Value"
JSONkey = JSONkey.replace(/\//g, '.'); // now JSONkey is "ident.Lesson.Value"
arrayElement.JSONkey = "value1" // Can I do this or how would I?
So arrayElement.JSONkey is the same as arrayElement.ident.Lesson.Value
arrayElement = new Object();
JSONkey = jsonData.table[0].key; // key in table[0] is "ident/Lesson/Value"
JSONkey = JSONkey.replace(/\//g, '.'); // now JSONkey is "ident.Lesson.Value"
deepRef(arrayElement, JSONkey, "value1");
function deepRef(ref, key, value) {
var segments = key.split("."),
n = segments.length;
for (var i=0, skey; i<n; i++) {
skey = segments[i];
if (i < n - 1) {
ref[skey] = {};
ref = ref[skey];
} else {
ref[skey] = value;
}
}
}

Categories

Resources