如何在同一页面上发出AJAX请求并获取PHP脚本?

For some reason, I need to pass an ID via AJAX to a PHP function on the same page and run a query and return the result back to AJAX which would then append the final result into a div.

As I did some research, I came across this solution, but there are some shortcomings with it.

  1. function1($_GET['id']);**//not getting the id's value**
  2. echo "This is function 1 AND id=".$param;**//this string must be passed back to the previous ajax request.**

AJAX request (efund.phtml)

$.ajax({
    type:'GET',
    url:'efund.phtml',
    data:"function_to_call=0?id"+cl[3], 
    success: function(data){
        // alert('successful');    
    }
});

PHP (efund.phtml)

switch ($_GET['function_to_call']) {
    case 0:
        function1($_GET['id']); // not getting the id's value
        break;

    case 1: 
        function2();
        break;

    default:
        break;
}

//And your functions. 

function function1($param) {
    echo "This is function 1 AND id=".$param; // This string must be passed back to the previous AJAX request.
}

function function2() {
    echo "This is function 2";
}

Change

data:"function_to_call=0?id"+cl[3], 

to

data: {function_to_call: 0,id : cl[3]},

in this case data work as object and it is easy to fetch value.

According to your only first condition called every time because you are passing function_to_call=0

The most common way to communicate between server/client tends to be to use XML or JSON, for your case I recommend you use JSON:

$.ajax({
  method: "GET",
  url: "efund.phtml",
  data: { function_to_call: 0, id: cl[3] }
})
  .done(function( msg ) {
    var obj = jQuery.parseJSON( msg );
    alert( "ID obtained from server is " + obj.id );
  });

And then in the server get them using:

$_GET['function_to_call']    // To obtain 'function_to_call' param
$_GET['id']                  // To obtain 'id' param

To send information back as response from the server I recommend you, use the same approach and use json_encode for parse an array as JSON and return it using:

in your case for function1 it would be:

function function1($param) {
         return json_encode(array ( "id" => $param ) );
    }

Also, maybe you should consider if you should use GET or POST for the Http request. You can see more information about it here: www.w3schools.com/tags/ref_httpmethods.asp

Edit: If you have problems with the ajax request and you want to check if the ajax request is executed correctly modify the Ajax code like this:

  $.ajax({
      method: "GET",
      url: "efund.phtml",
      data: { function_to_call: 0, id: cl[3] }
    }).fail(function() {
      alert( "error" );
    }).always(function() {
       alert( "complete" );
    }).done(function( msg ) {
        var obj = jQuery.parseJSON( msg );
        alert( "ID obtained from server is " + obj.id );
      });