alexandercannon
alexandercannon

Reputation: 544

JQuery Post to php with dynamicaly created IDs

I am trying to create a method that posts data to mysql when called. The only problem is I can't figure out how to pass it the correct information from the fields as their IDs are created at runtime.

The fields are created using a while loop and on double click they become editable then on blur they are supposed to revert to their previous state and post any changes made to the database. (this is my first time writing one of these I hope I'm clear!)

My JS

function disablefarm(farmid) {
  $(function() {
    var farmstr = farmid.replace(/[^0-9\.]+/g, ""),
      farmID = $("#farm" + farmstr + "").val(),
      farmName = $("#farmn" + farmstr + "").val(),
      fieldarray = $([]).add(farmName).add(farmID);
    $("input:text[id=" + farmid + "]").attr('readonly', 'readonly');
    $("input:text[id=" + farmid + "]").addClass("noshow");
    var epost_url = "editfarm.php";
    var epost_data = fieldarray.serialize();
    $.post(epost_url, epost_data, function(response) {
      alert(response);
    });
  });
}

The html elements are created in a while loop that outputs

echo "<td name='farmL' ><input type='hidden' value='$id' id='farm$id' />   <input type='text' id='farmn$id' value='$fname' readonly='readonly' class='noshow' size='33' ondblclick='enablefarm(this.id)' onblur='disablefarm(this.id)' />";

And finally editfarm.php looks like

if (filled_out($_POST)){
    $efarmID = check_input  ($_POST['farmID']);
    $efarmName = check_input  ($_POST['farmName']);
}
else{           
    echo "not committed";       
}

$query = "UPDATE farm_name
          SET farmName='".$efarmName."' 
          WHERE farmID=".$efarmID.";";
$result = mysql_query($query);
if(!$result)
{   
    echo"".stripslashes($efarmName)." not updated";}
else{
    echo"".stripslashes($efarmName)." updated"; 
}

The HTML output looks like this

<tr id='row27'>
    <td name='farmL'>
        <input type='hidden' value='27' id='farmid27' />
        <input type='text'
               id='farmn27'
               value='111 Gary farms'
               readonly='readonly'
               class='noshow'
               size='33'
               ondblclick='enablefarm(this.id)'
               onblur='disablefarm(this.id)' />
    </td>
</tr>

Thanks!

Upvotes: 0

Views: 130

Answers (2)

Aakash Sahai
Aakash Sahai

Reputation: 4004

Reducing js to minimum, I would have done this by introducing an extra attribute to your dynamically generating inputs.

<td><input type="text" data-id="27" name="farmid27" value="111 Gary Farms" class="farmEdit" /></td>

Now simply update your js to:

$(document).on("blur", "input.farmEdit", function() {                
            $.post("editfarm.php",    
            {
                farmID : $(this).attr('data-id'),
                farmName : $(this).val()
            },
            function(response) {
                alert(response);
            });
    });

Here you can see the 'data-id' attribute removed the dependency on input name, and I would suggest why to introduce input name when you are posting it individually using ajax(atleast for these types of cases).

Upvotes: 1

FixMaker
FixMaker

Reputation: 3877

You may find it easier if you refactor your code somewhat. If you modify your PHP code to output the table content to look something like this:

<td>
    <input type="text"
           name="farmid27"
           value="111 Gary Farms"
           class="farmEdit" />
</td>

(The indentation is just to make it readable.)

Then you can rewrite your JavaScript to something like:

$(document).ready(function() {
    $(document).on("blur", "input.farmEdit", function() {
        var $inputElement = $(this),
            inputName = $inputElement.attr("name"),
            inputValue = $inputElement.attr("value")
            curFarmId = inputName.substr(6); // Strip off the "farmid.." prefix

        $.post(
            "editfarm.php",
            {
                farmID : curFarmId,
                farmName : inputValue
            },
            function(response) {
                alert(response);
            });
    });
});

This takes advantage of jQuery delegated events and the fact that the this object in a click handler refers to the page element that was clicked (the <input> in this case).

Upvotes: 1

Related Questions