0

I'm pretty new to jQuery and am stuck with a particular issue.

So I've written a script to change the text value of spans on a page. e.g. <span class='xxx'>Iamstuck</span> using a php db querying script, triggered when a user mouseenters one of the spans (which works).

Thing is, after the sentence is updated and I attempt to call $(this).text(), it returns me the original text rather than the updated text. How can I get hold of either the updated text?

$('span.xxx').mouseenter(function(){
    var selected = $(this).text();
    var $this = $(this);
    $.get("search.php",
         {term: selected},
         function( data ) {
             $this.text(data);  // this line updates the span text
         });
    var lookup = $(this).text(); // this line returns me the original text instead of the updated text
    console.log("lookup: " + lookup);  // just for debugging
});

Thanks in advance!

Reuben L.
  • 2,806
  • 2
  • 29
  • 45

1 Answers1

1

That is because it is AJAX!!!

Do everything inside the complete callback:

$.get("search.php", {
        term: selected
    },
    function(data) {
        $this.text(data); // this line updates the span text
        var lookup = $this.text();
        console.log("lookup: " + lookup); // just for debugging
    })
});
Amit Joki
  • 58,320
  • 7
  • 77
  • 95