>

How to call PHP function from JavaScript tutorial

If you’re using PHP files to render your web pages, then you can call the PHP function from JavaScript by calling the PHP echo() function.

Suppose you have an index.php file with the following content:

Then, you write your HTML content right below the function as follows:
 You can include a tag inside the tag that calls on PHP function as follows:
 When you open your index.php file from the browser, you will see the HTML rendered as follows:
Any PHP code that you include inside your HTML page will be processed on the server-side before being served to the browser.

When you call a PHP function inline from JavaScript as shown above, you can’t use dynamic values from user input.

If you want to call PHP function as a response to user action, then you need to send HTTP request from JavaScript to the PHP file. Let’s learn that next.

Call PHP function from JavaScript over HTTP request

  • separate your PHP file from your HTML file
  • Call the PHP function over an HTTP request using fetch() JavaScript method

First, separate your PHP function in a different file. Let’s call the file add.php and put the following content inside it:

Next, create an index.html file in the same folder where you created the add.php file and put the following content inside it:
The fetch() method will be executed each time the element is clicked. JavaScript will send a POST request to the PHP server and write the response inside the element.

In the code above, I used the full URL of my add.php , which is located at http://localhost:8000/add.php . You need to change the address to your actual PHP file location.

Once your files are ready, open the index.html file from the browser. Please make sure that you’re opening the HTML file from the same server that serve your PHP files to avoid CORS issues.

You can run a local PHP server using php -s localhost:8000 command and open localhost:8000/index.html from the browser to see your HTML page.

When you click on the button, the fetch() method will be executed and JavaScript will put the response inside the element.

The resulting HTML would be as follows:

 Now that your code is working, you can add elements to the HTML page and assign the values that the user puts in those elements to x and y variables. The PHP function should be able to add the dynamic values correctly

And those are the two ways you can call PHP function from JavaScript. More often, you’d want to separate the PHP files from your JavaScript files and call PHP function using HTTP requests.

The same pattern also works when you’re developing web app using modern PHP framework like Laravel and modern JavaScript libraries like React and Vue.

You can use the fetch() method and send a POST request to the right Laravel API route that you created and send the right parameters.

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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

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

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

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

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

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

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

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

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

AddType application/x-httpd-php .htm .html AddHandler x-httpd-php5 .htm .html SetHandler application/x-httpd-php 

Замечания, дополнения и обмен опытом приветствуются.

ВЫВОДЫ

Довольно странно, что небольшая заметка, которая фактически предлагает всего-навсего сниппет для быстрой реализации конкретной практической задачи вызвала такое бурное обсуждение, по большей части похожее на попытки блеснуть теорией. Знаменитое хабра-сообщество в данном случае самоотверженно линчевало те идеи, которые в заметке в принципе не затрагивались. Хотя надо отдать должное — несколько здоровых мыслей все таки есть. И кроме того — нет «никакой другой роскоши, кроме роскоши человеческого общения» (если верить Экзюпери)))).

Источник

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:

--- title: Running PHP in Javascript ---   

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:

// No server needed, "just" Javascript parsing PHP alert(php(``)); 

But not even Reddit’s «PHP» search in r/atwoodslaw could find what I seek.

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:

import parser from 'php-parser'; import translator from './translator'; import generator from '@babel/generator'; const run = (code, opts) => < // Make a closure so that `out` doesn't collide with the PHP variables: let out = ''; // Define `echo` since it's used in the transpiled JS code for some reason opts.echo = opts.echo || (str =>out += str); // Pretend this is safe. Pro tip: IT IS NOT SAFE new Function(. Object.keys(opts), code)(. Object.values(opts)); return out; > export default function (src, opts = <>) < const ast = new parser().parseCode(src); const file = translator.translateProgram(ast); const code = generator(file).code; return run(code, opts); >; 

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

Demo

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 .
  • 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:

Источник

Читайте также:  Css not any child
Оцените статью