0

I have a page that I have edited after load and what I want to do is get the pages current HTML and pass that off to a PHP script.

I first passed document.documentElement.innerHTML but that ended up including a bunch of computed style garbage at the top which I did not want. After googling around I found I could use ajax to get a copy of the current file on the server and then replace the edited part afterwards.

I can get the copy of the file using this:

var url = window.location.pathname;
  var filename = url.substring(url.lastIndexOf('/')+1);

  $.ajax({
    url: filename,
    async: false,   // asynchronous request? (synchronous requests are discouraged...)
    cache: false,   // with this, you can force the browser to not make cache of the retrieved data
    dataType: "text",  // jQuery will infer this, but you can set explicitly
    success: function( data, textStatus, jqXHR ) {
        origPage = data; // can be a global variable too...
        // process the content...
    }
});

Which works fine and gets me the html I expected and see when viewing the page in notepad.

The next step is what I cannot figure out. All I want to do is swap out the innerHTML of a div with an id of 'editor' with what the current value is, so I have tried this:

origPage.getElementById('editor').innerHTML = e.html;

But I get the error "TypeError: undefined is not a function". I must be doing something simple wrong I feel but I don't know the proper formatting to do this. I have tried the following variations:

alert($(origPage).getElementById('editor').innerHTML);
//Different attempt
var newHtml = $.parseHTML( origPage );
alert($(newHtml).getElementById('editor').innerHTML);
//Different attempt
alert($(origPage).html().getElementById('editor').innerHTML);

But I always get "TypeError: undefined is not a function" or "TypeError: Cannot read property 'getElementById' of undefined". How can I do this properly?

EDIT:

Complete page html below:

<!DOCTYPE html>
<html>

  <body>
    <div id="editor">
      <h1>This is editable.</h1>
      <p>Click me to start editing.</p>
    </div>
 

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript" src="snapeditor.js"></script>
    <script type="text/javascript">
      var editor = new SnapEditor.InPlace("editor", {onSave: function (e) {
   var isSuccess = true;
   //var origPage = e.html;
   var origPage;
   var url = window.location.pathname;
   var filename = url.substring(url.lastIndexOf('/')+1);
   // Actually perform the save and update isSuccess.
   
   // Javascript:
   $.ajax({
        url: filename,
        async: false,   // asynchronous request? (synchronous requests are discouraged...)
        cache: false,   // with this, you can force the browser to not make cache of the retrieved data
        dataType: "text",  // jQuery will infer this, but you can set explicitly
        success: function( data, textStatus, jqXHR ) {
            origPage = data; // can be a global variable too...
            // process the content...
        }
    });
 //origPage shows expected html as this point
 
 //alert($(origPage).getElementById('editor').innerHTML);
 //alert($(origPage).html().getElementById('editor').innerHTML);
   $(origPage).getElementById('editor').innerHTML = e.html;//fails here
   alert(origPage);
   //alert(newHtml.getElementById('editor').innerHTML);
  $.ajax({
   data: {html: origPage, docName: 'example1.html'},
   url: 'savePage.php',
   method: 'POST', // or GET
   success: function(msg) {
    alert(msg);
    isSuccess = true;
   }
  });
   return isSuccess || "Error";
 },
 
 onUnsavedChanges: function (e) {
   if(confirm("Save changes?")) {
  if(e.api.execAction("save")){
   //location.reload();
  }
   } else {
  e.api.execAction("discard");
   }
 }});
    
    </script>
  </body>
</html>
Bryan
  • 623
  • 1
  • 6
  • 23
  • Does this help? http://stackoverflow.com/questions/28700919/cannot-integrate-jquery-variable-into-php/28701329#28701329 – cssyphus Feb 24 '15 at 22:44
  • You are sending an AJAX request to the same page you are on, which will result in the current page's HTML being returned. This is an error condition and is usually not desired. Please show us your entire code (HTML and jQuery/js) so we can better assist you. – cssyphus Feb 24 '15 at 22:49
  • Hmm, I don't see how but I may be missing something? I can post new information to my php script just fine, what I can't do is get the current page as a jquery object that I can manipulate the innerHTML of. – Bryan Feb 24 '15 at 22:50
  • @gibberish I've added the whole page to my post – Bryan Feb 24 '15 at 22:58
  • `origPage ` is a string, it doesn't have any DOM methods as is, if you want to access parts of it try `$(origPage).find('#editor').html()`. Hard to follow exactly what you are doing but most likely there are simpler approaches like using jQuery `load()`. I disagree with @gibberish that accessing same page is an error condition – charlietfl Feb 24 '15 at 22:59
  • and DO NOT USE `async: false`. It is a terrible practice and browsers are starting to deprecate it's use – charlietfl Feb 24 '15 at 23:01
  • @charlietfl I tried "$(origPage).find('#editor').html() = e.html;" but I get the error "ReferenceError: Invalid left-hand side in assignment" – Bryan Feb 24 '15 at 23:06
  • you don't set html that way with jQuery. I assumed you were trying to `get` the html. Question is really confusing, I think you should create a better explanation of your overall goals rather than have people try to understand them from fragmented invalid code. – charlietfl Feb 24 '15 at 23:06
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/71625/discussion-between-bryan-and-charlietfl). – Bryan Feb 24 '15 at 23:09
  • @charlietfl Hi Charlie - this is what I mean by "error condition". Sounds like what the OP is doing: http://stackoverflow.com/questions/17529509/values-not-updated-after-an-ajax-response/17530014#17530014 – cssyphus Feb 25 '15 at 01:25
  • @gibberish I think I explained my problem better here if it helps: http://forums.phpfreaks.com/topic/294877-get-contents-of-current-html-body-without-the-mess-documentdocumentelementinnerhtml-adds/ – Bryan Feb 25 '15 at 03:22
  • @Bryan Meet me in same chat room you used with CharlieTFL (link above) – cssyphus Feb 25 '15 at 03:29

