Ajax php class method

I’m a coder. Welcome to my blog. Here are some of the records on my job.

Home

Categories

Calling a PHP class method using AJAX

I have come up with the following bits of code to call a method via AJAX in my PHP classes:

class Ajax extends Controller < private $class; private $method; private $params; function __construct() < $this->params = $_POST; // Call params $call = explode('->', $this->params['call']); $this->class = new $call[0]; // e.g. controller->method $this->method = $call[1]; array_shift($this->params); $this->parse(); > public function index() < //Dummy >public function parse() < $r = ''; $r = call_user_func_array(array($this->class, $this->method), $this->params); echo $r; > > 
function creditCheck2(id) < $.post(ROOT + 'Ajax', creditState', id: id, enquiryid: enquiryId>, function(data) < alert(data) >, 'json') > 

It seems to work great, but is it secure and could it be better?

Just for reference, I have added my code with the changes suggested by the answers:

class Call extends Controller < private $class; private $method; private $params; private $authClasses = array( 'Gallery' ); function __construct() < $this->params = $_POST; // Call params $call = explode('->', $this->params['call']); if(!in_array($call[0], $this->authClasses)) < die(); >$this->class = new $call[0]; // e.g. controller->method $this->method = $call[1]; unset($this->params['call']); $this->parse(); > public function parse() < $r = ''; $param = array(); // Params in any order. $mRef = new ReflectionMethod($this->class, $this->method); foreach($mRef->getParameters() as $p) < $param[$p->name] = $this->params[$p->name]; > $this->params = $param; if($r = @call_user_func_array(array($this->class, $this->method), $this->params)) < echo $r; >else < >> > 

Small issues

It could be better in that array_shift($this->params) unnecessarily assumes that the first item in the params array will always be call . That’s not true and it does not agree with the direct access $this->params[‘call’] you are doing a little earlier. The array_shift should be replaced with simply unset($this->params[‘call’]) .

Читайте также:  Php convert to space

Bigger issues

There is also the problem that the order of values in the params array must match the order of parameters in the signature of the method you are trying to call. I don’t think there is a guarantee that the order will be the same as the order of the parameters in the AJAX request, so that’s a theoretical problem.

VERY big problem

More importantly, this way of doing things forces the author of the AJAX code to match the order of parameters in the signature of the method you are trying to call. This introduces a horrible level of coupling and is a major problem. What’s worse, changing the order of the parameters by mistake will not be apparent. Consider:

public function bankTransfer($fromAccount, $toAccount, $amount); $.post(ROOT + 'Ajax', < call: 'Bank->bankTransfer', from: "sender", to: "recipient", amount: 42 >, function(data) < . >); 

This would work. But if you do this

$.post(ROOT + 'Ajax', < call: 'Bank->bankTransfer', to: "recipient", // swapped the order of from: "sender", // these two lines amount: 42 >, function(data) < . >); 

You will get the opposite result of what is expected. I believe it’s immediately obvious that this is extremely bad.

To solve the problem you would have to use reflection to match the array keys in $this->params with the formal names of the parameters of the method being called.

Security

Finally, this code is insecure in that anyone can make a request that directs your code to call any method of any class with the appropriate parameters — even methods that should not be accessible from a web environment.

This is another serious problem and cannot really be fixed unless you introduce some type of filtering to the dispatch logic.

Call the javascript class method using this keyword in addeventlistener

I want to call the javascript class method using addEventListener with parameters using this keyword var _this = this; function onClickBound(e) < _this.getItemList.call(text_box, e || window.event); >if (text_box.addEventListener) < text_box.addEven

Calling a PHP class method and getting the return value using jQuery and AJAX

I’m creating a little project for myself. I’m not a very experienced programmer, so I began creating the project in PHP. Soon it became evident that running PHP functions and class methods via HTML button clicks wasn’t the most straightforward of tas

Call the php class method from the string with the parameter

I am having trouble calling a class method from a string in PHP. Here’s a simple example. Once I get this working I’ll be using a variable as the method name. Here’s how I’d be calling the method normally: $tags_array = $this->get_tags_for_image($row

Читайте также:  Css body font url

Dynamic calling of PHP class methods

Is there any security problem with dynamically calling a method in a class from user input. For example: > $obj = new A(); $method = $_GET[‘method’]; $obj->$method(); I am aware that the user wi

Is there a way to access a PHP class method using JavaScript via jQuery?

I have a JavaScript script: $(«#feedbacksubmit»).click(function() < if($("#frmfeedback").valid()) < var tname = $("#name").val(); var temail = $("#email").val(); var tphone = $("#phone").val(); var tconten

Unable to call a controller action method using Ajax

I am beginner to jquery-ajax. I trying to get Employee data into front-end using ajax method. But the url is not calling the action method. Please check the below code MyScripts.js: function fn_test() < var eno = $("#t1").val(); $.ajax(< cache :

How to call the jsp controller method using ajax

I am using spring boot, maven 3.2.5. I am working on simple maven webapp using spring boot following mvc pattern. i am trying to call controller method from jsp suing ajax. this is my jsp javascript method look like , which call the ajax call to call

How to call a php controller method using jquery?

I am developing a web application and i am integrating jquery in it. Now looking for ajax calls with jquery to my controller function. jquery.ajax() would be useful i think so. But how to call my controller method. $.ajax(< type: "POST&quot

Calling a PHP class from the AJAX responding script

I’m trying to reach a PHP-File via AJAX. When I’m using a simple PHP-File like this:

Calling a different class method using the selector when the button is clicked

I have written a method and hooked that up with a button so that it gets called when the button is clicked. Now what I want to do is to call that same method when a button on some other view is clicked. How can I do that? Do I need to use selector or

Php class methods used statically without class reference?

I have a class like this: class Utils< public function hello() < return "Hello World
«; > > Can I now do something directly like this in my page.php: require_once(«classes/Utils.php»); echo hello(); Or must

c ++ Calling a different class method with a for loop

im trying to call a different class method using the [i].display(); function the error im getting i as follows: no operator «[]» matches these operands Here is my relevant code: Main.cpp: for (int i = 0; i < n; i++)< char date_description[7];

call the java method using ajax on the click button

I have a button in blank.jsp (lets say).

Calling the base class method from instance creation using the type function

Normally, a base class method in Python can be called from a derived class the same way any derived class function is called: class Base: def base_method(self): print(«Base method») class Foo(Base): def __init__(self): pass f = Foo() f.base_meth

Читайте также:  No ocijdbc19 in java library path

Источник

Как передать код статического метода класса PHP через ajax?

Есть класс с методами, которые отрисовывают различные элементы на странице(например запись/пост). Как через ajax передать сгенерированную методом запись(html+php)?

Простой 7 комментариев

Adamos

Задача поставлена неверно.
Исполнить задуманное можно только грязными хаками, не имеющими права на существование.

ThunderCat

Adamos, схренали? Как раз вполне по DRY. Есть готовые хелперы, если они возвращают куски хтмл в готовом виде их и надо использовать.

Adamos

ThunderCat

Adamos, человек не умеет грамотно объяснять задачу, видимо еще опыта мало. Впрочем, в том что у него это действительно что-то вроде хелперов тоже не факт. В целом ему, конечно же, не нужен пхп код на выводе, ему нужно результат отработки скрипта, очевидно. Но видимо код кривоват или не правильно используется.

Adamos

ThunderCat, именно кривое объяснение и вынудило меня предположить, что ТС придумал ядерный велосипед с охлаждением реактора задницей пассажира.
А не сделал все, как положено в солидных фреймворках, и теперь просто не может объяснить.

Adamos, мне всего лишь нужно было засунуть код сгенерированного поста в переменную 😉 Решение Роман — помогло. Не знаю как я не смог до этого додуматься :c

Adamos

ArtyomPLAY, особенно странно, как вы это сформулировали в вопросе.
Хотя и прекрасно, что вы не пытаетесь сделать то, что написали 😉

Источник

Как передать код статического метода класса PHP через ajax?

Есть класс с методами, которые отрисовывают различные элементы на странице(например запись/пост). Как через ajax передать сгенерированную методом запись(html+php)?

Простой 7 комментариев

Adamos

Задача поставлена неверно.
Исполнить задуманное можно только грязными хаками, не имеющими права на существование.

ThunderCat

Adamos, схренали? Как раз вполне по DRY. Есть готовые хелперы, если они возвращают куски хтмл в готовом виде их и надо использовать.

Adamos

ThunderCat

Adamos, человек не умеет грамотно объяснять задачу, видимо еще опыта мало. Впрочем, в том что у него это действительно что-то вроде хелперов тоже не факт. В целом ему, конечно же, не нужен пхп код на выводе, ему нужно результат отработки скрипта, очевидно. Но видимо код кривоват или не правильно используется.

Adamos

ThunderCat, именно кривое объяснение и вынудило меня предположить, что ТС придумал ядерный велосипед с охлаждением реактора задницей пассажира.
А не сделал все, как положено в солидных фреймворках, и теперь просто не может объяснить.

Adamos, мне всего лишь нужно было засунуть код сгенерированного поста в переменную 😉 Решение Роман — помогло. Не знаю как я не смог до этого додуматься :c

Adamos

ArtyomPLAY, особенно странно, как вы это сформулировали в вопросе.
Хотя и прекрасно, что вы не пытаетесь сделать то, что написали 😉

Источник

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