0

I have the following code, and it is not intuitive to me how I can append the Date to the front end of the newly entered data.

Basically I have a text field that allows editing of the data within. It initially pulls the oldVal from a database, shows it in the td and allows a user to update/edit/add to it. When focus leaves that textarea this method is called and then a php file is called to write to the database.

Here is the td:

<td class="editable-col" contenteditable="true" col-index='4' oldVal ="<?php echo nl2br($res2['status']); ?>"><?php echo nl2br($res2['status']); ?></td>

Here is the javascript method called on 'focusout':

<script type="text/javascript">
$(document).ready(function(){
    $('td.editable-col').on('focusout', function() {
        data = {};
        data['val'] = $(this).html().replace(/\r?\n/g, '<br />');
        data['id'] = $(this).parent('tr').attr('data-row-id');
        data['index'] = $(this).attr('col-index');
        if($(this).attr('oldVal') === data['val'])
            return false;

        $.ajax({   

              type: "POST",  
              url: "updater_1.php",  
              cache:false,  
              data: data,
              dataType: "json",       

        });
    });
});
</script>

I want to append " March 21, 2017 - " to the front of the new data entered.

I would add "and yet another update here"

So the td ends up looking like this:

March 13, 2017 - Update on cuz blah blah blah
March 19, 2017 - Another update here
March 21, 2017 - and yet another update here

Any suggestions ? I tried to handle it in the updater_1.php file but after many hours it is not as easy as I thought.

Thanks for any and all suggestions.

Image added:
enter image description here

Another:
enter image description here

New code test:

$(document).ready(function(){
  $('td.editable-col').on('focusout', function() {
    data = {};
    data['val'] = getDate() + $(this).html().replace(/\r?\n/g, '<br />');
    data['id'] = $(this).parent('tr').attr('data-row-id');
    data['index'] = $(this).attr('col-index');

$.ajax({   

      type: "POST",  
      url: "updater_1.php",  
      cache:false,  
      data: data,
      dataType: "json",       

    });
  });
});
Vacek
  • 179
  • 1
  • 12
  • Do you want to do that at the client or server? Probably a duplicate of [*Where can I find documentation on formatting a date in JavaScript?*](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – RobG Mar 23 '17 at 00:43
  • I dont see any code in the AJAX call to capture and process any returned data from the PHP call??? – RiggsFolly Mar 23 '17 at 00:51
  • This functions just fine ... it is posting "data" to the php page and process' it fine. – Vacek Mar 23 '17 at 00:52

2 Answers2

0

For the starter, you can use date("F j,Y") to return the date in Month date, Year format: So, here's the algorithm to consider on updater_1.php script:

Step1: Get the posted values and sanitize them.

Step2: Get the last part of the string after <br /> in $_POST['data']['values'] ( based on your JS logic and assuming your last line is the newly added string here)

Step3: add today's date in required format to the last part of the string (newly added data)

Step4: fetch the old data from database. this step is important because we don't trust the data user entered He might have fiddled the dates of previously added data

step5: append the data in step 3 to the data in step 4 (ie, oldData + 'br /'+ date + newData)

step6: write this data to the database

step7: if everything goes well and good return this newly written data to front end

To do the above your php script should be doing something like:

 // When you've the post
 $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
 //whatever is present in the text box
 $userData = explode("<br />",$_POST['data']['value']);
 //newly entered line/ data and current data
 $todayDate = date("F j,Y")
 $newDataToSaveWithDate =  $todayDate." - ".$dataToSave[count($dataToSave)-1]; 
 //fetech the old data from DB again we don't trust the user he might have changed the date of previously edited data
 //assuming the oldData is fetched correctly into a variable called $oldData
 $dataToSave = $oldData.'<br />'.$newDataToSaveWithDate;
// Save $date to DB
//assuming when everything goes right and the DB is updated
echo $dataToSave; //this would return a date like March 23, 2017 subjected to your datetimezone

And in your ajax call write a success function:

    var self = this; //or any other selector where you want to update/display the date
    $.ajax({   

          type: "POST",  
          url: "updater_1.php",  
          cache:false,  
          data: data,
          dataType: "json",
          success: function(data) {
                       $(this).html(data);
                   }       

    });
Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28
  • Maybe I wasn't exactly clear (been a long day). My data base stores this value in a single text row. So each time the database is updated with the new value. The td itself initially shows the old value from database, and appends any new data and updates the row with old+new. I want to append the date to each new item as they get added on the webpage. Clear like mud? :) It also needs to be the date the update was added .. not when it gets displayed. So therefore the date needs to get appended when written to the database. – Vacek Mar 23 '17 at 00:56
  • you mean you want to store the data as `date`+`oldData`+`newData` in your database is that what you mean? – Nishanth Matha Mar 23 '17 at 01:11
  • oldData , date + newData – Vacek Mar 23 '17 at 01:13
0

You can do this on the client side using native JavaScript code: you can use the global Date class to get the time, and write a function that returns the formatted date. (There is no simple, built in way to format Date objects in JS, but you can use libraries such as moment.js to do so).

Here's a function to format the current date from another SO answer:

function getDate() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();

    if(dd<10) {
        dd='0'+dd
    } 

    if(mm<10) {
        mm='0'+mm
    } 

    today = mm+'/'+dd+'/'+yyyy;
    return today;
}

