Как в javascript вставить php
Перейти к содержимому

Как в javascript вставить php

  • автор:

Выполнение PHP-кода в файлах JavaScript

В большинстве веб-приложений статические JavaScript-файлы устраивают разработчика на 100%. Однако же иногда бывает лучшим решением подключить PHP и сгенерировать содержимое JS-файла «на лету» (например, получить актуальные цены на продукты из БД и передать их JavaScript-программе для валидации формы заказа). Как же это сделать?

Способ первый: простой

Конечно же, самое простое решение состоит в том, чтобы включить код PHP внутрь секции вашего HTML-шаблона, поскольку есть шансы, что у него будет расширение .php.

Даже если расширение шаблона .htm или .html, то в большинстве случаев веб-сервер настроен так, чтобы понимать включения PHP-кода (если же нет, то в конце заметки есть простой пример как решить и эту проблему). Но что касается красоты, то этот вариант не самый изящный. Хорошо бы держать мух и котлеты раздельно.

Способ второй: красивый

Второй вариант решения — настроить веб-сервер так, чтобы он парсил JavaScript-файлы на предмет выполнения PHP-кода. Достаточно создать в нужной папке файл .htaccess или открыть уже существующий и добавить в него следующие строки:

Pro et Contra: что нам это дает?
  • Вы можете включать PHP-код в файлы с расширением .js и он автоматически выполнится при клиентском обращении к JavaScript-файлу.
  • Вы можете держать такие «гибридные» скрипты в отдельной папке — достаточно в эту папку поместить описанный выше файл .htaccess.
  • Если вы хотите держать все JavaScript-файлы в одном месте (статические и гибридные), то можете зарегистрировать обработчик файлов с произвольным расширением, например, .js2 — достаточно немного модифицировать текст .htaccess.
  • Вы можете разделить статические HTML-страницы, шаблоны и JavaScript-файлы.
  • Теоретически это вызовет минимальную дополнительную нагрузку на работу сервера, но, учитывая вариации с отдельными папками или расширениями файлов, польза кажется превосходящей.
Дополнение

Для того, чтобы веб-сервер парсил файлы .htm и .html и выполнял включенный в них PHP-код, нужно добавить в .htaccess следующие строки:

Как вызвать функцию PHP из JavaScript

От автора: PHP имеет гораздо больше встроенных функций для работы со строками, массивами и другими типами данных по сравнению с JavaScript. Поэтому для многих естественным является желание вызывать функции PHP из JavaScript. Однако, как вы уже догадались или узнали, это не работает должным образом.

Может быть множество других случаев, когда вы захотите запустить некоторый PHP-код внутри JavaScript — например, чтобы сохранить некоторые данные на сервере. Простое размещение PHP-кода внутри JavaScript в этом случае тоже не сработает.

Причина, по которой вы не можете просто вызвать функцию PHP из JavaScript, связана с порядком, в котором выполняются эти языки. PHP — это серверный язык, а JavaScript — это, прежде всего, клиентский язык.

Каждый раз, когда вы хотите посетить страницу, браузер отправляет запрос на сервер, который затем обрабатывает запрос и генерирует некоторые выходные данные, запустив код PHP. Затем полученная или сгенерированная веб-страница отправляется вам обратно. Браузер обычно ожидает, что веб-страница будет состоять из HTML, CSS и JavaScript. Любой PHP, который вы могли разместить или повторить внутри JavaScript, либо уже запущен, либо не будет работать вообще, когда веб-страница загружается в браузере.

Однако надежда еще не потеряна. В этой статье я объясню, как вы можете вызывать функции PHP из JavaScript и функции JavaScript из PHP.

Профессия Frontend-разработчик PRO

Готовим Frontend-разработчиков с нуля

На курсе вы научитесь создавать интерфейсы веб-сервисов с помощью языков программирования и дополнительных технологий. Сможете разрабатывать планировщики задач, мессенджеры, интернет-магазины…

Вызов функции PHP из JavaScript

Мы можем использовать AJAX для вызова функции PHP для данных, созданных внутри браузера. AJAX используется на многих веб-сайтах для обновления частей веб-страниц без полной перезагрузки страницы. Если все сделано правильно, это может значительно улучшить взаимодействие с пользователем.

Имейте в виду, что код PHP по-прежнему будет работать на самом сервере. Мы просто предоставим ему данные из нашего скрипта.

Использование jQuery AJAX для запуска кода PHP

Если вы используете jQuery, становится невероятно легко вызвать любой файл PHP с кодом, который вы хотите запустить.

Вы можете передать в функцию один или два параметра ajax(). Когда передаются два параметра, первым будет URL-адрес веб-страницы, на которую браузер отправит ваш запрос. Когда вы передаете только один параметр ajax(), URL-адрес будет указан в конфигурации.

Второй параметр содержит набор различных параметров конфигурации, чтобы указать данные, которые вы собираетесь обрабатывать, и что делать в случае успеха или неудачи и т. д. Параметры конфигурации передаются в формате JSON.

