javascript – Returning HTML Fragment with Ajax


Is there the possibility of returning only a fragment of the code of a page with AJAX JQuery ?

What I want to do is:

I have a page where I send the ID with AJAX through POST , and generate the body of a modal <div class="modal-body"> , but I would like to have another div to return the header of this modal <div class="modal-header"> .

Is there any way to call each div individually through the AJAX result so that the HTML changed via Javascript ?


What I have so far would be this:

    function teste(){
        var url = "&id="+teste;
        url: "conv_modal_results.php",
        type: "POST",           
        data: url,
        beforeSend: function(){
            $('.modal-body').html('<div align="center"><img src="img/loading.gif" /></div>');
        sucess: function(data){

<input type="button" value="botaozinho" onClick="teste()">
<div class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Carregando....</h4>
      <div class="modal-body">
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

In conv_modal_results.php I have the following return

<div id="corpo_modal" class="row">
Aqui vai o corpo do modal...

What I want is to be able to add one more div and be able to call each one individually in the result, using something like JQuery .find() to use just that piece of HTML


I made a simulation of something close to what you need like this:

In PHP, I return a JSON from an array containing the HTML of the header and the Body:

    $header = "<div>Meu Header</div>";
    $body = "<div>Conteúdo</div>";

    echo json_encode(array($header, $body)); 

With javascript, I make the script's ajax call and on success parse the JSON to get the array. Then just insert the content in place and display the modal:

    type: 'POST',
    url: 'index.php',               
    cache: false,
    success: function(result) {
            var resultObj = JSON.parse(result);
            $("#minhaModal .modal-header").html(resultObj[0]);
            $("#minhaModal .modal-body").html(resultObj[1]);
        else {
Scroll to Top