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
Related
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.
I need some help, i can't understand why my json is returning false...
This is my Ajax :
var xhr10 = getXhr();
length=document.getElementById('ChoosenStuff').options.length;
ListChoosenStuffNames = [];
for(var i=0;i<length;i++)
{
ListChoosenStuffNames[i] = document.getElementById('ChoosenStuff').options[i].value;
}
xhr10.onreadystatechange = function(){
if(xhr10.readyState === 4 && xhr10.status === 200){
Selection = JSON.parse(xhr10.responseText);
for(var i = 0; i < Selection.length; i++) {
document.getElementById('ShowResult').innerHTML += Selection[i] + "\n\r";
}
}
};
xhr10.open("POST","Ajax/AjaxGetDTravauxCorrespondant.php",true);
xhr10.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr10.send("ListChoosenStuffNames="+ListChoosenStuffNames);
And then my php file with my query which works on phpMyAdmin :
include '../Reglage/ConnexionBDD.php';
$res = [];
$Query="Select NomDomaineTravaux from equipement
JOIN typeequipement ON equipement.CodeTypeEquipement =
typeequipement.CodeTypeEquipement
JOIN domainetravaux ON typeequipement.IDDomaineTravaux =
domainetravaux.IDDomaineTravaux
WHERE NomEquipement=:stuff";
$rep = $bdd->prepare($Query);
$custom = $_POST['nomsEquipementsChoisis'];
$rep->bindParam(':stuff',$custom);
$rep->execute();
$NomDomaineTravaux= $rep->fetch(PDO::FETCH_ASSOC);
$res[$i]= $NomDomaineTravaux;
echo json_encode($res, true);
I have {NomDomaineTravaux: "Divers"}
how do i use this to display "Divers" in my js file with obj = JSON.parse(xhr.reponseText) ?
I tried obj.NomDomaineTravaux but it says that he dont recognize this... :(
Thanks A LOT,
I've just coded a little script to replace all variables from a .txt file to their values in a JS file
Example:
Txt file example (values):
Hi = "HELLO WORLD",
Hey = /someregex/g,
Hh = 'haha';
Script example:
window[Hi] = true;
"someregex hi".replace(Hey, "")
window[Hh] = 1;
Here's my script:
var fs = require("fs")
var script = fs.readFileSync("./script.js", "utf8");
var vars = fs.readFileSync("./vars.txt", "utf8");
var replace = {}
var spl = vars.replace(/\r\n/g, "").replace(/ /g, "").split(",");
console.log("caching variables")
for(var dt of spl) {
var splt = dt.split(" = ");
var name = splt[0];
var val = splt[1];
if(!name || !val) {
continue;
}
if(val.endsWith(";")) {
val = val.slice(0, -1);
}
replace[name] = val;
}
console.log("Variables are in cache!")
console.log("Replacing variables in script")
var i = 1;
var t = Object.keys(replace).length;
for(var var_name in replace) {
var var_val = replace[var_name];
var regex = new RegExp(var_name, "g");
console.log(i, "/", t, "Replacing", var_name, "with", var_val, "regex", regex)
script = script.replace(regex, var_val);
i++;
}
console.log("DONE!")
fs.writeFileSync("./dec.js", script, "utf8")
However, when i ~= 100, I have this error:
RangeError: Invalid string length
at RegExp.[Symbol.replace] (native)
at String.replace (native)
EDIT: also, I can see that node.js process is using ~400MB of RAM and I have the error when it reaches 900MB
What's wrong?
I have created script for storing some data. Function demo returns data in JSON format. But I want to create a JSON file for my external project.
var demo = function(table) {
// JSON file
var data = [];
var headers = [];
headers[0] = 'img';
// filling headers
for( var i = 1; i < table.rows[0].cells.length; i++ ) {
headers.push(table.rows[0].cells[i].children[0].text.toLowerCase().replace(/\s/g, ''));
};
for( var i = 1; i < table.rows.length; i++ ) {
var obj = {};
for( var j = 0; j < table.rows[i].cells.length; j++ ) {
var cells = table.rows[i].cells[j];
switch (headers[j]) {
case 'img':
obj[headers[j]] = cells.childNodes[0].childNodes[0].getAttribute('src');
break;
case 'name':
obj[headers[j]] = cells.childNodes[0].text;
break;
default:
obj[headers[j]] = cells.innerHTML;
break;
}
}
data.push(obj);
}
return data;
}
demo(document.getElementById('the_list'));
My question: Is there any possible to export "data" variable to file.txt ?
You can use FileSaver.js -> https://github.com/eligrey/FileSaver.js
Here is an example saving a JSON variable :
var json = {
"test" : "qwerty"
}
document.getElementById('save').onclick = function() {
var textToSave = JSON.stringify(json),
filename = 'file.txt',
blob = new Blob([textToSave], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename);
}
working fiddle -> http://jsfiddle.net/sf0o8d4j/1/
But as mentioned in comment, I really cant see why you should save it as a file locally on the client filesystem rather than using localStorage.
I'm trying to save a HUGE json string in my localStorage but for some reason sometimes it saves it and sometimes not, I thought I should compress it so I took an LZW implementation in js from one of the threads in stackoverflow.
The problem is when I try to localStorage.setItem() the compressed string it gives me an error "Invalid argument", any idea why or what should I do?
Edit:
this is the code I'm using:
// LZW-compress a string
function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
this is the code that calls the compressing algorithm and saves it in LS
LOG("GetMerchantList(): Done");
var SITESVAR = unescape(data)
localStorage.setItem("MYSITES", lzw_encode(SITESVAR)); //this throws error
IWT.BuildMerchantList(SITESVAR);