I have following ajax call and response with json data type. Currently I write the data and html tag directly in js but I think this is not good and hard to read. How can I pass them in Codeigniter view?
$.ajax({
type: "POST",
url: baseUrl + "profile/setting",
dataType: 'json',
success: function(data){
var html = "";
html += "<div>";
html += "<img src=\"" + baseUrl + data.picture + "\" />";
html += "<div>" + data.email + "</div>";
html += "<div>" + data.first_name + " " + data.last_name + "</div>";
html += "<div>" + data.address + "</div>";
html += "<div><input type=\"text\" class=\"input_text_top\"/></div>";
html += "<div><input type=\"text\" class=\"input_text_middle\"/></div>";
html += "<div><input type=\"text\" class=\"input_text_bottom\"/></div>";
html += "<div><input type=\"submit\" class=\"btn btn_grey\"/></div>";
html += "</div>";
$('#result_column').removeAttr('style').html(data);
}
});
There are a couple of options for you:
1. Generate the HTML from a CodeIgniter View:
If you change your
dataTypeattribute todataType: 'html'you can have the server return a string of html which you can immediately inject into your#result_column.CodeIgniter’s
$this->load->view()comes with a third boolean parameter. It’s default isFALSE. If you passTRUE, the$this->load->view()function returns data instead of echoing it to the browser.What you can do is:
2. Use a templating system
Like Mustache, Handlebars, EJS or Underscore to inject your returned json data into a custom template. This has the advantage of saving bandwidth because you only transfer the markup once (on initial page load) and from that point forward transfer data only.