I'm developing an application which relies heavily on jQuery for user interaction.
(and if you're browser doesn't support jQuery, then upgrade or don't use my application :)
As normal, one have functions to GET, SET and DELETE data from a table.
In my application, I'm GET'ing and SET'ing a lot of information without page reload. To do this, I mostly use jQuery.post.
A typical code in my JS file looks like this:
jQuery.post("mypath/jquery_getset_data.php", { instance: 'getItems_A', itemID: itemID_value},
function(data) {
populateItemList(data);
});
The jquery_getset_data.php contains of many if statements:
if($_POST['instance'] == 'getItems_A'){
// PHP code to get and process data from MySQL DB
}
if($_POST['instance'] == 'setItems_A'){
// PHP code to process and insert data to MySQL DB
}
Here's my question:
Is tehre a better way for interaction between JS file and jquery_getset_data.php?
How can I dynamically call different "remove item" functions inside createStoreList? See update 1.
Update 1: This is the code that I use to create many different lists.
function createStoreList(data)
{
var ul = jQuery("<ul/>");
// We need to build the html structure in order for this to be registered in DOM.
// If we don't, jQuery events like .click, .change etc. will not work.
for (var i = 0; i < data.length; i++)
{
ul.append(
jQuery("<li/>")
.attr("id", "listItem_"+data[i].id)
.append(jQuery("<span/>")
.addClass("btnRemoveItem")
.attr("title", "Remove store from list")
.attr("id", data[i].id)
.click(function() { removeItemA(this); })
)
.append(data[i].name + ', ' + data[i].street)
);
}
return ul;
}
Update 2 I figured I just could use switch statements. I've tested it and it works.
.click(function() {
switch(instance)
{
case 'removeListItemA': removeListItemA(this); break;
case 'removeListItemA': removeListItemB(this); break;
case 'removeListItemA': removeListItemC(this); break;
}
})
The only thing I would change is in
jquery_getset_data.php
I would use a switch statement instead of many if statements. jQuery's $.post method is fine for what you're doing, talking to a script that affects the database (deletes/updates/etc) using one of the GET ajax methods ($.load or $.get) breaks the HTTP specification.In order to reduce the jquery_getset_data.php I would use the OOP design patterns to avoid switches and if statements.
and then:
I know looks complicated, but for my taste looks much better. And regarding your second question I'm not sure I understood it, can you add more explanation?
After I saw you update, I think for second question you can do:
There the "instance" is the function name, or you can update or append it latter to make it be the function name;