Reputation: 1619
I am creating an application in opencart in which the controller returns output in json form. If i do $('.my-div').html(json['output'])
then its working fine. But how can i filter particular div
or table
from that response and put only that filtered html in my div. I know about $('.my-div').load('index.php?route=mymodule/subpage' .my-div > * );
But it doesn't work as my controller is created to return output not to generate.
What my controller returns is
$json['output'] = $this->load->view('default/template/mymodule/mytemplate.tpl', $data);
Edit
What i am getting in response is
json['output'] = '<div>......</div><table class="myclass"></table>';
I want to load only myclass
in my div. So how can i filter only myclass table
from response.? I've tried filter but its giving me error.
Upvotes: 0
Views: 576
Reputation: 26
Like Raghubendra said, it's better to only keep the html
you need in the .tpl
file, but if you can't do that for whatever reason, you can try to filter it on the server side using xPath [it's not the fastest way, but it's a clean way to get the result]. Here is how I think you can do it:
$output = $this->load->view('default/template/mymodule/mytemplate.tpl', $data);
$dom = new DOMDocument();
@$dom->loadHTML($output); // @ is to suppress all warnings related to the fact that html is not a proper dom document
$xpath = new DOMXPath($dom);
$match = $xpath->query('//table[@class="myclass"]');
/* $match is not an array, it implements 'Traversable', you can't access your <table> node using $match[0],
you need a foreach that will only loop once if you have one <table class="myclass"> element */
foreach($match as $table) {
$json['output'] = $table->ownerDocument->saveHTML($table); // saveHTML allows you to get the output in an HTML string
}
N.B: Please note that you need to change this code in case you have multiple <table class="myclass">
, I would recommend using iterator_to_array($match);
to transform the node list to an array so you can access it using $match[0]...
and avoid the foreach
.
Upvotes: 1
Reputation: 2769
If you want only a part of the html in your div then why are you rendering the whole tpl file. Why don't you remove the html code that you don't want to use.
Suppose if your mytemplate.tpl has
<div>
---------
--------
</div>
<table class="myclass"></table>
<div>
---------
--------
</div>
Then why don't you only keep the table code are remove all the other code as you are not using it while rendering the tpl file.
Upvotes: 0