I am currently dynamically loading various JSPs using an Ajax call. However, once a JSP is loaded none of the Javascript contained inside is working. I am assuming this is because the Script inside has not been parsed yet.
To that end I found the module "aui-parse-content" which, according to its description, should be able to parse the contained script.
The ParseContent Utility - Parse the content of a Node so that all of the javascript contained in that Node will be executed according to the order that it appears.
However, I can't get it to work. Here is my AUI:Script for reference.
<portlet:resourceURL var="viewContentURL">
<portlet:param name="jsp" value="<%= tmp %>"/>
</portlet:resourceURL>
<div id="<portlet:namespace />jspcontent"></div>
<aui:script use="aui-base, aui-io-request,aui-parse-content, aui-node">
var url = '<%= viewContentURL.toString() %>';
AUI().io.request(
url,
{
on:{
success: function(){
var message = this.get('responseData');
//alert(message);
AUI().one('#<portlet:namespace />jspcontent').html(message);
AUI().one('#<portlet:namespace />jspcontent').plug(AUI().Plugin.ParseContent);
},
failure: function(){
alert("An error occured");
}
}
}
);
</aui:script>
Thank you in advance!
-John
Edit:
Since I found a fix a while ago and others might have the same problem this is how I got aui-parse-content working:
on:{
success: function(){
var message = this.get('responseData');
var tmp = A.one('#<portlet:namespace />jspcontent');
tmp.html(message);
tmp.plug(A.Plugin.ParseContent);
tmp.ParseContent.parseContent(message);
},
}
I found a fix a while ago and others might have the same problem this is how I got aui-parse-content working:
on:{
success: function(){
var message = this.get('responseData');
var tmp = A.one('#<portlet:namespace />jspcontent');
tmp.html(message);
tmp.plug(A.Plugin.ParseContent);
tmp.ParseContent.parseContent(message);
},
}
I also amended my original post to reflect my findings
Related
There is a web page. In page source have script:
<script>
var important = [{....}];
</script>
How get information from this variable with use node.js???
In a similar situation, when information was in function:
$(function() {
_very.important ([{....}]);
I use code:
var cloudscraper = require("cloudscraper");
cloudscraper.get("link" , function(error, response, data) {
if (error) {
console.log('ERRRRRRROR');
} else {
var info = JSON.parse(data.split("_very.important(")[1].split(")")[0]);
But, I dont know how work with this problem.
var important = [{....}];
You can assign a id to the script like <script id="script"> and get the details through innerHTML like
document.getElementById('script').innerHTML
I'm trying to make a client-server application where from the client I send a request through a JSON object to the server to register. The thing is I should get another JSON with an "OK" field (which is actually being sent) but for some reason the client keeps going to the .fail function instead of the .done one (sorry if some of used terms are not very accurate, I'm new to this).
So I'll this is my code incase you can check if there's anything wrong causing this:
Client JS:
define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'jquery', 'ojs/ojknockout', 'ojs/ojinputtext'],
function(oj, ko, $, app) {
function RegistrarseViewModel() {
var self = this;
this.email = ko.observable();
this.pwd1 = ko.observable();
this.pwd2 = ko.observable();
this.registrar = function(){
alert("Se ha mandado el registro");
var p = {tipo:"Registrarse",email: this.email(), pwd1:this.pwd1(), pwd2:this.pwd2()};
$.ajax({
type:"POST",
url:"http://localhost:8080/ServidorWeb/Registrarse.jsp",
data: "p=" + JSON.stringify(p)
}).done(function(data, textStatus, jqXHR){
alert("Comprobando tipo");
if (data.tipo == "OK"){
//window.location="index.html?root=juegos"
sessionStorage.jugador=self.email();
app.router.go("login");
alert("Registro correcto");
}else
alert(respuesta.texto)
}).fail(function() {
alert("Sorry. Server unavailable. lol ");
});
}
this.cancelar = function(){
app.router.go("login");
}
}
return new RegistrarseViewModel();
}
);
Server JSP:
<%# page language="java" contentType="application/json ; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import= "org.json.*,dominio.Manager"%>
<%
String p = request.getParameter("p");
JSONObject resultado=new JSONObject();
try{
JSONObject jso= new JSONObject(p);
if(!jso.getString("tipo").equals("Registrarse")){
resultado.put("tipo","NOK");
resultado.put("texto","Mensaje inesperado");
}else{
String email=jso.getString("email");
String pwd1=jso.getString("pwd1");
String pwd2=jso.getString("pwd2");
Manager.get().registrarse(email,pwd1,pwd2);
resultado.put("tipo","OK");
resultado.put("texto","Te has registrado con el email " + email);
}
}
catch(Exception e){
resultado.put("tipo","NOK");
resultado.put("texto","Mensaje Inesperadoo");
}
%>
<%=resultado.toString()%>
After executing Manager.get().registrarse(email,pwd1,pwd2); (which is the logic to register into a MongoDB) it just continues with the resultado.put("tipo","OK"); line which means the problem isn't in there.
Also if I send the request http://localhost:8080/ServidorWeb/Registrarse.jsp?p=%7Btipo:%22Registrarse%22,email:%2233%22,pwd1:%2220%22,pwd2:%2220%22%7D from a browser like Google Chrome it prints this: {"texto":"Te has registrado con el email 33","tipo":"OK"} but from the real client it just won't get into the .done function, idk why.
I really hope you can help me.
Thanks in advance.
EDIT 1: Added the server response from the browser console IMAGE
Okay I solved this finally.
I had to add this line at the beggining of the .jsp, this was an issu with TomCat which has something like 2 machines and without this line it doesn't allow communication among different machines because of security reasons it seems.
response.setHeader("Access-Control-Allow-Origin", "*");
if you use jquery the correct way is use serialize function from jquery
https://api.jquery.com/serialize/
first give a id for you form something like :
`
$("#myform form").submit(function(event){
event.preventDefault();
var sendData = $("#myform form").serialize();
$.post("your-PHP-handler.php", sendData);
});
<form id="myform" method="post" action="your-PHP-handler.php">
<input type="name" placeholder="name">
<input type="name" placeholder="age">
<input type="name" placeholder="address">
<button type="submit">send</button>
</form>
`
note when you submit your form via javascript the serialization jquery get all inputs in your post end send all together you cam handler the response php inside of $.post() you can make many things with this consulting jquery documentation.
anyway the basic is there , get everything inside my form and send to my php file
I'm trying to use flask with url_for. The problem is that when I try to launch an alert with the value of the javascript variable everything seems ok, but when I try to launch a alert with the url_for the content of the variable is not printed. What I'm doing wrong? or What is missing in my code?
How can I pass a JavaScript variable into the url_for function?
html code:
<a class="dissable_user_btn" data-user_id="{{user.id}}" href="#" title="Change Status"><i class="fa fa-plug"></i>
</a>
JS Code:
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id) //everything ok
alert ('{{url_for('.dissable', _id=user_id)}}'); //dont print the valur of user_id
</script>
Short answer: you can't. Flask & Jinja2 render the template on the server side (e.g. Flask is translating all of the {{ }} stuff before it sends the HTML to the web browser).
For a URL like this where you're including a variable as part of the path you'd need to build this manually in javascript. If this is an XHR endpoint I'd recommend using GET/POST to transfer the values to the server as a better best practice than constructing the URL this way. This way you can use Jinja:
$(document).ready(function(){
var baseUrl = "{{ url_for('disable') }}";
$('.dissable_user_btn').click(function(event) {
var user_id = $(this).data("user_id");
// first part = url to send data
// second part = info to send as query string (url?user=user_id)
// third parameter = function to handle response from server
$.getJSON(baseUrl, {user: user_id}, function(response) {
console.log(response);
});
});
});
I found another solution for this. My problem started when I needed to pass a variable with space.
First I created a function to remove trailing and leading spaces
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
After that, I used the function and encoded the URL
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id)
user_id = strip(user_id).replace(" ","%20");
alert ('{{url_for('.dissable', _id='user_id')}}.replace('user_id',user_id);
</script>
It worked pretty nice for me!
This is how I applied to my problem
<script>
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
$(document).ready(function() {
$('#exportcountry').click(function() {
var elemento = document.getElementById("countryexportbtn");
var country = strip(elemento.textContent).replace(" ","%20");
$('#exportevent').load("{{ url_for('get_events',country = 'pais') }}".replace('pais',country));
});
});
</script>
I wrote the script below to get values from a Json file that is stored inside a industrial automation equipment. The script is inside a HTML page that is stored in a PC and replaces Div contents based on its ID. Note: I can't run any code on the industrial equipment. This is not a "real server". It just stores Json files and update its values based in real sensors.
Script inside index.html
<script>
function callback(json)
{
document.getElementById("Nro_Ensaio").innerHTML = json.Nro_Ensaio;
document.getElementById("SP_Pelotas1").innerHTML = json.SP_Pelotas;
document.getElementById("SP_Pelotas2").innerHTML = json.SP_Pelotas;
document.getElementById("PV_Pelotas1").innerHTML = json.PV_Pelotas;
document.getElementById("Status").innerHTML = json.Status;
}
</script>
<script type="text/javascript" src="http://192.168.0.103/awp/VAR_PRENSAS/ensaio.json"></script>
ensaio.json file
callback({
'Inicia': ':="ENSAIO".CMDS.LIBERA:',
'Rearme': ':="ENSAIO".CMDS.RESET:',
'Nro_Serie': ':="ENSAIO".Nro_Serie:',
'Modelo': ':="ENSAIO".Modelo:',
'Nro_Ensaio': ':="ENSAIO".Nro_Ensaio:',
'Pronto': ':="ENSAIO".Pronto:',
'Data': ':="ENSAIO".Data:',
'Hora': ':="ENSAIO".Hora:',
'SP_Pelotas': ':="ENSAIO".SP_Pelotas:',
'PV_Pelotas': ':="ENSAIO".PV_Pelotas:',
'Status': ':="ENSAIO".Status:'
});
When I open index.html in a browser I can view all values on the places that I really want, but I need a way to get this values refreshed. I tried to refresh the page using the script below, but div values flickers every time.
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(5000);">
How can I update div contents from the Json file every second without flickering the page?
Very important Information: I can't enable cross-domain requests on this "server".
More information about creating pages for this equipment here! http://www.dmcinfo.com/latest-thinking/blog/articletype/articleview/articleid/8567/siemens-s7-1200-web-server-tutorial--from-getting-started-to-html5-user-defined-pages
Thanks!
I tryed to do this script below.
<script>
function callback(json)
{
document.getElementById("Nro_Ensaio").innerHTML = json.Nro_Ensaio;
document.getElementById("SP_Pelotas1").innerHTML = json.SP_Pelotas;
document.getElementById("SP_Pelotas2").innerHTML = json.SP_Pelotas;
document.getElementById("PV_Pelotas1").innerHTML = json.PV_Pelotas;
document.getElementById("Status").innerHTML = json.Status;
}
setInterval(callback,1000);
</script>
<script type="text/javascript" src="192.168.0.103/awp/VAR_PRENSAS/ensaio.json"></script>
Ensaio.json Content
callback({
'Inicia': '0',
'Rearme': '0',
'Nro_Serie': '010',
'Modelo': 'CPT001',
'Nro_Ensaio': '138',
'Pronto': '0',
'Data': '18-07-2014',
'Hora': '10-02',
'SP_Pelotas': '40',
'PV_Pelotas': '1',
'Status': 'ENSAIO',
'Nome': 'Test',
'Descricao': 'Test1'
});
I tried changing the src attribute of the script tag in Javascript, but it seems as though the script tag needs to be replaced for the script to load. Here's a function that takes a script URI and an interval and then reloads the script indefinitely, without piling up a bunch of script tags:
var scriptLoader = (function () {
var head = document.getElementsByTagName("head")[0];
return function (scriptURI, interval) {
var scriptElement = null;
setInterval(function () {
var newScriptElement = document.createElement('script');
newScriptElement.type = 'text/javascript';
newScriptElement.onerror = function (error) {
throw new URIError('Could not load script ' + error.target.src);
};
if (scriptElement) {
head.replaceChild(newScriptElement, scriptElement);
} else {
head.appendChild(newScriptElement);
}
newScriptElement.src = scriptURI;
scriptElement = newScriptElement;
}, interval);
}
}());
It's used like this:
window.onload = function () {
scriptLoader("http://192.168.0.103/awp/VAR_PRENSAS/ensaio.json", 10000);
};
[EDIT: this answer is only valid if you can set Access-Control-Allow-Origin headers on your server. also, my answer is sans jquery.]
if i understand you correctly, the name for what you are trying to do is asyncronous http requests. that means that you want to get more information from a server without reloading the whole page. the javascript technology that is used to do so is called ajax or XHR. here is an example of how to use ajax. you will want to replace the URL in xmlhttp.open("GET","ajax_info.txt",true); with the (complete) URL of the file on the server you want to access, i.e. http://..... the response that your requests gets from the server is stored in xmlhttp.responseText where xmlhttp is the name of the variable assigned to the ajax request.
[EDIT: in light of new information, maybe you'd prefer reloading an iframe than the whole page? not an awesome solution but iframes don't require cross-site request.]
I trid to use an upload plugin for jQuery.
http://valums.com/ajax-upload/
When I set the returning respond type to json, firefox will popup a dialog asking how I like to handle the returning json object.
People have asked the same question at the upload script's author's page but no answer so far. Hopefully javascript guys here can figure out how we can handle this.
Thanks.
<script type= "text/javascript">
/*<![CDATA[*/
$(document).ready(function(){
/* example 1 */
var button = $('#button1'), interval;
new AjaxUpload(button, {
//action: 'upload-test.php', // I disabled uploads in this example for security reasons
action: '/posts/upload_images/',
name: 'myfile',
responseType: 'json',
onSubmit : function(file, ext){
// change button text, when user selects file
button.text('Uploading');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function(){
var text = button.text();
if (text.length < 13){
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response){
var json = response;
alert(json);
button.text('Upload');
window.clearInterval(interval);
// enable upload button
this.enable();
// add file to the list
// $('<li></li>').appendTo('#example1 .files').text(json.response_text);
$('<li></li>').appendTo('#example1 .files').text(file);
}
});
});
/*]]>*/
</script>
http://api.jquery.com/jQuery.parseJSON/
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
This jQuery plugin makes it simple to convert to and from JSON: http://code.google.com/p/jquery-json/
Also, you might be interested in this comment on the blog post you referenced:
Sorry to spam your blog post (which is great), but I thought I’d mention that I found the problem:
For whatever reason, the response always has <pre> tags around the entire response when the response is of type plain/text. That was causing the eval() call to fail. My current solution was just to strip those tags off before the eval() call and now everything works. Not a great solution but at least I can keep working for now.
I was looking for a solution for the same script and stumbled upon this page. I didn't found a solution online so here's how I fixed it:
# upload-file.php:
replace
echo "success".$cc;
with
echo json_encode(array(
status' => 'success',
'id' => $picid,
'image' => $imgurl
));
# front end:
replace
var bb=response.substr(0,7)
var idd=response.replace('success',' ');
var idb =idd.replace(/^\s*|\s*$/g,'');
if(bb==="success")
{
$('<span></span>').appendTo('#files').html('<img src="images/'+file+'" alt="" width="120" height="120" style="margin:5px;" />').addClass('success');
}
else
{
$('<span></span>').appendTo('#files').text(file).addClass('error');
}
with
var what = jQuery.parseJSON(response);
if(what.status == 'success')
{
$('<span id='+what.id+'></span>').appendTo('#files').html('<img src="'+what.image+'" alt="" width="120" height="120" style="margin:5px;" /><br>Delete').addClass('success');
}
else
{
$('<span></span>').appendTo('#files').text(response).addClass('error');
}
And to actually answer this question.
jQuery.parseJSON(response);
does..
This may be it, I don't know because I know nothing about that plugin, but you may need to take a look at the response type you are setting on the server-side of things; you should set the HTTP response to have a content/MIME type of something like "text/plain", "text/javascript" or "application/javascript" - see if that fixes your problem.