append method using the from inside an Jquery $getJSON - javascript

Ok, so I have 3 files,
First a JSON file that tells me all the information that I need,
A Html file that gives me like a skeleton of where to put all the javascript
A javascript file that will hook up the information from the JSON and put into the html.
So my HTML is something like:
<div class="hello">
<h2>Name</h2>
</div>
My JSON is this with root to data/bio.json:
{
"name" : "Olivia Palito",
"age" : "23"
}
My Javascript is like this:
var mockup = '<div class="work"></div>';
var mockup02 = '<div>%data%</div>';
var $addItem01 = $(".hello");
var $addItem02 = $(".work");
var jsonRoot = 'data/bio.json';
$.getJSON(jsonRoot, function(data){
var addMe = mockup.replace('%data%', data.name);
$addItem01.append(mockup);
$addItem02.append(addMe);
});
Now the problem,
When I run this on the browser, I can add the first mockup, and it will add the <div class="work"></div> but when I try to add also the addMe, it doesn't show anything.
What am I missing here?
And if I put console.log(data); it will show something, which means that I am receiving the file, but it just not adding to the html, because I can add also static text, instead of using the replace method, and won't add the content.

var mockup02 = mockup.replace(%data%, data.name);
It does not work because that is not valid JavaScript.
Open up the console and you should see the error
Uncaught SyntaxError: Unexpected token %
You need to make it a regular expression
var mockup02 = mockup.replace(/%data%/, data.name);
or a string
var mockup02 = mockup.replace("%data%", data.name);
And the second reason it fails is you are selecting the element with the class work before it is added to the page. It does not magically find the element.
Switching it to and it will add it.
$(".work").append(addMe);

Related

how to render a form using JSON in JQuery Form builder

i have simple web application where i can create forms and save its JSON in a database then get the same JSON and Render it back , all built using the Jquery FormBuilder that is available online. Right Now , I am Struggling with render part because it doesnt display anything , and my knowledge in java script is pretty limited to fix it .
here is what i have done so far
for the PHP side , i can take the Json schema and give it to a variable , i tested it and the value is there and can be printed
$json=$row['survey_schema'];
for the java script part
var container = $('#formrender');var options = {
container,
dataType:'json',
formData:'<?php $json ?>' }; container.formRender(options);
as for the HTML
<div id="formrender"></div>
from what i understand the script looks for the div named formrender and renders the form based on the provided JSON that i gave it to it .
but nothing happens and it is just a blank screen
thank you , and sorry for my bad english
This is available in jQuery Form builder documentation, and this is how I did it:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/highlight.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-render.min.js"></script>
<script>
jQuery($ => {
const escapeEl = document.createElement("textarea");
const code = document.getElementById("formrender");
const formData = "";//Your JSON data goes here
const addLineBreaks = html => html.replace(new RegExp("><", "g"), ">\n<");
// Grab markup and escape it
const $markup = $("<div/>");
$markup.formRender({ formData });
// set < code > innerText with escaped markup
code.innerHTML = addLineBreaks($markup.formRender("html"));
hljs.highlightBlock(code);
});
</script>

My javascript code can't recognise my array element defined in Python

So I'm trying to open a new window by executing a script in Selenium using driver.execute_script("window.open('');")
But I want to open a link given by the user.
So I got the link input from my array and put it to my javascript code just like this:
driver.execute_script("window.open(data[0]);")
Now It's giving an error like this:
selenium.common.exceptions.JavascriptException: Message: javascript error: data is not defined
How to fix this? Thanks for your time.
EDIT: A part of my code is something like that:
from selenium import webdriver
import PySimpleGUI as sg
import time
global data
data = []
layouts = [[[sg.Text("Enter the Wordpress New Post link: "), sg.InputText(key=0)]],
[sg.Button('Start The Process'), [sg.Button('Exit')]]]
window = sg.Window("Title", layouts)
def selenium_process():
# Getting the driver path
driver = webdriver.Chrome(r'Driver\path')
driver.get('https://google.com')
driver.execute_script(f"window.open({data[0]});")
time.sleep(10000)
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
data.append(values[0])
selenium_process()
did you try string interpolation ?
Try this:
driver.execute_script(f"window.open({data[0]});")
Your solution does not work since data[0] is a string, not a variable. You instead need to substitute data[0] with its value (must be a value that JS can understand).
Please read the description of Javascript window.open : https://developer.mozilla.org/fr/docs/Web/API/Window/open
If you just need to get to an URL:
driver.get(data[0])

