Brandon Brandon - 1 month ago 4
jQuery Question

ajax POST trouble passing variable

I am having issues passing a variable through aJax POST. When I remove the 4th line of data (

old
) everything works perfectly. I am trying to pass the value of the
<td>
being edited before it is edited along with after. Content is the value after the edit, so after the table
<td>
is selected but before it becomes editable content I grab the value of the cell.

This is what I am trying to pass through with the variable '
old
'.

$('td').click(function(){

var old=$(this).text();

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

});

$('td').on('input',function() {
console.log('event');
$.ajax({
method: "POST",
url: "updatedatabase.php",
data: {
content: $(this).text(),
date: $(this).siblings().first().text(),
prod: $('tr:first-child th:nth-child(' + ($(this).index() + 1) + ')').text(),
old
}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});

});

Answer

You could pass three types to data Type: PlainObject or String or Array (as mentioned in jQuery.ajax() documentation) and since you're passing an object you can't just put a variable old inside an object, you should pass name and value like name: value,name: value,..., so it should be like old: old :

var old=""; //--->Define variable

$('td').click(function(){
    old=$(this).text(); //--->Set variable
    $(this).prop('contenteditable', true);
});

$('td').on('input',function() {
    ...

    data: { 
        content: $(this).text(), 
        date: $(this).siblings().first().text(),
        prod: $('tr:first-child th:nth-child(' + ($(this).index() + 1) + ')').text(),
        old: old //--->Get variable
    }

    ...
});

Take a look to Working with objects documentation.

NOTE : You have to declare you variable old globaly so it will defined inside the both events click and input.

Hope this helps.


var old="";
var show_notification = false;

$('td').click(function(){
  show_notification = true;
  old=$(this).text();

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

$('td').on('input',function() {
  if(show_notification===true){
    toastr.info(old,'Old text',{"timeOut": 2000});
    show_notification = false;
  }


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" rel="stylesheet"/>
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>

<table border=1>
  <tr>
    <td>first td</td>
  </tr>
  <tr>
    <td>second</td>
  </tr>
  <tr>
    <td>third</td>
  </tr>
</table>

Comments