0

I have two php files one is index.php and other is phpscriptname.php. i need to call differet functions by using ajax and case method. i found a solution in a website which i give below, but this is not working.

index.php as below

<script>

$.ajax({ url: 'phpscriptname.php',
         data: {function2call: 'getEmployeesList'},
         type: 'post',
         success: function(output) {
                      alert(output);
         }
});
</script>

phpscriptname.php as below

<?php?
if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
    $function2call = $_POST['function2call'];
    switch($function2call) {
        case 'getEmployeesList' : getEmployeesList();break;

    }
}


function getEmployeesList(){

    return "hai";
}


?>

i was expected "hai" in a popup. but it is not working.

4
  • 1
    you should echo instead of return to get value in ajax. so just replace return "hai"; by echo "hai"; Or if you want to return multiple data then refer stackoverflow.com/a/52404102/6309457 Commented Sep 27, 2019 at 12:56
  • Dear devsi odedra, i tried echo, but it is not working, can you please check from your side, Thanks in advance! Commented Sep 27, 2019 at 13:00
  • debug your switch case and see in console that what you passed what response you got Commented Sep 27, 2019 at 13:02
  • dear debung, thanks, it is solved. Commented Sep 27, 2019 at 14:04

1 Answer 1

1

alert(output); will not return anything becuase you are using return for getting plain text response from PHP, you need to use echo instead return in your method.

Second solution is that, if you want to use return in your method then you can modify your switch case as:

if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
    $data = ''; // initialize in default 
    $function2call = $_POST['function2call'];
    switch($function2call) {
        case 'getEmployeesList': 
        $data = getEmployeesList();
        break;
    }
    echo $data;
}
Sign up to request clarification or add additional context in comments.

2 Comments

dear devpro, thanks for your supprot, it is solved!
@SABITH: glad to help u

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.