I was wondering how you guys do a page rebuild with php and jquery.
In my application i need to rebuild divs all the time.
So what i do is
-
sending a ajax call with get for example
person_controller.php?action=rebuild -
The controller makes a database query filling the fields of form.
-
Now the div has created for example
$div = '<table>
<tr>
<td>
<label id="' . $id . '">' . $id .'</label>
</td>
</tr>
</table>';
return $div; -
On the succes function of the ajax call i do this :
$('#Div').replaceWith(newdiv);
This works very fine, but i was wondering of this is the good method about rebuilding divs without page refresh.
Also in firebug you can see the whole div code within the get request.
Summarized: Is this a good way? Or need i to change my coding behaviour.
This method is perfectly fine. It can have drawbacks from a developer perspective: it’s more difficult to browse the ajax response in firebug if it’s HTML as opposed to just data, and it will limit the reuse of your server-side script since it will only ever return a HTML table where in another case you may want the same data but in a different format.
The alternative is to return just the data by itself in an array or object, and no HTML. Then you would construct the HTML on the client side. Typically people would do a database query for a row or an array of rows, then call
json_encodeto put it in JSON format, and then in the success callback of their javascript ajax call they would have a javascript object or array that they could pull the data out of ($id in your case) and generate the HTML.If you decide you want your ajax calls to transfer only data, and no HTML, then you may want to look into javascript templating. There are libraries such as Mustache that allow you to define templates and then pass the data from your AJAX call into the template and have it fill in placeholders. This is cleaner than concatenating strings together in Javascript.