5

I would like to refresh a partial view using ajax. I kwow how to append the new data to the HTML, but I would like to know if there is a simpler way to do it.

I have partial view that does this

  • each x in data li x.name

I pass the data using !=partial('test',{data:data})

I want to call a function to render the partial view again without reloading the page.. and without doing append( ... ); Any Idea?? Or other way to do it...

Mark Achée
  • 517
  • 1
  • 4
  • 14
JJS
  • 51
  • 1
  • 1
  • 2

2 Answers2

20

First, add a route for just the partial like

app.get('/mypartial', function (req, res) {
    //compute data here
    res.render('mypartial', {layout: false, data: data});
});

Then load the new HTML with a jQuery .get or .ajax call to /mypartial.

Then use jQuery to replace the HTML of the parent element by doing

$('#idofparentelementofyourpartial').html(responseHTML);

See also my answer to this similar question.

Community
  • 1
  • 1
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • what if u need to run a JS function before sticking it to _idofparentelementofyourpartial_. My contructed ejs has a
    some content
    – vardha Sep 23 '16 at 14:23
  • @PeterLyons please excuse me tagging you here but you seem like you may be able to help with an issue i am having with partials and ajax, would you be so kind as to take a look at https://stackoverflow.com/questions/50354062/update-div-via-ajax-with-ejs-partial-express please – Richlewis May 15 '18 at 22:05
-2

Use it You may get good solution

function ajaxRequest(url, succesCallBck, completeCallBck, errorCallBck)<br>
{
$.ajax({url: url
type: "POST",
dataType: "json",
complete: completeCallBck,
success: succesCallBck,
error: errorCallBck

});
}
ozer
  • 335
  • 1
  • 5
  • 13
pkp
  • 300
  • 3
  • 7