Setting variable from .CTP view to .JS - javascript

I'm having an extremely annoying and non-sense problem, are you prepared? :x
Ok, let's go:
Actualy I have an specific software deployed into 4 environments : Development, Certification, Preproduction and Production.
Yesterday I've received an error report in Production environment.
Thing is when I try to set a javascript variable from my .ctp to my .js my .js cant access that variable so the 'set' is not done. The weird thing is that in other environments (DES, CERT and PRE) that works perfectly but in PRO (for a certain casuistic it fails).
Sketching the problem:
translate.ctp
<?php
$translations = array();
$translations['NO_DATA']=__('NODATA');
$translations['VALUE']=__('VAL');
$translations['WEBROOT'] = $this->webroot;
$this->Js->set('translations',$translations); // <-- prepare 'translations' into JS as window.app.translations
echo $this->Js->writeBuffer(array('onDomReady' => false)); // sets the variable 'translations' into the javascript (I only use writeBuffer once in this code and project)
?>
default.ctp
...headers, script loads and stuff...
<?php echo $this->element('translate');?> // loads translations ctp
<?php echo $this->fetch('script'); ?>
main.js
$(document).ready(function() {
// window.app doesn't exists so the following instruction will trigger an error:
var translatedNoData = window.app.translations['NO_DATA'];
}
Thank you very much guys, I hope the info above is enough.

I'm updating this post in order to solve the 'issue' posted above.
The code above is OK. $this->Js->set.. and $this->Js->writeBuffer are the correct way to set a variable from .CTP directly into the .JS as a global variable (it's gonna be set inside window.app)
Problem was caused by data inserted by the user. He putted some ' without closing it in a certain column from DB table which content was rendered directly into an HTML DOM element, so it crushed everything coming next...
Sry for the missunderstanding :)

Related

Odd Javascript behavior - porting to WordPress

I'm currently making my first effort into porting a webpage to Wordpress, so forgive my inexperience on the subject.
In my page, I have the following code:
function workLoad() {
$.ajaxSetup({ cache: false });
$('.thumb-unit').click(function() {
var $this = $(this),
newTitle = $this.find('strong').text(),
newFolder = $this.data('folder'),
spinner = 'Loading...',
newHTML = 'work/'+ newFolder +'.html';
$('.project-load').html(spinner).load(newHTML);
$('.project-title').text(newTitle);
});
}
In the past, this has worked fine hosted both locally and on Github. However, running my wordpress build locally through MAMP gives me the following error:
jquery-2.1.1.min.js:4 GET http://localhost/work/proj-1.html?_=1485348127113 404 (Not Found)
The URL should be fine, except for the part where it adds the ?_=(number). I'm not familiar with this behavior or what causes it. I tried changing work/ to /work/, since the dir is in the root folder, but that didn't solve it. I also have tried changing the variable to
newHTML = '< ?php bloginfo('template_directory')' + '/work/'+ newFolder +'.html';without the space after the opening bracket but to no avail. I also tried putting that bit in its own var, but it keeps adding ?_=1485348127113 to the URL of the html file I want to load, resulting in a 404 error.
What causes this? Thanks in advance for any advice you could share.
This timestamp is added for You to obtain the latest version of the file using ajax load.
If You want to disable this behaviour, You should set
$.ajaxSetup({
cache: true
});
This will enable caching and Your request would not contain the ?_=1485348127113 part anymore. This parameter should not cause the 404 not found error. Please check your path.

SCRIPT5 : Access is denied on IE-10 after Security Update : jquery-1.4.4.min.js

There was an IE-10 security update on Sept-10. After that, in my application there seems to be an issue accessing a standard div using jquery.
Here is the quick scenario :
I have a jsp layout template where there is a div defined :
<div id="abc"></div>
In that I include a js file k1.js, the following function in that is triggered upon a click of a button
function sample() {
jQuery.get("/fetchmedata.do?a=true", function(data) {
jQuery("#abc").html(data);
});
This was totally functioning across all browsers including ie-10 till Sept -10. After 10th, it still works fine on IE-9 and old IE-10 builds, but on new IE-10 build throws the error in console :
SCRIPT5 : Access is denied
The call stack pointed to internals of Jquery code which I couldn't decipher/understand the context.
The quick fix was to replace the jquery with Javascript, and it worked :
function sample() {
jQuery.get("/fetchmedata.do?a=true", function(data) {
document.getElementById('abc').innerHTML = data;
});
The jquery version was jquery-1.4.4.min.js.
Please advice on what could have been the issue, is it again probably related to not using XDomainRequest instead of XHR, so that we could take precautions in the code to avoid future issues.
Also what is the best practices around it ?
Please advice.

Cannot find source of javascript function call

Ok, so I need to find the source code of a particular javascript function on a website. (The specifics do not really matter unless there is no way to do what it is that I am asking)
I can see the function call in a link of html code
onclick="inbox.sendMessage();"
I know that the function does work because if I use a plugin a can call the function on that page, however, I have searched every .js file is referenced in that page, and none of them contain a function called sendMessage.
What I am asking is, is there a way to follow the code back to the source, perhaps if there was a way to debug the html and break when the onclick is triggered and then step into the function to see its source, but I do not know how I can do that or if it is even possible. Any help will be greatly appreciated, Thanks.
I guess you could do :
inbox.sendMessage
In the webconsole. (the function name without the parenthesis)
It will print out the source code of the function.
I usually use Opera, and in that at least this is what I do:
Open Opera Dragonfly (Ctrl + Shift + I).
Click on the HTML tag with the onclick handler.
Go to the listeners tab in the right hand side column.
See the listener for the click event. It shows you the file and line number.
sendMessage could be declared as:
var inbox{
sendMesssage:function(){
}
}
//or
function inbox(){
this.sendMessage=function(){
}
}
// or
inbox.sendMessage=function(){}
// or ...
So looking for "sendMessage(" or "function sendMessage" will not find you anything.
In chrome, Internet Explorer and Firefox (with firebug) you can hit F12 and go to debug, there you can check the scripts that have been loaded as there might have been scripts loaded dynamically.
#!/usr/bin/env ruby
Dir::glob("*").each do |name|
lineCount = 1
File.open(name, "r").each do |line|
puts "\nFile name: " + name + "\nline: " + lineCount.to_s if line =~ /inbox.sendMessage/ && name != "findfunction.rb"
lineCount += 1
end
end
Wrote a quick ruby script to help you out. To execute, first make sure you have a ruby interpreter on your machine then place the script in the directory with all your relevant files. load up a command line terminal, navigate to said directory and type "ruby findfunction.rb".
It will tell you all instances (files + line number) of "inbox.sendMessage".

Why is alert in microAjax not outputting text echoed from php file?

I am trying to get a string from a text file. I have a php file called genjsonGPS.php that looks like this:
<?php
$myFile = "vesselGPS.txt";
$fh = fopen($myFile, 'r');
$vesselGPS = fread($fh, filesize($myFile));
fclose($fh);
echo("Hello");
?>
When I run it, I get for an output in my browser:
"Hello"
I have a webpage with a js file using microAjax (from the js file):
microAjax("genjsonGPS.php", function (res) {
alert (res);
});
When I run the webpage I get a blank alert. When I change the function above to:
microAjax("genjsonGPS.php", function (res) {
alert (res.toString);
});
I get an alert that says:
function toString() { [native code] }
How do I get the function above to output "Hello" in the alert like the browser does?
Please follow these tips.
Monitor your HTTP server's access log, something like tail -f /var/log/apache/access.log is helpful. (Assume you are working on *nix platform)
If you are using Chrome, please check out the network monitor panel.
You'd better make sure that:
Your php page is truly accessed.
There is no error occurs, both in server and client sides.
If you still cannot figure out where things goes wrong, if would be useful to let people know how microAjax is implemented.
What happens if you put the URL like "/genjsonGPS.php"?

After upgrading to jQuery 1.6.2, globalEval throws an error when trying to execute javascript on page

I upgraded from jQuery 1.4.2 to 1.6.2 and now I get error(in IE). I have JavaScript on the page that gets executed by jQuery globalEval() function
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
In IE the call throws exception:
"Error: Could not complete the operation due to error 80020101."
The data parameter that get executed is javascript variables on page surrounded by <!-- -->
<!--
var id = \"ctrl90900\";
var url = \"myur.com/blah.html\";
-->
I'm using IE9, and jQuery 1.6.2 Not sure why this would cause an error.
If there is any error at all in a script passed to execScript, as far is Internet Explorer is concerned, it will report a 80020101 instead of the original error.
So, also check for missing semicolons and JS features not supported by IE.
For short code passages, i found the most effective debugging technique was to comment out parts of code and see if the error still turns up. If it doesn't, examine the code block that was just commented out for above errors.
It might be the commenting of the code, which is invalid JavaScript and unnecessary in this day and age.
You can strip it out with this regex...
$.globalEval(str.replace(/<!--\s*([\s\S]*?)\s*-->/, '$1'));
jsFiddle.
Just wanted to add a bit to this -- I was getting an error 80020101 whenever in an AJAX-called PHP script that included JavaScript. The script inside the PHP file was also breaking somehow, and refusing to render any of the script in the designated div (other elements of the PHP came through, but nothing inside the JavaScript -- I was trying to draw a chart using HighChart).
Turns out there was an undefined PHP function inside the JavaScript in the included PHP file (used to echo some text). I found this using Firebug.
So bottom line, make sure you don't have any undefined functions inside code coming back via AJAX.

Categories

Resources