0

I need some advice on how to successfully update mutiple rows in my database from dynamically created input fields.

So, what I have is this:

PHP

<?php
   while ($row = mysql_fetch_array($sql)) {
       echo "<input class='estemated_days' type='text' id='".$row['scpe_id']."' value='".$row['scpe_estemated_days']."'></td>";
   }
?>

This will output something like this:

HTML

<input class='estemated_days' type='text' id='718' value='5'>
<input class='estemated_days' type='text' id='719' value='8'>
<input class='estemated_days' type='text' id='720' value='10'>

<input type='button' id='save' value='Save'> <!-- Button to jQuery -->

.....etc.

Here is where my knowledge is lacking. I want jQuery to do something like this:

jQuery

($"#save").click(function () {

  // Get value of id from (".estemated_days") as an identifier, and get the input value it contains
  // Send to /update.php

});

Then, the update.php would do something like this:

PHP

<?php

if (isset($_POST['save'])) {

    /*
        Get all of the id's and the value it contain's

        perform:
    */

    mysql_query = ("UPDATE myDatabase SET estemated_days = '$the_value_from_the_input' WHERE scpe_id = '$the_value_of_the_id'");
    //Repeat this for all rows from the webpage
}

?>

My knowledge is basic web programming but I would really like to make this work. Anyone got advice on how I should do it?

2
  • <input> tags don't have a data-id attribute. Why not use id? Commented Jun 18, 2012 at 23:22
  • @Mike oh, i did not know that. Yeah, I guess ID would work. I'll edit this in my post. Commented Jun 18, 2012 at 23:25

1 Answer 1

1
var values = {};
$('input.estimated_days').each(function(n, el){
   values[ $(el).attr('id') ] = $(el).val();
});

$.ajax(
  {
    type : 'POST',
    url : 'update.php',
    data : {edays: values}
  }
); /// see jquery docs for ajax callbacks 

<?php
   foreach($_POST['edays'] as $id=>$value) // ...

http://api.jquery.com/jQuery.ajax/ also http://api.jquery.com/attr/

... and don't forget to sanitize the input for mysql

Sign up to request clarification or add additional context in comments.

3 Comments

Thank's! I will try this out asap.
thank you. Do you have any idea on why this code wont update my database? See pastebin link: pastebin.com/p8ks686W I noticed now I didn't end with a semicolon but this is added now and still no luck.
Define yourself a success callback in jquery ajax that alerts you to the output: success : function(data){ alert(data); } - you can then var_dump $_POST or dump mysql last error and get that output in a popup. See the jquery ajax link to learn about callbacks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.