javascript call function from php file! (using yii) - php

I'm trying to call a function in a .js file from the php page where I'm displaying it!
What I want to do is something like this:
.php file:
...
function testFunc(){
return "2";
}
...
now I want to call this function inside the .js file!
Thaks in advance for your help

What you have tried?
Assuming the testFunc function is enclosed in proper script tags,
your .js file can call it quite simply like this:
testFunc()
Ideally, you include the .js file after testFunc is declared.

PHP runs server side. JavaScript (assuming you are using it in a browser) runs client side. If you want to execute this PHP function from the client side and get the result without reloading the page, you have to do an ajax request, which may be beyond your skills.
Look into jQuery Ajax:
http://api.jquery.com/jQuery.ajax/

Related

AJAX Load function from php

;-) I have a hit a brick wall. Today I have met Ajax for the first time in my life. And I understand, that my question can seem very stupid. But I need your help.
I have a php file (for ex. index.php), it has an include (function.php). In the file function.php I have a function (for example function Jokes(){....}).
I want to use AJAX to load this function in my page. But I don't know how to do this... :-(
I have found some easy solutions (I use Jquery load function), but it's not what I want, because I have to use a separate file.
$('#jokes').load('jokes.php');
But I need something like:
$('#jokes').load('function.php','jokes()');
Any help or ideas? It will be appreciated.
P.S: Sorry for my bad English...))
What you can do is make one AJAX file, e.g. ajaxfunctions.php where you divide the functions.
$('#jokes').load("ajax.php", { 'function': 'jokes' } );
In your PHP file ajax.php you can do this:
<?php
include 'function.php';
if (isset ($_POST['function']) && $_POST['function'] == 'jokes')
{
echo jokes ();
}
?>
Does this help you?
The browser (and thus Ajax) can only make HTTP requests to the server.
It cannot execute specific functions.
You would have to write server side code that would recognise a particular URL (e.g. to a script that only calls that function, or a script that decides which function to run based on the query string) and execute a particular function in response to a request to it.
No, it's impossible to do it this way. You must make a request to a url. You can't just invoke a specific function from a php file.
Build a url wrapper for the function you need.
Don't do that.
Ajax is used to send or retrieve data, but what you are trying to do is to load a Javascript function defined in a PHP file (isn't it?).
Instead, just define your Javascript function in a JS file and load it via a script (or, if it should be loaded dynamically, you may use an AMD loader like require.js)
If you want to load a PHP function in JS, then it's not possible. You may call that function and fetch its result instead, though.
It doesn't work like this.
$('#jokes').load('jokes.php');
does an http request to jokes.php. If you want to execute a specific function, you can use a parameter, like this:
$('#jokes').load('jokes.php?func=jokes');
From your php script, get 'func' and execute the proper function.
...
function jokes() {
return 'some output';
}
...
$func='';
if (!empty($_REQUEST['func'])) {
$func=$_REQUEST['func'];
}
if ($func=='jokes') {
echo jokes();
}
You don't need AJAX for this. You want to put the Jokes() function in a JavaScript file, maybe called Jokes.js, include it in index.php and then call it normally in a JavaScript block in index.php.

Is it possible to include a php file in js script and access the function of that php file?

I have js file where i need to call the function defined in the php file to calculate the value and then move on to next step. Is this possible to do? I am not able to access the function of the php file from my script. Also is there some way around to include php file in a html page without changing the extention .html
No, you cannot do that. PHP and Javascript do not execute in the same environment, nor at the same time.
PHP executes on YOUR web server (server-side) before the page is served up.
Javascript is executed on the CLIENT's browser after the page has been served up.
To call a PHP function from javascript, you will need to make an AJAX call. This sends a value from the client side to the server side where it can be processed, and the response is then sent back to the client.
Try JQuery Ajax
It´s easy to use.
$.ajax({
type: "POST",
url: "yourphpfile.php",
data: { values: "100"}
}).done(function( msg ) {
console.log("php file called"+msg);
});
replace yourphpfile.php with your php file and your php file gets executed
If you want to access server-side resources (filesystem writing, database), you'd need to use AJAX to switch back and forth.
If you're just more familiair with PHP, you could take a look at http://phpjs.org/, which reimplements many PHP functions in Javascript.
PHP files are files that are executed by the server.
"I have js file where i need to call the function defined in the php file to calculate the value." Browsers cannot run php functions, you need server to do that.
"Also is there some way around to include php file in a html page without changing the extention .html" If you do that your php code will not run, because server use the extensions to know if a file needs execution or not.
To call a PHP function from javascript, you will need AJAX. The value is send from the client to the server where it is processed, and the response is then sent back to the client.

Ajax call does not execute PHP function

I have written a very basic PHP pagination class and I'm trying to load the content with jQuery Ajax $.post requests. My class has two functions, one displays the content and the other one the pagination. If I don't use jQuery, but only PHP, everything works fine. Once I try to use jQuery, my displayContent() function never gets called, but the createNav() one does its job just fine(I mean the page numbers are loaded).
Here is my js.
http://goo.gl/BUZH1
And here is my PHP:
if($action=='displayArticles') displayArticles();
function displayArticles()
{
$content=new createPages(5,10);
$content->displayContent();
$content->createNav();
}
And here is the PHP class I just created. It was too large to add it in here, but I saved the code in text format.
http://goo.gl/Lv9Wl
Try dumping $_POST['action'], then check the output in the $.post response. It's pretty obvious that your if statement is resolving to false. :)
You can also try dumping $action, then checking that in the response. Good luck!
You can not call PHP functions after the page has been loaded. PHP is server side script, so you need AJAX to load a separate page, where your displayArticles function will be defined.

Include PHP inside JavaScript (.js) files

I have a JavaScript file (extension .js, not .html) containing several JavaScript functions.
I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.
Is that possible?
Would I need to "include" the .php file containing the PHP function in the .js file?
How would I do that? For example, say I had a file called myLib.php containing a function called myFunc that takes two parameters (param1 and param2). Then I have a .js file containing a function called myJsFunc. How would a call the myFunc (PHP) from within the myJsFunc (JavaScript function)? Wouldn't I need to include the PHP file somehow in the .js file?
7 years later update: This is terrible advice. Please don't do this.
If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.
<script type="text/javascript">
var phpVars = <?php echo json_encode($vars) ?>;
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>
If you're trying to call functions, then you can do this like this
<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
// assume each element of $arrayWithVars has already been json_encoded
functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
functionTwo(<?php echo json_encode($moreVars) ?>, <?php echo json_encode($evenMoreVars) ?>);
</script>
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
Add the above code in .htaccess file and run php inside js files
DANGER: This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).
If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically "application/javascript"
PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.
A slightly modified version based on Blorgbeard one, for easily referenceable associative php arrays to javascript object literals:
PHP File (*.php)
First define an array with the values to be used into javascript files:
<?php
$phpToJsVars = [
'value1' => 'foo1',
'value2' => 'foo2'
];
?>
Now write the php array values into a javascript object literal:
<script type="text/javascript">
var phpVars = {
<?php
foreach ($phpToJsVars as $key => $value) {
echo ' ' . $key . ': ' . '"' . $value . '",' . "\n";
}
?>
};
</script>
Javascript file (*.js)
Now we can access the javscript object literal from any other .js file with the notation:
phpVars["value1"]
phpVars["value2"]
This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.
I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.
Actually the best way to accomplish this is to write the javascript in a .php and use jquery in a separate file to use the Jquery get script file or jquery load use php include function in the doc where the javascript will live. Essentially this is how it will look.
Dynamic Javascript File in a .php file extension - Contains a mixture of php variables pre processed by the server and the javascript that needs these variables in scripts.
Static Js File - Using http://api.jquery.com/jquery.getscript/ or http://api.jquery.com/load/
In the main html page call the static file as a regular js file. Calling the static js file will force load the dynamic data from the server.
some file.php 1:
<?php
$somevar = "Some Dynamic Data";
?>
$('input').val(<?php echo $somevar?>);
or simply echo the script such as
echo "$('input').val(".$somevar.");";
File 2:somejsfile.js:
$("#result").load( "file.php" );
File 3 myhtml.html:
<script src="somejsfile.js"></script>
I believe this answer the question for many people looking to mix php and javascript. It would be nice to have that data process in the background then have the user have delays waiting for data. You could also bypass the second file and simply use php's include on the main html page, you would just have your javascript exposed on the main page. For performance that is up to you and how you want to handle all of that.
Instead of messing with generic php-handlers do a 1-file exception using a rewrite:
Rename the .js-file to .php and rewrite the request to make it responde to a .js request. If the file is served by apache; add in .htaccess:
RewriteEngine on
RewriteRule myjsfile\.js myjsfile.php [L]
Secondly make the .php-file pretend to be a js-file. Inside the php-file start the file with:
<?php header('Content-Type: application/javascript'); ?>
Et voilà, you can now use php-tags in your ".js"-file.
You can't include server side PHP in your client side javascript, you will have to port it over to javascript. If you wish, you can use php.js, which ports all PHP functions over to javascript. You can also create a new php file that returns the results of calling your PHP function, and then call that file using AJAX to get the results.
Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX - in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!
You can make a double resolution of file:
"filename.php.js" in this way.
PHP generates JS in this file.
I got all parameters from DB.
This worked for me on xampp.
There is not any safe way to include php file into js.
One thing you can do as define your php file data as javascript global variable in php file. for example i have three variable which i want to use as js.
abc.php
<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>
After use it directly in your js file wherever you want to use.
abc.js
function test(){
alert('Print php variable : '+ abc +', '+number);
}
function printArrVar(){
alert('print php array variable : '+ JSON.stringify(mydata));
}
Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.
this is the standard way you can call php script data into js file without including js into php code or php script into js.

problem executing php file with javascript

i have been learning about javascript and using dojo. I am trying to execute a php file with dojo. My code is
dojo.xhrGet({
url: 'helloworld.php',
load: testCallback,
error: testError,
content: {name: dojo.byId('name').value}
});
for the dojo function. The php file is basically a simple script that prints the value of whats being passed in through xhrGet
<?php
header('Content-type: text/plain');
print "Hello {$_GET['name']}\n";
?>
When I call this function, I get the php file displayed as text. My testCallback function is simply
function testCallback(data, ioArgs)
{
alert("in testCallback");
alert(data);
}
I cant think why this wont work as it was pulled from the dojo tutorial itself. I tested php with a file with phpinfo() in it, and it was working. Does php have to be configured to 'work' with certain ports?
If you get your php file back as text your webserver is not setup to call php to handle the file. It is as simple as that.
Have you named it .php or something else (judging from the post it looks like it is called helloworld.php and in that case I wonder how your phpinfo() call could work, was it the same server?)

Categories