And then you can use this in your existing AJAX call. Just call the above function while setting the data['val'] key:

data['val'] = getDate() + $(this).html().replace(/\r?\n/g, '<br />');
Community
  • 1
  • 1
joepin
  • 1,418
  • 1
  • 16
  • 17
  • close ... Here is what I get now:03/22/2017Status Test 2 ... Status already existed, and i added "Test 2" ... it added the date before the oldVal "Status" instead of in front of "Test 2" – Vacek Mar 23 '17 at 01:33
  • Ok, so then it sounds like you need to keep track of what the old text is and what the new text is. I would remove the old value of the data field from the input of the `td`, so that the user is only entering a new value: `` and then in the `focusout` function, get the new value that the user inputted using `$(this).html().replace(/\r?\n/g, '
    ')`, and the old value using `$(this).attr('oldVal')`. You can then concatenate the two along with a call to the above `getDate()`.
    – joepin Mar 23 '17 at 01:41
  • Basically, you want to separate the existing value from the newly inputed value, that way you can know where to insert the date string. From what I understand, you want to see the old value and then the new values, correct? You do not want to see the old value repeated several times? – joepin Mar 23 '17 at 01:46
  • you are correct, yes. Display the old value in the TD , allow a new value to be entered and append the date on the front side of the new value only – Vacek Mar 23 '17 at 01:47
  • I added an image to my original post ... might help clear it up a little. "3/21/2017 - Status" already existed in the database (oldVal). I then entered "Test 2" and when it saves I want it to be: " 3/22/2017 - Test 2" – Vacek Mar 23 '17 at 01:54
  • Gotcha - that image did help a lot! So to clarify my initial comment, there's no way that I can think of to have the old value in the input area, allow for new input, and distinguish between them programatically. What you can do is put the old values as an [HTML placeholder](https://www.w3schools.com/tags/att_input_placeholder.asp) and then anything new will be easily identifiable as the user's new input. Or you may want to consider putting the old values in a separate HTML element from the input, and then append the data from the input to the old value – joepin Mar 23 '17 at 02:04
  • The reason I say this is because JavaScript doesn't know or care which bits of the input are "old" and which are "new"; all it knows is that it has one string of text that it can deal with. You could, of course, compare this string with the original value, but if the user changed a character in the "old" part of the string, it would be difficult to tell – joepin Mar 23 '17 at 02:07
  • Another image & some more code added to original post: I think I need to go to bed. when I add "New 2" and I click away from the status box into the "owner" box , the date is getting written to the owner box and not appended to my new status item. *sigh* – Vacek Mar 23 '17 at 02:30