Im making a 100% javascript and canvas web application, no forms at all. I have a js array with data and I'm wondering how could be possible to pass it to a php script so it gets loaded into the database. Suggestions?
3 Answers
My thoughts are to keep it simple. If you are looking to store arrays based on value/pair, ie a flat file and no relationships between tables, then I would do the following:
Create a mysql database with one table, two rows:
CREATE TABLE `data` (
`data_id` INT(10) NULL,
`data_key` CHAR(50) NULL,
`data_value` TEXT NULL,
`datemodified` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`datecreated` DATETIME NULL,
PRIMARY KEY (`data_id`),
UNIQUE INDEX `data_key` (`data_key`)
)
COLLATE='latin1_swedish_ci'
ENGINE=MyISAM
ROW_FORMAT=DEFAULT
Anyway create a PHP script that will take a post of 2 variables, a key (a key), and value (this would be an object in javascript).
If you post a key, it should return the value (in the json format so javascript can interpret it into an object)
If you post a key and a value, the script will do an "Insert Ignore" and return the data_id. Run the value through json_encode() (as it will be if posted through javascript) and store it under the key.
You could also make an optional third way of accessing the data using the data_id value.
Just a thought... let us know how much php experience you have and if you need specific details on what functions to use
Security would also be a factor to consider. In this case, you might want to have javascript generate a unique session id, and then add this session_id to the table. So users can only access their own data. Not really sure how your app works at this stage though so sorry I can't suggest something more secure.
-
Not selected as the answer, but gave you a point for the explanation and the tips.Gabriel– Gabriel12/13/2010 15:54:07Commented Dec 13, 2010 at 15:54
create a webservice in php that can connect to mysql db. Your js code would make calls to these webservices to save to db
-
Any code example about making the call with no forms where to get the data from?Gabriel– Gabriel12/13/2010 04:43:49Commented Dec 13, 2010 at 4:43
-
1
jQuery.post(url, data);
where data is your JavaScript array. api.jquery.com/jQuery.postDan Grossman– Dan Grossman12/13/2010 05:28:11Commented Dec 13, 2010 at 5:28
You can send it as a JSON string to a PHP file using AJAX and then decode the JSON, inserting the data into the database. You should have the PHP file return something to make sure it's done.