run php code in javascript

How to execute PHP code within JavaScript

When the button is pressed I want to execute PHP code (at this point to echo asadasda)

run php code in javascript. Смотреть фото run php code in javascript. Смотреть картинку run php code in javascript. Картинка про run php code in javascript. Фото run php code in javascript

10 Answers 10

You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it’s just echos, and the script is in a php file, you could do something like this:

don’t worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

and test.php would be:

it would write the contents of test.php to whatever element has the result class.

Interaction of Javascript and PHP

We all grew up knowing that Javascript ran on the Client Side (ie the browser) and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.

First, to clarify the DHTML usage I’ll cite this DHTML example:

Assuming we have an html file with the somewhere, then we can alter the display with a simple

Golly gee; we don’t need PHP to do that now do we! But that creates a structure for applying PHP provided content.

We change the webpage in question into a PHTML type to allow the server side PHP access to the content:

Now our javascripts can get to the PHP globals like this:

// by accessig the globals var textMsg = ‘ ‘;

In the javascript, replace

var textMsg = ‘Say good night Gracy’;

with: // using php returnContent()

To be resolved: calling updateContent() with a filename and using it via onClick() instead of onLoad()

Источник

How do I run PHP code when a user clicks on a link?

I want to have a page run some PHP code when a user clicks on a link, without redirecting them. Is this possible with

or with the javascript onclick event?

10 Answers 10

Yeah, you’d need to have a javascript function triggered by an onclick that does an AJAX load of a page and then returns false, that way they won’t be redirected in the browser. You could use the following in jQuery, if that’s acceptable for your project:

As others have suggested, use JavaScript to make an AJAX call.

I know this post is old but I just wanted to add my answer!

You said to log a user out WITHOUT directing. this method DOES redirect but it returns the user to the page they were on! here’s my implementation:

the code that gets the file name from the full url isn’t bug proof. for example if query strings are involved with un-escaped ‘/’ in them, it will fail.

However there are many scripts out there to get the filename from url!

You cant run PHP when a user clicks on a link without leaving the page unless you use AJAX. PHP is a serverside scripting language, meaning the second that the browser sees the page, there is no PHP in it.

Unlike Javascript, PHP is ran completely on the server, and browser wouldn’t know how to interpret it if it bit them on the rear. The only way to invoke PHP code is to make a Page request, by either refreshing the page, or using javascript to go fetch a page.

In an AJAX Solution, basically the page uses javascript to send a page request to another page on your domain. Javascript then gets whatever you decide to echo in the response, and it can parse it and do what it wants from there. When you are creating the response, you can also do any backend stuff like updating databases.

Источник

How to Call a PHP Function From JavaScript

PHP comes with a lot more built-in functions to work with strings, arrays and other types of data in comparison to JavaScript. Therefore, it is natural for a lot of people to feel the urge to call PHP functions from JavaScript. However, as you might have guessed or found out, this does not work as expected.

There can be a lot of other cases where you might want to run some PHP code inside JavaScript—for example, to save some data on your server. Simply placing the PHP code inside JavaScript will not work in this case either.

The reason you can’t simply call a PHP function from JavaScript has to do with the order in which these languages are run. PHP is a server-side language, and JavaScript is primarily a client-side language.

Whenever you want to visit a page, the browser sends a request to the server, which then processes the request and generates some output by running the PHP code. The output or generated webpage is then sent back to you. The browser usually expects the webpage to consist of HTML, CSS, and JavaScript. Any PHP that you might have placed or echoed inside JavaScript would either have run already or won’t run at all when the webpage loads in the browser.

All hope is not lost, though. In this tutorial, I’ll explain how you can call PHP functions from JavaScript and JavaScript functions from PHP.

Call a PHP Function From JavaScript

We can use AJAX to call a PHP function on data generated inside a browser. AJAX is used by a lot of websites to update parts of webpages without a full page reload. It can significantly improve the user experience when done properly.

Keep in mind that the PHP code will still run on the server itself. We will just provide it with data from within our script.

Using jQuery AJAX to Run PHP Code

If you are using jQuery on your website, it becomes incredibly easy to call any PHP file with code that you want to run.

