Best practice to handle ajax jquery database queries?
I have a "little" problem because I don't know whats the best way to handle ajax jquery database request?
So far I've done it this way: For ever (single) database request I created a new .php file like:
newbill.php
newcosumer.php
listallbills.php
u开发者_StackOverflowpdatecostumer.php
..and so on and pull the data via:
$.ajax({
type: "POST",
url: "ajax/newbill.php",
data: "..."
success: function(msg){
...
}
});
..what I don't like is all the .php files for only ONE! database request!?
There must be a better way to handle this??I would do it in this way.
Create a php file for each entity (Ex : consumerajax.php , billajax.php,etc...) then have seperate functions for each of your database queries.When calling from the javascript pass a querystring variable to determine which function to be executed in the ajax server page
Ex : In consumerajax.php
<?php
$mode= $_GET["mode"] ;
if($mode=="getconsumerdet")
{
$consumerId=$_GET["cid"];
GetConsumerDetails($consumerId)
}
else if($mode=="updateconsumer")
{
$consumerId=$_GET["cid"];
$name=$_GET["name"];
UpdateConsumerInfo($consumerId, $name)
}
function GetConsumerDetails($consumerId)
{
// execute query the table here and return the result from here
echo"Have the data and return"
}
function UpdateConsumerInfo($consumerId,$name)
{
//execute query to update
echo "updated";
}
?>
and from your scrip call like
$.ajax({ type: "POST", url: "ajax/consumerajax.php?mode=getconsumerdet&cid=34", data: "..." success: function(msg){ });
or
$.ajax({ type: "POST", url: "ajax/consumerajax.php?mode=updateconsumer&cid=34&name=shyju", data: "..." success: function(msg){ });
You could create a single file called ie. dbrequest.php
and pass it parameters, that you then read from php and make the appropriate request to the database..
But it would depend on what exactly you are doing inside your pages, and if it is easy to maintain in a single file..
精彩评论