Reputation: 11157
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);
}
});
Upvotes: 2
Views: 5551
Reputation: 7388
There are a couple of options for you:
If you change your dataType
attribute to dataType: '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 is FALSE
. If you pass TRUE
, the $this->load->view()
function returns data instead of echoing it to the browser.
What you can do is:
$response = $this->load->view("your_ajax_view", $data, TRUE);
//do anything you would need to with the response.
echo $response;
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.
Upvotes: 4
Reputation: 10077
basically, if you want to do that, you will just take care of it in the profile/setting controller. then at the end of the controller load your view. then change your ajax function to just do the html as the data that is returned. Something like this:
AJAX part:
$.ajax({
type: "POST",
url: baseUrl + "profile/setting",
success: function(data){
$('#result_column').html(data);
}
});
controller:
function setting()
{
//whatever your code is, but then just pass the json
//data you were echoing before to the view file
$data['json_stuff'] = '';//however you generat this
$this->load->view('some view file', $data);
return;
}
Upvotes: 2