Taking data via ajax

Asked

Viewed 791 times

1

I need to get content from a div. I’m actually building a dynamic menu, where I define

<li class="menuLi">
  <div class="acao">-3</div>
  <div class="desc">Inicio</div>
</li>

Then I have an ajax that should take this acao and send to a page to know which page to load. However when caught this action is not coming, the attribute comes as undefined.

The js code.

function carregarPaginas() {
    $(".menuLi").click(function (e) {
        e.preventDefault();
        var acao = $(this).attr('href');
        location.href = 'includes/publicacao.php?c='+acao;
    });
} 
  • 1

    $(this).attr('href') would work if your LI was an A and had an attribute href...

  • how then ?

  • 1

    Dude, strange this menu... <br> exchange: var acao = $(this). attr('href');<br> por: var acao = $(this). find('.acao'). html(); Ps.: $(".menuLi").click... needs to be right inside a function? Abs

  • no, I need that when you click either the menu or the sub menu it pulls the page that comes with the code in action. would have to formulate a response ?

4 answers

4


You are not using link on yourself <li>, so it’s impossible to get the attribute href.

  1. It is recommended that you assign the event click at the .menuLi in the ready of the document.
  2. For registering a bind, it should not be inside a function, since the function will "bindar" several times the same event, so, nay place the bind of click class .menuLi within a function and yes ready of the document.

Completion

Your HTML

<li class="menuLi">
  <div class="acao">-3</div>
  <div class="desc">Inicio</div>
</li>

The correct Javascript:

$(document).ready(function() {
      $(".menuLi").click(function (e) {
        e.preventDefault();

        var acao = $(this).children('.acao').html();
        location.href = 'includes/publicacao.php?c='+acao;
    });
});

JSFIDDLE

  • However and when I have a sub menu this your code does not work. How to adapt it to such done.

  • @Renanrodrigues, I only indicated that way because it was the initial model that passed, but tell me, what do you think of assigning the click event to div acao? Or it needs to be in the ,menuLi Really? If I need to I adjust to how you need to.

1

$("#menu li a").click(function() {
  var resposta = $(this).attr('href');
  alert(resposta);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<ul id="menu">
  <li><a href="login.html"> Login</a>
  </li>
  <li><a href="menu.html"> Menu</a>
  </li>
</ul>

0

If your intention was to take the action set in the first internal div of the selected menu, then just replace the snippet var acao = $(this).attr('href'); for

var acao = $(this).find(".acao").text();

0

Whoa, try this on:

var acao = $(".acao").html();

Browser other questions tagged

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