user1683645
user1683645

Reputation: 1579

Sending multiple PHP files with AJAX

Usually when I want to create new content in a php file and implement it somewhere in my site I do something like this (JS and PHP):

    case 'someCasename':
    ...
    include_once 'file.php';
    break;

...
success: function(data){
    $("#idSelector").html(data);
}

and the new content is displayed at the selected element.

But im curious on if its possible to send multiple php files at the same time. Not sure if this is really necessary and I've not come across a single time where I need to do this but I thought of the it and wanted to ask. This last code is most likely very very wrong but I just want to showcase what i mean:

    case 'someCasename':
...
$phpArray = array("file1" => include_once 'file1.php', "file2" => include_once 'file2.php', "file3" => include_once 'file3.php'):
echo $phpArray;
break;

...
success: function(data){
    $("#idSelector").html(data.file1);
    $("#idSelector").html(data.file2);
    $("#idSelector").html(data.file3);
}

Is something like this even remotly possible? You cant json_encode php files can you?

Upvotes: 1

Views: 187

Answers (1)

jeroen
jeroen

Reputation: 91734

If I understand you correctly, your included php file echo out something that you want to use in the success function of the ajax call.

What you could do, is loop through all your includes and use output buffering to capture the output of these files in an array.

Something like:

case 'someCasename':
  ...
  $results = array();
  while (files_to_include)
  {
    ob_start;    // start output buffering
    include_once "your_file";
    $results[] = ob_get_clean();    // get the contents of the output buffer
  }
  echo json_encode($results);    // send all collected output as json to be used on the js side
  break;

Although this would work, it would of course be better to use functions that return values in your includes instead.

Upvotes: 1

Related Questions