Chris Chris - 5 months ago 10
jQuery Question

Find and replace a string in JQuery

I have the following problem. I would like to find and replace a specific string which I'm getting through AJAX.

Code:

JQuery:

if(!countflag) {
$('.panel-body > p').each(function() {
var content = $(this).find("span").html();

$.ajax({
url: '/vacatures.php',
data: {company: content},
type: 'post',
success: function(output) {

var text = $(this).find("span").text();
$(this).text(text.replace(content, output));

}
});


if(content) {
countflag = true;
}
});
}


In the HTML the company ID (for example
c88
) is shown. This needs to be found and replaced by the actual name of the company.

The ID is inside
span
tags. I thought it would make it easier to find and replace the ID.

The AJAX sends a call to
vacatures.php
which sends back the name of the company that corresponds to the ID shown in
.panel-body > p
.

At this point I'm stuck on how to successfully find and replace the ID by the company name.

UPDATE (The HTML Code - partially):

HTML Code

Answer

You are having a closure issue... the this inside the success callback is different from the this of the each callback... you need to have a look on how closures work in javascript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

by the way, in order to have a fast fix you need to save the first this reference:

$('.panel-body > p').each(function() {
  // keep a memory reference of this
  var self = this;
  var item = $(self);
  var content = item.find("span").html();

  $.ajax({ 
    url: '/vacatures.php',
    data: {company: content},
    type: 'post',
    success: function(output) {
      
      var text = item.find("span").text();
      
      // the following expression cannot work because text isn't defined
      item.text(text.replace(content, output));

    }
  });

});

notes: the variable text seems to be not defined; generally that code needs a refactoring.

Comments