Daniele
Daniele

Reputation: 847

jquery load() and append

silly quick question:

I have my:

$('#result').load('ajax/test.html');

but what if I don't want to insert my loaded content into #result, but prepend it to #result, maintaining all precedent elements? Is it possible to create a variable, load it with content and then append or prepend it to my #result? I imagine some other scenarios where with my brand new variable I can manipulate it before inserting it into the DOM.

Upvotes: 33

Views: 68519

Answers (5)

Aleja_Vigo
Aleja_Vigo

Reputation: 980

var response;
$.ajax({ type: "GET",   
     url: "ajax/test.html",   
     async: false,
     success : function(text)
     {
         response= text;
     }
});
$('#result').prepend('<div>'+response+'</div>');

You need "async: false" so you WAIT for the response. If you dont wait for it (normal Ajax asynchronous call) you will have an undefined variable for an unknown time, so it could be dangerous.

EDIT: As the comments rightly say, using "async:false" is not usual and is ugly. Normally you would manipulate the response and insert it in the DOM inside the success callback. The use of the async only would be required if you really need the response in a variable waiting for another thing to use that variable, not a common thing to happen.

$.ajax({ type: "GET",   
     url: "ajax/test.html",   
     success : function(text)
     {
         $('#result').prepend('<div>'+text+'</div>');
     }
});

Upvotes: 27

M&#225;rcio SULZBACH
M&#225;rcio SULZBACH

Reputation: 61

I think this is a shorter soluction

$.get("ajax/test.html",function (dados) { $("#result").append(dados);});

Upvotes: 6

Shyju
Shyju

Reputation: 218882

Do a jQuery post and load the data to a vaiable and prepend to the desired div

$.post('ajax/test.html', function(data) {
  $('#result').prepend(data);  
});

Upvotes: 7

Sven Bieder
Sven Bieder

Reputation: 5681

You mean something like this?

var content;
$.get('ajax/test.html', function(data){
    content= data;
    $('#result').prepend(content);
});

That saves your loaded content into a variable first and you can manipulate it however you want.

Upvotes: 35

Ry-
Ry-

Reputation: 225164

A quick way might be:

$('#result').append($('<div>').load('ajax/test.html'));

Upvotes: 31

Related Questions