0

I want to make ajax request for fetching data to perform join operations on different tables depends on the parameters and table names.

$.ajax({ url: '/my/site',
     data: {fun_name: 'join_user_and_state',
            param: '12,1'
      },
     type: 'post',
     success: function(output) {
                  alert(output);
              }
});

On the server side, the action POST parameter and function name should be read and the corresponding value should point to the method to invoke, e.g.:

if(!empty($_POST['param']) && !empty($_POST['fun_name'])) {
   $param= $_POST['param'];  $fun_name= $_POST['fun_name'];
 // want to call proper function name with parametters from $fun_name and $param
 // parameters could be 2 or 3 or more its depends upon user choice
 // how to call
}

//definitions
join_user_and_state($user_id,$state_id)
 {
  // will do join query here with 2 tables
 }

join_user_and_city($user_id,$city_id)
 {
  // will do join query here with 2 tables
 }

join_user_and_state_and_city($user_id,$state_id,$city_id)
 {
  // will do join query here with 3 tables
 }

how could i call appropriate function ?

or there is any other way to achieve the same , I have to perform different different join query depends upon user choice like user_state, user_city, user_education, user_salary..etc (and all combinations of these also possible) ? and these columns are present in their own table

1 Answer 1

2

You can use call_user_func()

Example:

if(!empty($_POST['param']) && !empty($_POST['fun_name'])) {
  $param= $_POST['param'];  $fun_name= $_POST['fun_name'];
  $returnval = call_user_func($fun_name, explode(",", $param));
  //handle return variable etc....
}
Sign up to request clarification or add additional context in comments.

9 Comments

is this approach will be fast or using if else give me fast result ?
@amitgupta it is very easy as it's just one line. If you later add more functions it will be the better approach, as with if else you need more and more if statements the more functions you have.
ok thanks, is this a good approach to handle diff join operation means different function for each join or i should make only one query and pass all the variables on the same query ? see last 3 4 lines of my question.
is there any other way to achieve the same ?
@amitgupta you could call just one function which builds the SQL query out of the given configuration of the tables and parameters to use.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.