Print data from json file

I have json file with given data (total.json)
var data = {"trololo":{"info":"61511","path".... }}
I need to get object "info" and then print data "61511" in alert window
I include my json like
var FILE = 'total'
var data_file_names = {};
data_file_names[FILE] = 'total.json';
And then i use it like
var data_trololo = data_file_names[FILE];
Plese, help me print object "info". Maybe there is another way to solve this problem
You need to make an ajax call to the json file. Then you can access the array like the below example.
Note : Your json wasn't properly formatted.
var data = {
"trololo":{
"info": ["61511","path"]
}
};
console.log(data.trololo.info[0]); //this one will print 61511
Usually one can make an ajax call to read the file on the server.
But if you are ok with using HTML5 features then go through the link find out how to read the file on the browser itself. Though File API being part of HTML5 spec is stable across browsers.
http://www.html5rocks.com/en/tutorials/file/dndfiles/

MVC 5 CKEditor SetData to editor from DB

Almost got everything working with CKEditor plugin and the only problem left is to load the data already saved to the DB into the WYSIWYG editor.
If i try something like this in javascript as a test it works fine.
<script>
var value = "<h1>Awesome</h1>";
var config = {};
editor = CKEDITOR.appendTo('editor', config, html);
editor.setData(value);
</script>
So this creates the editor and actually tries to load the "html" variable into it but this is currently just empty.
So if I look in my DB I have a field called Description (nvarchar(max),null) which currently has this value: <h1>Awesome</h1>
But if I try to get this value in Javascript I get an error:
Uncaught SyntaxError: Unexpected token ILLEGAL
And if i look at the console log it looks like this:
var value = '<h1>Awesome</h1>
Uncaught SyntaxError: Unexpected token ILLEGAL
';
UPDATE
Ok, after some experimenting I managed to create a working solution.
I created a hidden field for the Description
#Html.HiddenFor(m => m.Note.Description)
And I am showing it like this:
<div id="editorcontents" class="well padding-10">
#Html.Raw(Model.Note.Description)
</div>
And when I go into edit mode I hide the editor and set the value to the editor from the hidden field.
if (editor)
return;
$('#editorcontents').hide();
var config = {};
var html = $('#Note_Description').val();
editor = CKEDITOR.appendTo('editor', config, html);
And in the success method of my ajax update function I destroy the editor and update the value in the hidden field.
success: function (data) {
editor.destroy();
editor = null;
$('#Note_Description').val(data[2].Description);
}
So somehow getting the value with Jquery fixed the problem.

How to insert javascript variable inside ejs tags

I am doing dynamic filtering ,but i am unable to do if condition check.
i want to insert targetOS var inside <%if(data[i].ListNames == targetOS ){%>
for the above syntax it is giving "targetOS variable is undefined"
Please help on this.
$(document).on("change",'.COTSCurrentOSClass', function(e){
var selectedOS = $(this).val();
var targetOS = "OS::From::"+selectedOS;
<%for(var i=0;i<data.length;i++){%>
<%if(data[i].ListNames == ***targetOS*** ){%>
<%for(var j=0;j<data[i].Values.length;j++){%>
console.log("options are");
console.log(data[i].Values[j]);
<%}}}%>
($(this).parent().parent()).find(".COTSTargetOSClass").append("<option>Select One</option>");
});
What you want to do is not possible!
This is the sequence of what happens:
1 - In the server, the ejs is rendered to HTML
2 - the HTML is then transferred into the browser
3 - The browser reads and processes the javascript
The JavaScript execution happens at a much later stage than the ejs execution.
What #fmsf has replied is correct. However, if you know the targetOS value on the server, while rendering the ejs you can do it like this:
define it like this in your ejs file:
var TARGET_OS = "<%= TARGET_OS %>";
Then when you render the page via ejs, pass parameter to it like this:
res.render(url, {TARGET_OS: "Your desired value here"}, function(err, html) {

Categories