I have a PHP function that queries a MySQL database and outputs an html table. This works fine with following PHP code:
<?php
showTable();
?>
But if I use the javascript code:
form.onsubmit = function() {
document.getElementById("php_code").innerHTML="<?PHP showTable(); ?>";
};
the browser does not show the table. There seems to be a problem with the (innerHTML) html string. I noticed for example that a carriage return inside a MySQL parameter causes problem with the innerHTML, but not with the PHP-only code.
Is there a way to fix this?
(the reason I wish to use the javascript bit is to be able to have a form with two buttons with different PHP functions depending on the form buttons clicked).
Php runs on the server, it generates the html page, and returns it to the browser for rendering. Javascript runs in the browser -- which happens after the php has finished running. It is not possible to invoke a php function directly from within a javascript function.
In order to do what you're trying to do, you'll need to move your php code into its own PHP file, and use something like jQuery's load() function to invoke your php via a separate http request. Something like this:
form.onsubmit = function() {
jQuery("#php_code").load('show_table.php');
};
where "show_table.php" contained something like this:
<?php
/** remember to include the function showTable()
* here, so you can call it below.
*/
function showTable() {
/* your function source here */
}
showTable();
Hope this helps. You might also want to do some research on web applications in general -- specifically, read up on the roles that are played by PHP and Javascript respectively.
edit
If you understand the distinction I've outlined above, and your actual intention really is to have the php function run when the page is initially loaded, rather than waiting till the javascript function is called, then you can modify your code as follows:
form.onsubmit = function() {
document.getElementById("php_code").innerHTML="<?PHP echo(addcslashes(showTable(), "\0..\37\\'\"/\177..\377")); ?>";
};
In order to use this approach, you will also need to make your function showTable() return the string rather than printing it out directly. One way to accomplish this is with php's output buffering functions. Just take your existing showTable() function, and wrap it like this:
function showTable() {
ob_start();
/* existing showTable logic goes here */
return ob_get_clean();
}
You need to escape the output of showTable() properly if you want to do it in a variable like that.
However, I propose a different method for you. Include the HTML like this:
<script type="text/html" id="showTable">
<?php showTable(); ?>
</script>
<script type="text/javascript">
form.onsubmit = function() {
document.getElementById("php_code").innerHTML= document.getElementById('showTable').innerHTML;
};
</script>
Notice the use of type="text/html" in the previous script tag. This will cause the table not to be shown to the browser, but retrievable by javascript.
Good luck.
Two things:
Be sure that no characters come out of showTable() that would interfere with the JavaScript code (like quotes)
Convert new lines to break characters (nl2br()) in your showTable() function.
Related
I actually work on a tool named jedox. With this tool I can make macro(like excel) but in PHP. Jedox provide some example of macro and in one of these example there is this code:
function test()
{
return array(array('eval', "(function(){
console.log('salut')
}())"));
}
It's a PHP code that run JS code. But the problem is I don't know how this code work, the only thing I know about it is that it execute JS code but can't return anything, so if you put return in the code it will not return any value. I have no way to retrieve the value returned.
So my question is how should I supposed to retrieve a value from this ?
PS: if I try to investigate about the value returned by test() I get an array nested with another array with those 2 values 'eval' and the function.
PS2: Apparently you can't run this code correctly with traditional tool. So to help me you should have jedox, I guess :/ ...
On the client side, someone must be getting those two strings and executing them. The PHP code ("host side") is not actually doing that.
You may could put the Javascript code into a file. Then execute the file using NodeJS and get the value.
For example:
function test() {
file_put_contents('test.js', <<< TEXT
(function(){
console.log('salut')
}())
TEXT);
return shell_exec('node test.js');
}
echo test(); // Return: sault
Also notice that in most shared hosts and servers shell_exec function is disabled by default. You can enable it through you php.ini.
I would like to add a function call including parameters to a HTML button via javascript. I know there are plenty of questions to this subject but none of the answers i found did work for me.
Note: My HTML and JS are in separate files which are correctly linked (the JS code works)
Problem:
I can add the function call like this:
var $add = $("#add");
$add.click(myFunction);
However $add.click(myFunction(i)); does not work.(Did also try with specific integer)
I have also tried it the following way:
document.getElementById('add').onclick = function() {myFunction(i);};
But like that the function does not even get applied to the button.
My function is defined in the JS file like this:
function myFunction(length) {
//do stuff with length I would notice
}
You can use some thing like function bind or do it using handler:
$add.click(function(e){
myFunction(i);
});
I am currently trying to convert a lot of backend code to front end (to lighten the load on a small system).
The code at the moment calls a PHP function to return specific information. (e.g. image locations, strings, styling)
I am converting this code to its js equivalent, the content from Mysql was converted to JSON and stored in a read only file and I am accessing that file using this code:
<script>
function jsread(tag) {
$.getJSON("/strings.json", function(result){
document.write(result[tag]['value']);
});
}
</script>
I want the function to "print" where ever it is invoked. document write writes the value to the page but stops all other loading and write only the value.
Let me be very clear on this: I DO NOT want to use anything that needs extra calls or references out side of this function, that will take months of work so no getting elements by their IDs I have already view many questions on this subject and none are what I can work with. I need something that can be applied to every situation. Other wise I will just have to read the JSON using PHP as a middle compromise.
The problem here is, document.write()'s behaviour is crazy across all the browsers, because, it directly modifies the document object and messes up with the events attached. So it is always better to avoid this function as each browser defines it differently and has a different effect on the same code, with different browsers.
Is there a way to use them without a direct reference?
Solution
The wise thing is, as I said in the comments, it is better to use one of the jQuery functions safely, which create a textNode and insert it the right way, without affecting the others:
<script>
function jsread(tag) {
$.getJSON("/strings.json", function(result){
$("body").append(result[tag]['value']);
});
}
</script>
In case, if you wanna do something like having a placeholder and doing stuff, then you can try giving something like this:
$(function () {
var data = "Dummy Data, that would probably get returned from the getJSON";
// Inside the Success function, do this:
$("span.placeholder-of-the-json").replaceWith(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="placeholder-of-the-json">This gets replaced</span>
AIM: I would like to set the below function to call every 5 seconds. Using qtip.
The variable ALARM_POPUP changes every minute via a shellscript which replaces the contents on the variable.
CODE:
function popupTXT()
{
var ALARM_POPUP="Alarm Warning warning ";
$('#telecom_1').qtip({content:ALARM_POPUP,style: {name: 'dark', tip: 'topLeft'} });
};
I am using the below to call on a timer.
setInterval("popupTXT()",5000);
OUTCOME: This will only work when I refresh the browser. Any suggestions would be appreciated
The variable ALARM_POPUP changes every minute via a shellscript which replaces the contents on the variable.
That means that in order to see that change on the page, you have to call the server to get an updated value. You're not doing that.
You could do that via ajax. Create a server-side page that outputs the new value for ALARM_POPUP as raw text (using Content-Type: text/plain) or as JSON (using Content-Type: application/json), and trigger an ajax call to get the contents of that page, then update the qtip with it. You wouldn't want setInterval for that because with the indeterminate length of time the ajax call would take, things would very quickly become chaotic. Instead, just initiate a setTimeout upon completion of the previous cycle.
Assuming you create an updatealarm.xyz page (PHP, JSP, ASP.Net, whatever) that outputs the current ALARM_POPUP value as plain text, that would look something like this:
(function()
{
var ALARM_POPUP="Alarm Warning warning ";
function updateQtip(popupText)
{
$('#telecom_1').qtip({content:popupText,style: {name: 'dark', tip: 'topLeft'} });
setTimeout(nextUpdate, 5000);
}
function nextUpdate()
{
$.ajax({
url: "updatealarm.xyz",
success: function(data)
{
ALARM_POPUP = data; // Although you don't actually need to update it
updateQtip(data);
},
error: function()
{
// Do error handling
}
});
}
updateQtip();
})();
About your original setInterval call: It's best not to pass strings into setInterval or setTimeout; that's basically doing an eval, and it's neither necessary nor a good idea. Instead, pass in a function reference (e.g., the function's name, without () calling it), as above.
Re your comment below:
I am having problems with this and I was wondering if you provide an example of what the php file would look like
I've only done a little PHP, but I believe it would look like this:
<?php
header('Content-Type: text/plain');
echo 'This is the message that will end up in \'data\' in the ajax success handler.';
?>
Or if you prefer to use a variable to make it easier for your sed script:
<?php
header('Content-Type: text/plain');
$alarm_popup = 'This is the message that will end up in \'data\' in the ajax success handler.';
echo $alarm_popup;
?>
Try this:
setInterval(popupTXT,5000);
Just a sample
Read more about .setInterval()
Here is my question, I am using jsp script, trying to match a key word in requesting url and do something:
<script>
$url = '${pageContext.request.requestURL}';
if("${fn:contains(url, 'key')}" == true){
...
}
....
But this doest work... I am not sure where the problem is but I want it to be like when url contains this string, go in to the if condition.
Thank you
You are mixing JSP/EL and JavaScript as if they run in sync. This is wrong. JSP/EL runs in webserver and produces HTML code which get executed in webbrowser. JavaScript (JS) is part of the generated HTML code and runs in webbrowser only.
You need to do it either fully in JSP/EL, or fully in JavaScript. You can use JSP/EL to dynamically generate JS code which get later executed when the page arrives at browser. Rightclick page in browser, do View Source to see what JSP/EL has generated. You should not see any line of JSP/EL. You should only see HTML/JS code. It's exactly that JS code which get executed then.
You're using a JSP EL function to test a JS variable which isn't in the variable scope at that moment at all. This is not going to work. It can only test JSP/EL variables.
Here's how you could do it in pure JS:
<script>
var url = window.location.href;
if (url.indexOf('key') > -1) {
// ...
}
</script>
If you really insist in doing it using JSP/EL, you could do as follows:
<script>
var url = '${pageContext.request.requestURI}';
if (${fn:contains(pageContext.request.requestURI, 'key')}) {
// ...
}
</script>
This will then generate the following JS code (rightclick page in browser and View Source to see it):
<script>
var url = '/some/uri';
if (true) {
// ...
}
</script>
But this makes no sense. Whatever functional requirement you need to solve, you need to think twice about the right approach. Feel free to ask a new question about solving the concrete functional requirement the proper way.
If you want a parameter that the page was requested with, use ${param.paramName}. So in this case ${param.key}. See implicit objects in the docs. And if you just want to check it has a value try ${not empty param.key}.