Вы можете использовать параметр method, чтобы указать метод HTTP, который следует использовать для выполнения запроса. Мы будем устанавливать его как POST, потому что мы будем отправлять данные на сервер.

Теперь давайте рассмотрим пример базового запроса AJAX, в котором мы будем передавать данные в файл PHP и вызывать функцию PHP wordwrap() внутри этого файла. Вот наша полная веб-страница:

How to Call a PHP Function From JavaScript

Monty Shokeen

Monty Shokeen Last updated Feb 17, 2021

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.

You can pass one or two parameters to the ajax() function. When two parameters are passed, the first one will be the URL of the webpage where the browser will send your request. When you pass only one parameter to ajax() , the URL will be specified in the configuration.

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.

Calling PHP Function in JavaScript with AJAXCalling PHP Function in JavaScript with AJAX Calling PHP Function in JavaScript with AJAX

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.

Just like in the AJAX example, we specify the URL and provide additional header information that we will be sending our data in URL encoded form. This allows us to use $_POST on the server side to read the data.

Call a JavaScript Function From PHP

As you know by now, PHP will run before JavaScript when you request a webpage from some server. We can also output anything we want to show on the webpage using echo . The same echo can be used to output JavaScript that will run in the client’s browser.

Here is some example code that will check an array of strings to find the index of the last palindrome. This index is stored in a PHP variable, which is then passed to JavaScript written inside the script tag using echo .

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!

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 PHP in Javascript ��

But why? you are wondering. You must be given some context: this is an experiment inside another experiment I'm doing to learn about Static Site Generators. PHP is the first language I knew well and I wanted to test whether it's a horrible or just a bad idea to use it for templates.

If you come from Google trying to find how to run PHP inside Javascript, you are very likely lost. Beware, this article is only for experts! /s

Since a large motivator for my site generator is to rely purely on Node.js and not to have to install Ruby, I also don't want to install PHP! But can you run PHP inside Javascript? I only need the most basic PHP features: variables, echo, loops.

The sarcastic language of this article might be deceiving, but there is a working demo below.

Initial objective

The idea came when I was making FrontMatter work properly for the current file. It is also related to my general dissatisfaction with the Node.js template engines, but that a topic for another day:

It reminded me quite a bit to what can be achieved with raw PHP:

Googling around

Google just led me to 780 StackOverflow questions with -1 average score. After reading some, I believe the average score should be more like -5 . I also learned that devs are trying to do:

As an astute reader might notice, that is supposed to run first through the PHP server, then sent to the browser and finally run the resulting alert("Hello world") on the client. But this level of sophistication is too high, I just want to run raw PHP on the browser! I want something like this:

Promising finds

After getting lucky with a "PHP parser Javascript" search, I end up finding the package php-parser in Github/npm. The problem is that the output is an Abstract Syntax Tree. I just wanted to run the code, not whatever an abstract tree seems to be:

An abstract tree somehow

Since you are reading this it means that in the Related Projects category I found my next clue. I head to the website with the funny looking cat : babel-preset-php . It transpiles PHP into Javascript ��

Since babel is in total chaos with the whole babel-loader vs @babel/loader and no one knows which one is which (ironic, innit?), I give up and take a break. I do practice my Kanjis, speak with my family in Spanish and think about the English title for this article.

Building up the library

Fresh again, I scavenge the library babel-preset-php for my project. I am now using:

  • php-parser to transform the PHP into the Abstract Tree thing.
  • babel-preset-php ravaged files to do something that I have no idea what it is but it's the only way to keep it working.
  • @babel/generator to finally generate the Javascript from the previous step.
  • A bit of Javascript. I use the fancier new Function() to pretend it's better than eval() .

I wasn't going to show you, but since my code is so tiny thanks to those great libraries I can just paste it here for your satisfaction:

Later on I will export some individual parts for better testing, but that is really all there is to it.

The long-awaited demo! Turn your internet off, hide your kids and say your prayers. I already loaded the php() function for you, but are you ready to run it?

Tips to make the demo better for lack of documentation:

  • Use backticks as the first argument of php() to allow for any quote type and multi line.
  • Provide a second argument as a plain object like < hello: 'world' >to define the variable $hello with the value "world" inside the PHP code.
  • If you want to run it with express use < _GET: req.query, _POST: req.body >as the second argument (do not do it, specially on a live server).
  • You could pass window as the second argument as well if you prefer PHP instead of Javascript. Heck, you could make a tool that finds and runs all <script src="ohmy.php" type="application/php"></script> .
  • I am running eval() against your code. The php() function is basically running eval() internally. Do I get a "Go to Jail card" for basically doing eval(eval(. )) ?

Closures

Yup, this sucks. Use it just as an example of things that should never happen. If you really, really need to use this, and want more features, feel free to throw me loads of money and I might consider talking you out of it or contacting the relevant health authorities.

Now that we have reached this point and seeing how many languages have AST generators, I ponder: can any language be transpiled to Javascript? Should we do it? Webassembly is going to eat JS so we might just give it a try!

If you hate PHP, or Javascript, and you really want to let me and others know* feel free to comment on Hacker News:

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

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