Brandon Brandon - 5 months ago 19
HTML Question

Issue passing value through ajax

I have a HTML table on my website where I click on a cell and then am able to edit it. I am now trying to push the edited value back to my database by using ajax. I have tested the click to work properly, the content editable to work properly and that ajax is sending to the correct URL by using a simple "hello" on updatedatabase.php and seeing it return through the alert. When I try to pull the data from ajax to updateddatabase.php is where I am having problems. I believe that maybe $(this).val() may not be what I want to get the contents of the cell that I just edited with contenteditable? The reason I say this is because it looks like a blank value is being passed through to the second page. Here is a chunk of my code for the click / content editable /ajax on the main page:


var val=($(this).siblings().first().text());

var col = $(this).parent().children().index($(this));

$(this).prop('contenteditable', true);

//var row = $(this).parent().parent().children().index($(this).parent());

//alert('Date: ' + val + ', Column: ' + col);

$(this).bind('input propertychange', function() {

//On key stroke

method: "POST",
url: "updatedatabase.php",
data: { content: $(this).val() }
.done(function( msg ) {
alert( "Data Saved: " + msg );


and here is what I have sitting on updatedatabase.php. I kept it simple just to test the value passing through for now.

if(array_key_exists("content", $_POST)) {

echo $_POST['content'];


Hopefully this is an easy fix as I believe it all may just be with $(this).val() but I am not sure what I should change it to? Thanks for the help!!


Part of the problem is that you're not actually capturing the value of the table cell to be edited. Using a new version of jQuery in my sample code I have replaced your bind() with keyup() as there should not need to be any delegation:

$('td').click(function() {
   $(this).prop('contenteditable', true);

   $(this).keyup(function() { // get the new value as soon as the key is released



As mentioned in comments by @adeneo, table cells have no value property which you can get with val(). In my example I have used $(this).html() to get the text inside the changed <td>, but you could also use .text().

You should change data: { content: $(this).val() } to data: { content: $(this).html() } or data: { content: $(this).text() } in order to send a variable value in your AJAX. Now if you watch the console you'll see something posted and something returned.