Home > Software design >  AJAX response with include statement in a while loop
AJAX response with include statement in a while loop

Time:09-22

I have an AJAX call to a PHP file where I get the data from MySQL database in a while loop. Then I am returning this back as response. So far so good.

Part of working sample PHP file called by AJAX looks like this. EDIT: echo in this sample is not a part of the some-HTML-included-file.php file in the second example.

... mysql commands ...
while($data = $result->fetch_assoc()){
    echo 'some HTML here' . $data['id'];
}

Now because the HTML (here in while loop) is quite big in my application and I use it also in another files, I have it in separate file and just including it.

So the result looks like this

while($data = $result->fetch_assoc()){
    echo include 'inc/some-HTML-included-file.php';
}

It kind of works, but it also returns true for successful include which becomes 1 in resulting HTML.

My question is, how to do this the correct way, so I get the result without additional 1s.

Note: I found similar question here, but this obviously does not work in a loop.

CodePudding user response:

Since the file itself already echoes data, just use include instead of echo include. You don't need to output the result of the include command!

Or do what most people would and implement this as a function which returns a string of HTML, rather than a raw include which directly echoes content - that approach is very obsolete.

For example:

function getRowContent($data)
{
  return 'some HTML here' . $data['id'];
}

while($data = $result->fetch_assoc()){
    echo getRowContent($data);
}

(Obviously to share that function across PHP scripts you can put the function in a separate PHP file and then include_once the file at the top of any script in which you want to use it, so that the function is then available to be called when needed.)

  • Related