Ajax and php functions

Как выполнить функцию php ajax’ом?

Есть файл index.php в нем есть textarea и функция вывода информации из этой textarea и выводится этот текст в блоке с id text.

В и интернете не смог найти, как вызвать php функцию, а не файл.

Или нельзя вызывать функцию с этой страницы? И как мне поступить, чтобы после изменения textarea, в блоке с id text, выводилось то, что введено в нее без перезарузке страницы?

Вот что у меня есть сейчас:

function show() < $.ajax(< url: "gensite.php", cache: false, method: "POST", data: "cod=2", beforeSend: function() < $("#content").html("").hide(); >, success: function(data) < $("#content").html(data); >>); > $(document).ready(function()< show(); setInterval('show()',1000); >);

У меня не получается передать на страницу gensite.php информацию из textarea (Да и вообще ничего не передается ни GET, ни POST).

UPD 16.11.2014
>У меня проект связан с тем, что пользователь выполняет определенные задания(пишет код), а пока он пишет этот код(HTML и CSS), он преобразуется в страницу в блоке content, грубо говоря, генерируется сайт, который пишет пользователь.

draJzOJ.png

Вот я нашел сайт htmlacademy.ru/courses/4/run/1
Так вот, правое окно, это и есть моя цель, я пытался найти в коде как они это сделали, но нашел только одну не понятную функцию связанную с ajax, которая не связана с этим окном.

Читайте также:  Какая то там буква питон

Оценить 2 комментария

Источник

Вызвать функцию php через ajax?

Всем привет.
Я понимаю, что этот вопрос уже наверное надоел всем или кому-то покажется глупы НО. Как вызвать определенную функцию php через ajax?

Я придумал дурацкий метод, но он работает. Но мне хотелось бы правильно это сделать.
Суть такова.
Через ajax обращаюсь к файлу, где выписаны все функции. И непосредственно само обращение к определенной функции сделать через условие:

require_once 'func.php'; //пдключаю файл с функциями if (isset($_POST['intt'])) < // в пост передаю определенное название или ключ(как угодно) к которой я и обращаюсь к определенной функции $intt = $_POST['intt']; emailto ($intt); // само выполнение функции >if (isset($_POST['val'])) < $val = $_POST['val']; example ($val); >if (isset($_POST['val2']))

Подскажите, кто знает как сделать мою задачу правильно. Я гуглил, но ничего не нашел, за что можно было бы уцепиться, что придумать или решил. При поиске, на каком-то форуме меня натолкнули на такую фот идею!

ewgenio

Здесь нет какого-то «правильного» стандартного подхода, вы можете передавать один параметр постом например $_POST[‘action’]
и в зависимости от его значения(например используя switch($_POST[‘action’])) выполнять в PHP скрипте нужное действие.
Можно так как вы и сделали, с опытом и для конкретных задач вы будете сами находить нужное решение.
Будете например использовать MVC фреймворки — тогда будете осуществлять это с помощью роутингов.
Так что метод совсем не дурацкий как вы написали, просто метод для небольшого приложения.

if(function_exists($_POST['func'])) < // функция существует, надо ее вызвать $_POST['func'](); // вызвали функцию $_POST['func']($_POST['args']['arg_1']); // передали аргумент $func = $_POST['func']; $func(); // так тоже можно вызвать >

Разумеется не стоит доступ к этому скрипту давать всем. Можно ведь и свой код таким образом выполнить на сервере.
А если всем надо, то делайте список доступных функций:

$allow_functions = ['count', 'rand']; if(in_array($_POST['func'],$allow_functions) && function_exists($_POST['func'])) < // выполняем код >

Источник

How to Call a PHP function from JavaScript Using ajax

If you have to write code in PHP, it will be necessary that the information found by the server is shown dynamically on the screen. This can be done by calling a PHP function from JavaScript.

This article shows how to achieve this method and how to use it properly.

Call external PHP function from JavaScript

JavaScript is a client-side language whereas PHP is a server-side language. So this is not possible to call a PHP function from JavaScript.

But it is possible to call a PHP function using ajax. So let’s check how it works.

What’s an AJAX request?

AJAX stands for Asynchronous JavaScript and XML and it is used to make asynchronous HTTP requests (GET/POST) to send or receive data from the server without refreshing the page. It looks like this:

Make Ajax Request  

Let’s take a basic example. Suppose, you have a page and you want to call a PHP function that will print a basic sentence i.e. “Hello World!” from an external page. So how to do it?

Here I am using jQuery to get the result from external-page.php . The external-page.php contains a basic PHP function like below.

So the conclusion is you can’t call PHP function from JavaScript without ajax. But using ajax, you can call an external page that has a PHP function and you can also show the return value of that function via JavaScript.

Call PHP function from JavaScript with parameters

Sometimes you need to pass parameters to a PHP function. But here we have to use Ajax again.

We can pass our parameters using GET/POST methods. Let’s check an example.

Here we have passes two parameters i.e. fno and sno . In our PHP function, it will be added and show the result.

After refreshing the page, you will get 20.

Call PHP function from the same page using JavaScript

Suppose you need to show the current server date when a user clicks on a button. So let’s check the code.

Get Date  

In the above code, I have called the PHP date() function to show the current date and store the value into the JavaScript variable server_date .

When a user clicks on “Get Date” button, it will show the PHP-generated current date.

Final Word

This blog post has introduced you to the basics of how to call a PHP function from JavaScript using Ajax. It’s time for me to wrap this up and give you some more resources on working with AJAX through other tutorials. I hope that this tutorial was helpful! If there is anything else we can do for you, please let us know. Happy coding!

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Источник

PHP — AJAX and PHP

The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:

Example

Example Explained

In the example above, when a user types a character in the input field, a function called «showHint()» is executed. The function is triggered by the onkeyup event. Here is the HTML code:

Example

  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a PHP file (gethint.php) on the server
  • Notice that q parameter is added to the url (gethint.php?q=»+str)
  • And the str variable holds the content of the input field

The PHP File — «gethint.php»

The PHP file checks an array of names, and returns the corresponding name(s) to the browser:

// Array with names
$a[] = «Anna»;
$a[] = «Brittany»;
$a[] = «Cinderella»;
$a[] = «Diana»;
$a[] = «Eva»;
$a[] = «Fiona»;
$a[] = «Gunda»;
$a[] = «Hege»;
$a[] = «Inga»;
$a[] = «Johanna»;
$a[] = «Kitty»;
$a[] = «Linda»;
$a[] = «Nina»;
$a[] = «Ophelia»;
$a[] = «Petunia»;
$a[] = «Amanda»;
$a[] = «Raquel»;
$a[] = «Cindy»;
$a[] = «Doris»;
$a[] = «Eve»;
$a[] = «Evita»;
$a[] = «Sunniva»;
$a[] = «Tove»;
$a[] = «Unni»;
$a[] = «Violet»;
$a[] = «Liza»;
$a[] = «Elizabeth»;
$a[] = «Ellen»;
$a[] = «Wenche»;
$a[] = «Vicky»;

// get the q parameter from URL
$q = $_REQUEST[«q»];

// lookup all hints from array if $q is different from «»
if ($q !== «») $q = strtolower($q);
$len=strlen($q);
foreach($a as $name) if (stristr($q, substr($name, 0, $len))) if ($hint === «») $hint = $name;
> else $hint .= «, $name»;
>
>
>
>

// Output «no suggestion» if no hint was found or output correct values
echo $hint === «» ? «no suggestion» : $hint;
?>

Источник

Оцените статью