The second parameter contains a bunch of different configuration options to specify the data you intend to process and what to do in case of success or failure, etc. The configuration options are passed in JSON format.

You can use the method parameter to specify the HTTP method which should be used for making the request. We will be setting it to POST because we will be sending data to the server as well.

Now, let’s see an example of a basic AJAX request where we will pass data to a PHP file and call the PHP function wordwrap() within that file. Here is our complete webpage:

Place the following code in a file called wrap.php in the same directory.

Remember that you have to echo the data that you want to send back to the browser. Your webpage will look like the image below if everything goes well.

run php code in javascript. Смотреть фото run php code in javascript. Смотреть картинку run php code in javascript. Картинка про run php code in javascript. Фото run php code in javascriptrun php code in javascript. Смотреть фото run php code in javascript. Смотреть картинку run php code in javascript. Картинка про run php code in javascript. Фото run php code in javascript run php code in javascript. Смотреть фото run php code in javascript. Смотреть картинку run php code in javascript. Картинка про run php code in javascript. Фото run php code in javascript

Using the Fetch API to Run PHP Code

You can also use the Fetch API to run PHP code on data collected inside the browser by sending a POST request to the server. In the previous example, we could replace the AJAX code with the following JavaScript to get the same result.

Call a JavaScript Function From PHP

The above example shows how you can pass data from PHP to JavaScript by simply echoing it. Just make sure that the code you echo is valid JavaScript.

Conclusion

We all know that PHP runs on servers and JavaScript usually runs in browsers. Since they both execute at different times, you cannot simply call functions from one language inside another and expect the code to work. However, there are ways to work around that issue, making it possible to exchange information between PHP and JavaScript.

To summarise, you can use AJAX when you want to call a PHP function from JavaScript or run PHP code on some data generated inside browsers. You can use echo in PHP to output JavaScript code which will run later in the client’s browser. If you have any questions about the article, please let me know in the comments.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

run php code in javascript. Смотреть фото run php code in javascript. Смотреть картинку run php code in javascript. Картинка про run php code in javascript. Фото run php code in javascript

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

Источник

Running JavaScript inside PHP code

Join the DZone community and get the full member experience.

v8js is a new PHP extension able to run JavaScript code inside V8, Google’s JavaScript interpreter that powers for example Chrome and NodeJS.

Installation

V8 must be present on the machine in order to install the extension. On a Debian/Ubuntu system, run the following:

libv8-dev will also install libv8 in its latest version.

Afterwards, download and compile the extension with:

There are no more requirements for compilation apart from the usual dependencies for PECL packages, like build-essential.

to php.ini or to a section in conf.d.

will confirm you the extension is loaded.

Some introspection

PHP’s reflection let us take a look at the classes and methods provided by this extension, even without documentation available. It probably hasn’t been written yet, due to the unstable API.

Interesting! We have just executed our first JavaScript expression inside a PHP process. Apparently the last statement’s value is returned by the executeString() method, with a rough conversion preserving the type:

Syntax or runtime errors are signaled with a V8JsException:

Let’s add more difficulty

The FizzBuzz kata OO solution is an example of JavaScript code creating an object and executing anonymous functions: it’s a good test bench for our integration.Since evaluating a variable as the last line returns it, that is our channel of communication, supporting integers, strings, floats, booleans, arrays (not objects at this time). Meanwhile, input for JavaScript code can be embedded into the executed string.

This code will output string(8) «FizzBuzz»:

By changing it a bit, we can build a JSON string by backslashing the double quotes («), and returns it in lieu of an object to communicate to the PHP process a complex result:

Wiring

Executing an external script would be nice: it would provide better stack traces, with traceable line numbers at the JavaScript level. It would also mean we won’t need backslashing for single quotes, simplifying the syntax.

We cannot load scripts on the JavaScript side out of the box, due to V8 missing this functionality (Node JS adds this feature) but we can load the code on the PHP Side:

Execution results in:

However, we still miss the capability of including JavaScript libraries.

Conclusion

There are many possible use cases for v8js, like sandboxed scripting or the integration of some code which was written for the client side. That would not be the most clean solution, but it’s a Turing complete approach, so why not?

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *