简体   繁体   中英

Can't get value of element in my success function using ajax ?

so I am having a problem i dont know how to solve it, I spent hours just trying to find a way to get my value of my element.

Here is my code (jsp) :

<div class="aimerSection">
     <div class="aime">
     <form>
     <input type="hidden" class="adore1" name="aime" value="${post.id}">
     <input type="button" class="adore2" value="J'aime">
     </form>
     </div>
     <c:if test="${ post.adore == 0 || post.adore == 1 }">
     <div class="nbreAimes"><p><span class="nbrAdore">${ post.adore }</span> personne aime ça</p></div>
     </c:if>

     <c:if test="${ post.adore != 0 && post.adore != 1 }">
     <div class="nbreAimes"><p><span class="nbrAdore">${ post.adore }</span> personnes aiment ça</p></div>
     </c:if>

</div>

What i want to achieve is to get the value of my 'p' in the div with 'nbreAimes' when i click my button ( input type button ) so that's my jquery file :

$(document).ready(function(){
$(".adore2").click(function(){
    var aime = $(this).parent().find(".adore1").val()
    var value = $(this).parent().parent().siblings().find(".nbrAdore").text()
    alert(value)

    console.log("value : "+$(this).parent().parent().siblings().find("p").text());
    $.ajax({
        type:"POST",
        data: {aime:aime},
        url:"acceuilServlet",
        success:function(result){

            console.log("in functions : "+$(this).parent().parent().siblings().find("p").text());
        }
    })

})
})

But the problem is that I am getting the value correctly, but inside the function of ajax ( success : function ) i copied exactly the same code and I get nothing ..

in my console I see :

value : 1 personne aime ça 
in functions : 

i get Nothing.

Hope I am going to find some help. Thank you.

The $(this) inside AJAX is different from the one outside. Try to save your value in another variable outside the AJAX call for later usage inside AJAX.

$(document).ready(function(){
$(".adore2").click(function(){
    var aime = $(this).parent().find(".adore1").val()
    var value = $(this).parent().parent().siblings().find(".nbrAdore").text()
    alert(value)

    console.log("value : "+$(this).parent().parent().siblings().find("p").text());

    var pText = $(this).parent().parent().siblings().find("p").text()

    $.ajax({
        type:"POST",
        data: {aime:aime},
        url:"acceuilServlet",
        success:function(result){

            console.log("in functions : "+pText);
        }
    })

})
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM