dave
dave

Reputation: 475

Echo HTML from PHP to display in ajax request on webpage

I have a list of scientific publications displayed on a website and would like to load additional content as the user arrives at the end of a list of 10 publications, and presses a button to load another 10 publications.

I make an Ajax call to load the next 10 publications

I am trying to display html code that is echo-ed from php script but I cannot appear to display the html. In the console, I am getting '1' as a value for my HTML. I do not understand: 1. why I am getting the value of '1'; 2. Also, is it good practice to echo HTML to be displayed via javascript?

JS (AJAX call):

  var resp = xmlhttp.responseText;
  var respArray = resp.split('|');
  var response = respArray[1];
  var publicationList = respArray[0];

  var currentHTML = document.getElementById('showPubs').innerHTML;

  if(response == '1'){
  console.log('more publications available');

        var currentHTML = document.getElementById('showPubs').innerHTML;
        document.getElementById('showPubs').innerHTML += publicationList;

        }else{
            document.getElementById('showPubs').innerHTML += '<div id="noMorePub">No more publications</div>';

   }

PHP:

 $recentPublications .= '
        <div id="pub'.$articleID.'" class="pub20">
            <div class="divImg">'.$avatarPathHTML.'</div>
            <div class="contentPub">
                <div class="datepub">
                    <div class="fullName"><a class="sfullNme" href="2profile.php?username='.$articleUsername.'">'.$fullname.'</a></div>
                    <div class="date">'.$submitDate.'</div>
                </div>
                <div class="divLink">
                    <a href="testPage3.php?article='.$articleID.'" class="pubLink">'.$articleTitle.'</a>
                </div>
                <div class="authorString">'.$author_string.'</div>
            </div>
                <hr class="pubSeparator">
        </div>
    ';


 echo $recentPublications.'|1';

Upvotes: 0

Views: 356

Answers (2)

Michail M.
Michail M.

Reputation: 755

I guess better idea is not use this dirty hack

  echo $recentPublications.'|1';

and

  var respArray = resp.split('|');
  var response = respArray[1];
  var publicationList = respArray[0];
  if(response == '1'){

You can just check length of response. if length of response is equal 0 bytes then other publications are not available.

Upvotes: 1

Karol Klepacki
Karol Klepacki

Reputation: 2098

The good practice is to separate concerns. Therefore, in your example, server-side script should only provide data to be displayed (ex. JSON via), and frontend should make AJAX call to specific endpoint.

Upvotes: 0

Related Questions