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

Как вызвать php из javascript

  • автор:

How to call PHP function from JavaScript tutorial

There are two ways of calling a PHP function from JavaScript depending on your web project’s architecture:

  • You can call PHP function inline from the <script> tag
  • You can use fetch() JavaScript method and send an HTTP request to the PHP server

This tutorial will help you learn both ways easily. Let’s start with calling an inline PHP function

Call PHP function from JavaScript inline

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 <script> tag inside the <body> 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

To send HTTP request from JavaScript to PHP server, you need to do the following:

  • 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 <button> element is clicked. JavaScript will send a POST request to the PHP server and write the response inside the <div > 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 <div> element.

The resulting HTML would be as follows:

Now that your code is working, you can add <input> 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.

Как вызвать функцию 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.

How can I call PHP functions by JavaScript?

I am trying to call a PHP function from an external PHP file into a JavaScript script. My code is different and large, so I am writing a sample code here.

This is my PHP code:

This is my JavaScript code:

So this is what I want to do.

My original PHP file doesn’t include these mathematical functions but the idea is same.

If some how it doesn’t have a proper solution, then may you please suggest an alternative, but it should call values from external PHP.

13 Answers 13

Yes, you can do ajax request to server with your data in request parameters, like this (very simple):

Note that the following code uses jQuery

and your_functions_address.php like this:

Victor's user avatar

Sandeep Kapil's user avatar

use document.write for example,

Anitha Mani's user avatar

You need to create an API : Your js functions execute AJAX requests on your web service

This work perfectly for me:

To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it’s impossible: directly call the proper PHP function, without adding code to the PHP file.

This for JavaScript:

So, your PHP code remain equals except return values, which will be echoed:

I suggest you to remember that jQuery is required:
Download it from Google CDN:

or from Microsoft CDN: «I prefer Google! :)»

Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website’s faster!

The choice is to you!

Now you finished! I just tell you how to use callPHP function. This is the JavaScript to call PHP:

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

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