Ahmed Mujtaba
Ahmed Mujtaba

Reputation: 2248

Changing the body of html with jQuery

I'm making an Ajax call which returns html body. I'm trying to change the html of the child element by following code:

(function inbox() {
    $.ajax({
        url: 'http://localhost:5958/myaccount/inbox/',
        success: function (data) {
            var x = $(data).find("#refresh")[0];
            $(x).html("f");
            console.log($(x).html())
            //console.log($(data).find("#refresh")[0]);
        }
    });
});

How do I change the body of the element "refresh"? I'm a beginner with jQuery and I'm stuck here. Any help will be appreciated.

Upvotes: 1

Views: 145

Answers (3)

Akhil Menon
Akhil Menon

Reputation: 306

Make a blank div in the body like <div id="result"></div>

Then in success of the ajax :

success : function(data){

      value = data.value; // get whatever value you want from data

      $("#result").html(value);

      } 

Upvotes: 0

Digpal Singh
Digpal Singh

Reputation: 166

Please try this below code

success: function (data) {
$("#refresh").html(data); }

or

success: function (data) {
$('body').find("#refresh").html(data);}

Upvotes: 3

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

Just you need

success: function (data) {
    $("#refresh").html(data);
}

This code will change element with id refresh with returned data

About your code let me explain some things in your code

$(data).find("#refresh")[0]; // I really don't know why you use [0] here

that mean data returned html with element has id refresh .. so data looks like

<div>
   <div></div>
   <div id="refresh">
       refresh data here
   </div>
</div>

so your code in success

var x = $(data).find("#refresh");

x will return an object

x = '<div id="refresh">refresh data here</div>';

and after that you used

$(x).html("f");

that mean you change x again to be

x = '<div id="refresh">f</div>';

so after you use

console.log($(x).html());

it will return f and this is right

but all your code not appended anything to your html page yet so you should use

$("body").html(x); // this will change body html to f

Upvotes: 0

Related Questions