LefterisL
LefterisL

Reputation: 1143

AJAX load specified function from php file

I am currently using the script below to fill some divs with data i need

function fillLeagues(){
    var load = $.get('drawleague.php');
    $(".really").html('Refreshing');
    load.error(function() {
      console.log("Mlkia kaneis");
      $(".really").html('failed to load');
      // do something here if request failed
    });
    load.success(function( res ) {
      console.log( "Success" );
      $(".really").html(res);
    });
    load.done(function() {
      console.log( "Completed" );
    });
}

I was wondering if it was possible to call a certain function in the drawleague.php file that will return the info since i don't wanna use say 10 php files to fill 10 divs for example.

Upvotes: 0

Views: 73

Answers (2)

thpl
thpl

Reputation: 5910

I'd suggest you use get parameters in order to achieve this behavior. Pass the function name via Get parameter and call it in your PHP file. Of course you need to create some kind of protection. See below (pretty provisoric).

<?php

$param = $_GET['p'];

$whitelist = [
    'func1',
    'func2',
    'func3'
];

if(!in_array($param, $whitelist))
    die("Sorry, no manipulating");

call_user_func($param);

function func1()
{
    //Some stuff
}


function func2()
{
    //Some stuff
}


function func3()
{
    //Some stuff
}

?>

Then pass the param in your JS part:

var load = $.get('drawleague.php?p=func1');

Upvotes: 2

Richard Peck
Richard Peck

Reputation: 76774

Ajax & PHP are different technologies, which means they can only communicate in certain ways

This means that it doesn't matter if you have 1 or 100 files, if you can call the functions inside the file, you can keep it to one file

I would recommend this:


Params

jquery $.GET parameters passing in the url

You can pass parameters through your $.GET request to your PHP file. This means inside your PHP, you can take these params & determine the output

Because you havn't posted any PHP code, here's what you might be able to use:

<? 
   switch ($_GET["name"]) {
      case "x":
         return $image_x;
         break;
      }
   }
?>

Upvotes: 4

Related Questions