EDIT My question was misleading in that it sounded like I wanted to read/write to the client machine when what I meant was that i want to read a script, not load it, from the source computer. I just assumed since you can summon (load) a script like so
<script LANGUAGE="javascript" SRC="source.js"></script>
Then there must be some way to read source.js before, during or after loading it. I ask because I am still trying to find an answer to my previous question here. I am trying to find some way to make an object/function/class aware of the code that gave rise to it, with comments and tabs and all.
you could load it via ajax and access it as a string
$.ajax({
type: "GET",
dataType: "text",
url: "jsLoader.php",
success: function(data){
alert("Length: " + data.length.toString());
eval(data);
}
});
Or:
$.ajax({
type: "GET",
dataType: "text",
url: "source.js",
success: function(data){
alert("Length: " + data.length.toString());
$("head").append('<script type="text/javascript">' + data + '</script>');
}
});
your question is kind of confusing, but it sounds like you want a way of accessing an object's code. To be honest I don't know how far you can get with this approach, and it won't include comments, but you can always just use toString().
e.g.
function myFunc() {
var somestuff = "my function's code";
};
function myClass() {
var that = this;
this.classFunc = function() {
var somethingelse = "my class function's code";
}
}
alert(myFunc.toString() + '\n\n' + myClass.toString());
Maybe I'm a little confused by your question, but first things first:
<script LANGUAGE="javascript" SRC="source.js"></script>
Does NOT read from client's machine, it reads from the web context that the page was loaded from. If the html page you're loading is www.google.com for example, then src="source.js" will load www.google.com/source.js
If I understand your question correctly though, I think the answer to your questions is that source.js does NOT get read asynchronously in the loading of the web page. Let's say source.js contains only this line.
var variable = {};
In index.html, you have this:
<script type="text/javascript">
alert(typeof(variable));
</script>
<script type="text/javascript" src="source.js"></script>
<script type="text/javascript">
alert(typeof(variable));
</script>
Then, the first alert is going to give you "undefined", and the second alert will give you "object". So, if you want to test if source.js is loaded or not, you can simply do a quick conditional:
if (typeof(variable) != "undefined") { doSomething(); }
One way to get around this would be to setup a php script which fetches the code serverside, wraps it in a function/object, and while doing so assigns the code as a string variable, somewhat like so
/*Get js script at $filename*/
$script = fread($handle, filesize($fileName));
/*Add the code as a string*/
$codeAsString = file_get_contents($fileName);
$script .= '_code=' . json_encode($codeAsString) . ';';
But this doesn't solve the bigger problem of not being able to debug the code. The reason for this is that I am using eval rather than including the scripts. The former executes the code, whereas the latter updates the DOM then executes the code. Only the latter will provide useful debugging info (see here).
Related
i'm trying to change a js file location when a visitor shows the source-code
, depending on that :
javascript functions don't work when the visitor shows the source-code
.
my idea is creating a file , put a javascript code to delete the file , in this situation the file won't be deleted if someone showed the source-code :
$check="$ip-$views-$id";
fopen("$check.txt","w"); //CREATING A FILE
// DELETING THE FILE ABOVE BY JAVASCRIPT , IT WON'T BE DELETED IF SOMEONE ENTERED VIA THE SOURCE-CODE MODE
?>
<div id="countno"></div>
<script type="text/javascript">
$('#countno').load('del.php?name=<?echo $check;?>&location=' + ' #countno');
</script>
<?
if (file_exists("$check.txt")) { //IF SOMEONE SHOWED THE SOURCE CODE
$new_location="fake_location.js";
}
else{
$new_location=$old_location;
}
?>
<script src="<?echo $new_location;?>"></script>
the problem now , is that the file_exists php function shows that the file still exists even though it was already deleted by the javascript code .
the file_exists function was executed before the javascript code !
any help / solution to make that php function check the file after that javascript code ? i know it's kinda impossible but it worth it !
What you are describing is not possible. php is a server side language while javascript is a client side language. Thus, the PHP on your page will always execute before the Javascript on your page executes. There is no way to make your Javascript execute first when you have it this way.
Instead, what you could do is to separate the PHP and Javascript. Have your file_exists check in another page. e.g. check.php.
if (file_exists("$check.txt")) {
echo "fake_location.js";
} else {
echo $old_location;
}
Then use an ajax call to make a request to check.php, and load your other script depending on what check.php outputs.
<script>
$.ajax({
method: "GET",
url: "check.php"
})
.done(function(script) {
$("#check").attr("src", script);
});
</script>
<script id="check"></script>
However, if your goal is to prevent people from figuring out where your javascript is located, it is not possible. Most browsers nowadays can inspect the HTML as it changes. They can see the loaded script without having to load the source separately.
I'm trying to get JSON array from my php-script. Following is my Jquery code written in my jsp file-
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://example.com/root_dir/test_json.php', function(data)
{
alert(data);
});
});
but, above code showing only outer alert (i.e. alert("Inside Ready");) and not showing inner alert (i.e. alert(data); ). I'm getting expected json when I hit URL in browser. So definitly there is no problem in URL and php-script.
following is test_json.php
<?php
//Create an array
$json_response = array();
$row_array['label'] = 'A';
$row_array['value'] = $row['0 to 2'];
$row_array['color'] = '#FA2020';
array_push($json_response,$row_array);
$row_array['label'] = 'B';
$row_array['value'] = $row['2 to 3'];
$row_array['color'] = '#2BD95A';
array_push($json_response,$row_array);
$row_array['label'] = 'C';
$row_array['value'] = $row['above 3'];
$row_array['color'] = '#F7F739';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
Getting following json when I hit URL in browser-
[{"label":"A","value":"19","color":"#FA2020"},{"label":"B","value":"1","color":"#2BD95A"},{"label":"C","value":"2","color":"#F7F739"}]
I'm using jquery-1.10.2.js. Thank You..!
Try This one...Hope so it is useful to you
$(document).ready(function()
{
$.ajax({
type:'POST',
url:'http://example.com/root_dir/test_json.php',
dataType:'JSON',
data:{
},
success:function(data1){
alert(data)
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
});
Your code seems to be working fine -
I just created a test page with your code and it works -
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://<<CHANGE SERVER NAME>>/zz-test/get_json.php', function(data)
{
alert(data);
});
});
</script>
</head>
<body>
</body>
</html>
Your jQuery and PHP code looks fine so, in my experience, it is usually an error caused by calling your PHP script from a different domain (i.e.: file:///). If you can access your browser's console, you should be able to see if this is in fact the error causing the data not to be displayed.
One solution for this is to add at the top of your PHP code:header('Access-Control-Allow-Origin: *');. There are however some security concerns with this, so it should not be used permanently.
Alternatively, you could upload all your HTML, CSS, JS, jQuery, etc. code to the web server hosting the PHP file, which is a far better option.
Finally, if the option above is not possible you could use JSON-P (although this does not work with POST requests), there is a question about this at Simple jQuery, PHP and JSONP example?
It is possible this question might be a little vague for the liking of many people here, but my knowledge of the topic is vague also, and despite some searching I have not been able to find anywhere online with clear instructions on how to do this although (in my view) it should probably be one of the simpler cross-domain JSONP operations.
I will explain what I am trying to do. I am trying to retrieve the contents of a HTML file on an external server using both JSONP and a PHP script. I have access to the server - my PHP script is as follows:
<?php
$callback = '';
if (isset($_GET['callback']))
{
$callback = filter_var($_GET['callback'], FILTER_SANITIZE_STRING);
}
$html = include($callback);
echo $callback . '('.json_encode($html).');';
?>
Using this it seems that when I type www.myurl.com/myscript.php?callback=filename.html, the correct file is displayed (although, for some reason, the ?callback is duplicated in the address, and the filename is appended to the end of the output displayed...
I have tried a few different scripts for my HTML file but currently have the following...
function request_jsonp(){
var script = document.createElement('script');
var url = 'http://www.myurl.com/myscript.php?callback=filename.html';
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
Now obviously this doesn't work because the output of the PHP script isn't a working function of any sort, but I am not sure of the best way to go about making it one. I would like to somehow wrap the output in something like this:
function DisplayOutput() {
document.getElementById('output').innerHTML = ...external HTML goes here!... ;
}
...but currently I'm really not sure of the best way to do this.
Any help would be very much appreciated.
callback needs to be the name of the callback function. You should generate a unique one each time the function is called.
You should use a second, different query string variable to determine what URI to fetch.
var jsonp_counter = 0;
function request_jsonp(url, callback){
jsonp_counter++;
var callback_name = "jsonp_function_" + jsonp_counter;
window[callback_name] = callback;
var jsonp_url = 'http://www.myurl.com/myscript.php" +
"?callback=" + encodeURIComponent(callback_name) +
"&url=" + encodeURIComponent(url);
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
request_jsonp("filename.html", function (data) {
do_something_with(data);
});
I have some working JS code which I put on the sections of my create and edit views, and it's working fine.
However, when I attempted to move the code to a separate JS file, the code would no longer call the controller action.
Here the JS code:
<g:javascript>
$(document).ready(function(){
<g:remoteFunction controller="project" action="ajaxGetClient" onSuccess="updateClient(data)"/>
});
function updateClient(data){
var element = $("#project\\.client");
element.empty();
element.val(data.name);
}
</g:javascript>
Here's the controller action:
def ajaxGetClient = {
if(!params.id){
params.id = Project.find("FROM Project ORDER BY id").id
}
def projectInstance = Project.get(params.id)
render projectInstance?.client as JSON
}
And here's the GSP code:
<g:textField name="project.client" id="project.client" maxlength="9" required="" disabled=""/>
<g:select id="project" name="project.id" from="${myPackage.Project.list()}" optionKey="id" required="" value="${productInstance?.project?.id}" class="many-to-one"
onchange="${
remoteFunction(
controller: 'project',
action: 'ajaxGetClient',
onSuccess: 'updateClient(data)',
params: '\'id=\' + this.value'
)}"
/>
I added a resource to ApplicationResources.groovy and changed the above JS code to this:
<g:javascript library="updateclient"/>
I simply copy/pasted the code into a JS file and then got a message:
Uncaught SyntaxError: Unexpected token <
which I understood came from it not recognizing the GSP syntax, so I tried some AJAX, which I'm pretty unexperienced at:
$(document).ready(function(){
$.ajax({
type: 'POST',
url: "${remoteFunction(controller:'project', action:'ajaxGetClient', onSuccess:'updateClient(data)')}"
});
});
Here's what I'm getting from the browser console:
http://localhost:8080/MyApp/product/$%7BremoteFunction(controller:'project',%20action:'ajaxGetClient',%20onSuccess:'updateClient(data)')%7D 404 (Not Found)
Quite frankly, I'm at a loss right now. Any help would be appreciated.
The reason for this is that Javascript (.js) and other non GSP (.gsp) files aren't parsed through the Groovy server pages engine. Thus, tag libraries such as the or ${g.remoteFunction} aren't parsed.
There are several ways to accomplish this however.
One is to keep the code in your GSP and not externalize it into javascript files.
Second is to move your code into javascript files but have configuration values in your GSP file. Here is a very simple example of using the message taglib:
// inside the .js file
function myFunction() {
console.log("I would use this value: "+_VALUE_FROM_GSP);
}
<script type="text/javascript">
// inside the .gsp file
var _VALUE_FROM_GSP = "${message(code: 'just.an.example')";
</script>
Finally, there plugins (listed below) that allows you specify some resources (javascript files in your case) to be parsed through the Groovy Server Pages engine.
GSP-arse plugin and GSP Resources
I'll be answering my own question here, since the bulk of it came from valuable advice from a friend of mine, but Joshua's answer was also very important, so I ended up combining both of them.
This is how I solved it:
On the GSP:
<script type="text/javascript">
var _URL = '${resource(dir: "")}/project/ajaxGetClient';
</script>
<g:javascript library="updateclient"/>
The reason I'm using the <script> tag is because in order for the _URL variable to become usable across different files, it had to be declared before the file using it. At least that's what this other SO answer said:
Global variables in Javascript across multiple files
Separate JS file:
$(document).ready(function(){
getClientAjax(null);
});
function getClientAjax(id) {
$.ajax({
url: _URL,
type: "POST",
data: { id: id },
success: function(data) {
updateClient(data);
}
});
}
function updateClient(data){
var element = $("#project\\.client");
element.empty();
element.val(data.name);
}
And the controller action remained the same.
At the end, there had to be created another JS function, but I gotta say I'm happy with the result.
Thanks for all the help.
I am looking for an equivalent to jquery's load() method that will work offline. I know from jquery's documentation that it only works on a server. I have some files from which I need to call the html found inside a particular <div> in those files. I simply want to take the entire site and put it on a computer without an internet connection, and have that portion of the site (the load() portion) function just as if it was connected to the internet. Thanks.
Edit: BTW, it doesn't have to be js; it can be any language that will work.
Edit2:
My sample code (just in case there are syntax errors I am missing; this is for the files in the same directory):
function clickMe() {
var book = document.getElementById("book").value;
var chapter = document.getElementById("chapter").value;
var myFile = "'" + book + chapter + ".html'";
$('#text').load(myFile + '#source')
}
You can't achieve load() over the file protocol, no other ajax request is going to work for html files. I have tried even with the crossDomain and isLocale option on without anything success, even if precising the protocol.
The problem is that even if jQuery is trying the browser will stop the request for security issues (well most browsers as the snippet below works in FF) as it allows you to load locale file so you could get access to a lot of things.
The one thing you could load locally is javascript files, but that probably means changing a lot of the application/website architecture.
Only works in FF
$.ajax({
url: 'test.html',
type: 'GET',
dataType: 'text',
isLocale: true,
success: function(data) {
document.body.innerHTML = data;
}
});
What FF does well is that it detect that the file requesting local files is on the file protocol too when other don't. I am not sure if it has restriction over the type of files you can request.
You can still use the JQuery load function in this context:
You would could add an OfflineContent div on your page:
<div id="OfflineContent">
</div>
And then click a button which calls:
$('#OfflineContent').load('OfflinePage.html #contentToLoad');
Button code:
$("#btnLoadContent").click(function() {
$('#OfflineContent').load('OfflinePage.html #contentToLoad');
});
In the OfflinePage.html you could have to have another section called contentToLoad which would display on the initial page.