Skip to content Skip to sidebar Skip to footer

Saving Appended Elements To Database

I've made a very simple shopping list with jquery here is the code: $(document).ready(function(){ $('.project-btn').click(function(e){ e.preventDefault(); var project = $('.projec

Solution 1:

$(document).ready(function(){
$('.project-btn').click(function(e){
e.preventDefault();

var project = $('.project-val').val();

$('<li></li>').addClass(project).text(project).appendTo('.project-list');

var elem={};
elem.str='<li class="'+project+'">'+project+'</li>';

$.ajax({

 url: 'path/to/your/phpscript.php',
 data: elem,
 type: 'POST',
 success: function(response)
 {
   //do whatever you like
 }

 })//end of ajax call

});
});

phpscript.php

<?php

define('DB_NAME', 'your schema/database name');
define('DB_USER', 'your db user name');
define('DB_PASSWORD','password');
define('DB_HOST', 'localhost');

$link=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);

if(!$link)
{
 die('Could not connect: '.mysqli_error());
}

  $db_selected= mysqli_select_db($link,DB_NAME);

if(!$db_selected)
{
  die('Cant use : '.mysqli_error());
}

 $sql="insert into yourtable values('$_POST[str]')";

 mysqli_query($link,$sql);

 mysqli_close($link);

  ?>

Solution 2:

You can have a table in database called Project. Every time you append things in your project-list also send with Ajax the details of the "project" to your database.

Then everytime your page loads make an Ajax request to your server and get the rows of Project table. Then you could use jQuery .each (http://api.jquery.com/jQuery.each/) and build your DOM so whoever and whenever someone opens your website it will be updated.

Hope it helps!

Solution 3:

Storing the complete HTML for something as trivial, and easy to accomplish might not really be a good idea.

What I would do is, store all the projects in the 'project-list' to a sql db, and then populate the list reading the values from the db. When you click a button, you could insert a new value in the db, via Ajax, then depending on the returned value, determine whether the insert was successful or not, and then create the element on the client side. Other users, who use the page, will anyway read the list from the table to populate their version of the lists, so it will get updated for their end too.

Post a Comment for "Saving Appended Elements To Database"