Calling a specific PHP function with Jquery & amp; Ajax

综合编程 2018-04-23 阅读原文

For me this is something new, so I am just researching this and trying to understand it. As you can see in the php script there are 2 functions and I am trying to call a specific one with jquery.

Now if I have one function then I can do it, but when I have 2 or more I am starting to get stuck. I suppose I could do this when I have 2 functions, but as soon as more variables are in play or more functions do I just make massive if statements in my php?

The problem is that when I attach a database to it, I would need to consider all inputs that can happen. How do I specify a specific php function when using jquery & ajax?


This text is going to change>
$(document).ready(function() { $('#calling').load(function() { $.ajax({ cache: false, type: "POST", url: "function.php", data: 'name=myname' success: function(msg) { $('#calling').html((msg)); } }); // Ajax Call }); //event handler }); //document.ready

You need to pass a parameter in, either via the data object or via a GET variable on the URL. Either:

url: "function.php?action=functionname"


data: {
    name: 'myname',
    action: 'functionname'

Then in PHP, you can access that attribute and handle it:

if(isset($_POST['action']) && function_exists($_POST['action'])) {
    $action = $_POST['action'];
    $var = isset($_POST['name']) ? $_POST['name'] : null;
    $getData = $action($var);
    // do whatever with the result

a better idea for security reasons would be to whitelist the available functions that can be called, e.g.:

switch($action) {
    case 'functionOne':
    case 'functionTwo':
    case 'thirdOKFunction':
        die('Access denied for this function!');

Implementation example:

// PHP:
function foo($arg1) {
    return $arg1 . '123';

// ...
echo $action($var);

// jQuery:
data: {
    name: 'bar',
    action: 'foo'
success: function(res) {
    console.log(res); // bar123
Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!


原生JS实现Ajax 前 言 这篇文章将给大家详细介绍一下,与JQuery对照用原生的js怎么去实现Ajax。 JQuery提供的Ajax方法: ...
What is a good autocomplete to use for a search fi... I am looking for an autocomplete ( or autosuggest) that is good for a search ...
PHP知识整理之——PHP基础、WEB安全、网络... 本篇文章是PHP知识系统整理系列之——PHP基础、WEB安全、网络,包括 PSR 规范,PHP7特性和性能提升,HTTP、HTTPS、TCP、WebSocket...
Geocoder 4.0.0 发布,PHP 移动定位应用开发库... Geocoder 4.0.0 正式版发布,Geocoder 是一个 PHP 开发库,帮助你构建移动定位应用,提供一个强大的地理编码操作的抽象层。 更新内...
外部排序–PHP版本 发现网上搜不到PHP版本的外部排序,有点心疼。所以打算自己写一个,这里和大家分享下。这应该是网上第一个PHP版本的外部排序。 小伙伴们应该都写过或者听过一...