Return only a certain element of the current page with jQuery AJAX

Asked

Viewed 396 times

3

Personal I am needing to pick up only one element of the current page returned via AJAX. The element I need is the id="main".

The most I could get is the full page, but I just wanted this element quoted above.

<form  id="sd_submit-job-form" class="job-manager-form" enctype="multipart/form-data">
    <h2 style='color:blue'>Escolha o tipo de anúncio:</h2>          
    <select name="aaa" id="sd-valorSel" >
        <option value="-1">Selecionar...</option>           
        <option value="1">Achados & Perdidos</option>
        <option value="2">Anúncio de Imóveis</option>   
    </select>
    <br>
</form>
<br>    

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<script>
$("#sd_submit-job-form").change(function(event){
    event.preventDefault();
    $.ajax({
        data: $(this).serialize(),
        url: this.action,
        type: "POST",
        dataType: "html",
        success: function(data){
            //alert(data);   // retorna toda a página     
            var xxx = $(data).find("#principal");
            alert(xxx);     
            //$("#retorno").html(xxx);            
        },
        error: function(){
            alert("Problema ao carregar a solicitação via Ajax.");
        }
    });
});     
</script>   

<div id="principal">Eu preciso que retorne apenas esse elemento.</div>
<div id="retorno"></div>

1 answer

3


If #principal is a direct child element of body (seems to be the case), use .filter():

<body>
   <div id="principal"></div>
</body>

$(data).filter("#principal");

Otherwise use .find():

<body>
   <div>
      <div id="principal"></div>
   </div>
</body>

$(data).find("#principal");

That’s because $(data) will return a nodelist and the find will seek within these nodes the element #principal. If this element is the direct child of the body, it will be a main knot, and the find you won’t find him.

Already the filter will catch straight the main node that matches the selector.

Documentation of . filter()

  • The . filter did not work in my script. Do you have any other idea? I really need to resolve this issue.

  • The filter showed what in $(date)?

  • Returned [Object Object]. Just that. And with . find happens the same thing.

  • 1

    That’s correct. [Object Object] is the main div#. It’s a jQuery object. If you want to get the HTML from it: xxx.html()

  • Perfect!! It worked!! Thanks for the strength!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.