1 Answers1

0

It seems that you get the user's changes in a variable - you called the var e.html. That is not a good variable name, BTW. If you can, change it to something like htmlEdited

Question: If you add the command alert(e.html); what do you get? Do you see the HTML after user edits?

If yes, then what you need to do is send that variable to a PHP file, which will receive the data and stick it into the database.

Code to send the data:

javascript/jQuery:

alert(e.html);  //you should see the user-edited HTML

$.ajax({
    type: 'post',
     url: 'another_php_file.php',
    data: 'userStuff=' + e.html,    //var_name = var_contents
    success: function(d){
        window.location.href = '';  //redisplay this page
    }
});

another_php_file.php:

<?php
    $user_edits = $_POST['userStuff']; //note exact same name as data statement above

    mysql_query("UPDATE `your_table_name` SET `your_col_name` = '$user_edits' ") or die(mysql_error());

    echo 'All donarino';

The AJAX javascript code will send the var contents to a PHP file called another_php_file.php.

The data is received as $user_edits, and then inserted into your MySQL db

Finally, I presume that if you redisplay that page it will once again grab the contents of the #editor div from the database?

This is where you haven't provided enough information, and why I wanted to see all your code.

ARE you populating that div from the database? If not, then how do you expect the page to be updated after refreshing the page?

You would benefit from doing some tutorials at phpacademy.org or a thenewboston.com. Do these two (free) courses and you'll be an expert:

https://phpacademy.org/videos/php-and-mysql-with-mysqli

https://phpacademy.org/videos/oop-loginregister-system


If all you need to do is insert the contents of e.html to replace the #editor div, then try this:

$('#editor').html(e.html);

HOWEVER, you need an event to trigger that code. Are you able to do this?

alert(e.html);

If so, then put the first bit of code at that same spot. If not, we need more information about when your code receives that variable -- that is where you put the $('#editor').html(e.html); statement.

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • e.html is returned from the editor I am using, I have not named it that myself. If I alert it I get "

    I edited this!

    I edited this too

    " or something like it. I was hoping to keep this all contained to one file if I could. At the end of the day all I really need to do is take the contents of a html page and change the contents of one div. My origPage is a string with " [...] " and my e.html content is shown above, if I can just insert the contents of e.html to replace the #editor div I would be happy.
    – Bryan Feb 25 '15 at 18:38
  • Okay, keep the variable with that name. It's just a name, however unusual. But did you look at the post about putting AJAX on same page as HTML? http://stackoverflow.com/questions/17529509/values-not-updated-after-an-ajax-response/17530014#17530014 I am pretty sure that is what you are doing -- but from your above comment, it doesn't look like even that is necessary. More in next comment. – cssyphus Feb 25 '15 at 18:48
  • If all you need to do is ***insert the contents of e.html to replace the #editor div***, then see new section at bottom of my answer – cssyphus Feb 25 '15 at 18:48
  • That would just replace the contents of the #editor div on the current page...with the current contents of the #editor div essentially doing nothing yes? I need it to replace the contents of the #editor div within my origPage variable. – Bryan Feb 25 '15 at 19:28
  • I think you are saying that you need the users' changes to be persistent, so that next time the page is refreshed the div still contains the modified contents, right? You have two choices: (1) store the data in a database (MySQL?) and with each page view/refresh, load the data from the DB and write into that div, or (2) save the data for that div into a file on the server and do as in (1). Please do yourself an enormous favor and do the tutorials at PHPAcademy -- if you had done them last night, you would know how to do this now. Best wishes for your project. – cssyphus Feb 25 '15 at 19:45
  • Yes, I want those changes to be persistent after the page refreshes, I know how to do it through that method and ended up loading and writing the contents of #editor to a .txt file because this had to be completed. Right now I just want to walk away from this project knowing how to do this seemingly simple thing. Is there no way to take your bit of code "$('#editor').html(e.html);" and have #editor refer to the div within origPage? Can't it be parsed into a more managable jquery object like I was trying to do initially? – Bryan Feb 25 '15 at 20:02
  • That is totally not the right way to do it, Bryan. I'm afraid I don't have a definitive answer on whether it is actually possible. I would think it should be, but trust me: you would never, ever do this. If you managed it as an exercise, you would never do it again. It's like mastering flipping a car up onto two wheels - not something you would ever do publically. Do those PHPAcademy tuts, man! :) – cssyphus Feb 25 '15 at 20:09
  • Thanks, I'm already familiar with those methods and have used them for projects in the past, when I'm able on smaller projects like this I try to do things in a new way as an exercise, I guess I'll have to write this one off though. – Bryan Feb 25 '15 at 20:28