-1

I'm looking to solve the issue of not being able to Save/Apply changes to an .html document when the document.createElement("div"); is used in JavaScript. I want to be able to save the changes made to the document and 'overwrite' the original .html document.

Future Possibilities(these can be ignored): Deletion of these elements, and saving those changes as well to revert it back to it's original state.

EDIT: -------------- I didn't make this clear, sorry!

THIS CODE IS TO EMBED MULTIPLE YOUTUBE VIDEOS ON A SINGLE PAGE; I WOULD LIKE SOME HELP HAVING SOMETHING OVERWRITE THE ORIGINAL .HTML DOCUMENT. THEREFORE LOADING THIS NEW CONTENT EACH TIME SOMEONE OPENS THE PAGE.

Here is my code:

<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body>
  <div id="container">
    <div id="header" align="center">Home</div>
    <div align="center">
      <button onclick="myFunction()">Button</button>
    </div>
    <div id="parentElement" align="center">
    </div>
    <script>
      function myFunction() {
        var parentElement = document.getElementById('parentElement');
        var theFirstChild = parentElement.firstChild;
        var newElement = document.createElement("div");
        parentElement.insertBefore(newElement, theFirstChild);
        newElement.setAttribute("id", "newElement");
        var embed = prompt("Please enter your YouTube Embed Link");

        if (embed != null) {
          document.getElementById("newElement").innerHTML = embed;
        }
      }
    </script>

</body>

</html>
Tsotmix
  • 13
  • 2
  • How are you trying to save it? I doubt that a browser can do that in straight JS; you can imagine the security nightmare if an HTML page could write to the local disk at will. A plugin could do it, if you wrote the plugin. – 15ee8f99-57ff-4f92-890c-b56153 Dec 24 '15 at 02:51
  • Any way. I read some things about using AJAX, PHP, and MySQL. Would this be the best route to go? – Tsotmix Dec 24 '15 at 04:32
  • You could send back innerHTML to the server, certainly. That's an odd way to do dynamic content though. It would be more usual to send back the list of YT vids and save that. Then have the page query for the list, and generate the content from that. – 15ee8f99-57ff-4f92-890c-b56153 Dec 24 '15 at 12:20
  • ...also, if this is a public facing server, it's a really bad idea to have a web service that lets any random person out of the darkness replace an HTML file on your server with arbitrary content. – 15ee8f99-57ff-4f92-890c-b56153 Dec 24 '15 at 12:44
  • So are you meaning more like a 'widget'? Like the twitter feed widgets? And this will eventually have a user login, but I'm trying to get the basics back atm. The user part will be a little more difficult. – Tsotmix Dec 24 '15 at 13:29

3 Answers3

0

<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body>
  <div id="container">
    <div id="header" align="center">Home</div>
    <div align="center">
      <button onclick="myFunction()">Button</button>
    </div>
    <div id="parentElement" align="center">
    <div id="newElement" style="display: hidden"></div>
    </div>
    <script>
      function myFunction() {
        var embed = prompt("Please enter your YouTube Embed Link");

        if (embed != null) {
          document.getElementById("newElement").innerHTML = embed;
          $('#newElement').css('display','inline');
        }
      }
    </script>

</body>

</html>

just taking out the parent - child element relationship in javascript code and put the new element div in html with display:none style attribute. Then in click function, just make it visible.

Cheers!

ehg
  • 26
  • 3
  • This is a neat concept, but I can only insert one video, and if I try another it overwrites that embed that I just entered. This isn't really the outcome I was looking for. – Tsotmix Dec 24 '15 at 04:34
0

It took sometime to understand your requirement infact still now it is not clear .But from your code I understand that you are trying to get a text from prompt message and initally you want to display it in your page.But that is not working since you are not able to execute it. document.getElementById("newElement").innerHTML Rather that using innerHTML you can check textContent. Here is a minor change in your function

        if (embed != null) {
          newElement.textContent = embed;
        }

WORKING COPY

brk
  • 48,835
  • 10
  • 56
  • 78
  • My code works for me, I'm just wanting a way to 'overwrite' the existing index.html document so the content sticks every time I load the page, without loading the default HTML. Sorry to have wasted your time. – Tsotmix Dec 24 '15 at 04:33
  • HTML is static content , you need to use jsp/jstl and update its content on page load.You cannot expect js to overwrite a html ! – brk Dec 24 '15 at 04:48
0

I think what you're asking is how to put dynamic content in a static web page. This is not my area of expertise, but I can give you the outlines of how to do what you're trying to do. This is the architecture. You'll have to fill in some implementation details yourself, but I'll try to give you a clear idea of what you'll be googling for at each step of the way.

Suggestions for improvement from real web guys will be eagerly embraced. If there's already an answer on SO that walks a noob through the design of a trivial single-page AJAX/JSON web app, I can't find it. There must be one, though.

This is a lot more complicated than your original idea, but rewriting a web page not a great idea: You're writing arbitrary zeroes and ones from strangers to a file on your server. You need one HTML file per user, if you store their data in HTML files. How do you serve him the right one? What if you change the layout after you have 500 users? You'd be writing a script to alter the text of 500 HTML files. In practice it's just a horrorshow.

What you're groping for is dynamic content via AJAJ, which we usually still call AJAX for historical reasons (prior to the advent of CNC machining, curly braces were difficult to mass produce economically, and so web services commonly used pointy brackets instead).

First, write a web page to serve the user's personal content. It'll save updates as well. May as well use PHP. That "page" isn't a web page; instead of HTML, it returns JSON text with a content-type of application/json. The user can POST text to it in JSON format as well. This "page" is a web service.

On a get request, the web service page, given a username (and appropriate security), will retrieve the user's YouTube video list from MySQL and return it to the caller as JSON.

For now, the content going to and from that web service page is pretty simple. Just a list of URLs. Let's make it an object that has one member, and that one member will be an array of objects that contain information about YouTube videos the user has chosen. For now, each one just has a URL, but we may want to add more detail later, so we won't just make it an array of bare URL strings. At the top level, we'll also be able to add other types of content alongside "YouTubeVideos" if there's a need -- for example, you're going to want a username and a security token.

{
    "YouTubeVideos": [
        {
            "url": "http://youtu.be/LKJDFKLJDF"
        },
        {
            "url": "http://youtu.be/87sdfd234"
        }
    ]
}

In the HTML page, your JS code will first request the user's data from that web service in onLoad. You'll do that using XMLHttpRequest. You'll use the JavaScript function JSON.parse to turn the response text into a JS object.

So write a function called requestUserYTContent or something, and call that from onLoad. This is simplified: There's no validation, exception handling, etc.

//  Empty default instance to start out. 
var ytInfo = { "YouTubeVideos" : [] };

function requestUserYTContent() {
    //  ...
    //  Do stuff with XMLHttpRequest to get the JSON for this user from 
    //  the web service. 
    //  ...

    ytInfo = JSON.parse(http_request.responseText);

    console.log('Got ' + ytInfo.YouTubeVideo.length + ' videos');

    //  Once you've got that JSON object, you can loop through the 
    //  videos and do stuff with their urls. We'll stick that loop in 
    //  another function so we can re-use it in cases where the list
    //  changes for reasons other than a web service call. 

    var ytDiv = document.getElementById('ytContent');

    ytDiv.innerHTML = 
        generateVidListHTML(ytInfo.YouTubeVideos);
}

function generateVidListHTML(vids) {
    var newHTML = '';
    for (var i = 0; i < vids.length; ++i) {
        var url = vids.YouTubeVideos[i].url;
        //  ...generate HTML to display this video, and append to 
        //  newHTML
    }
    return newHTML;
}

So we keep that ytInfo around in a global variable. When the user adds to the list or deletes from it, alter the list, re-generate the HTML with generateVidListHTML(), insert the HTML into the page as above, and then post the newly-altered list as JSON back to the web server to update the user's content in the mySQL database.

You'll POST data back to the web service with XMLHttpRequest. Here's an example. You'd be using a different content-type, of course.

https://stackoverflow.com/a/9713078/424129

In JavaScript in the web page, converting a live JavaScript object back to JSON is easy: https://stackoverflow.com/a/4162803/424129

For simplicity, you may as well just pass the same JSON format back and forth.

When you send JSON back to the web service, it'll need to parse it too. I don't know how to parse JSON in PHP, but I know somebody who does:

https://www.google.com/search?q=how+to+parse+json+in+PHP

Community
  • 1
  • 1
  • This is certainly a lot of information; and it seems to be going in the right path of what I wanted. So I will put this together, and if I have any questions along the way; I will ask. Thank you very much for your major contribution. I do appreciate it. I will mark your answer for now, in case anyone would like to try this. – Tsotmix Dec 24 '15 at 17:54
  • @Tsotmix Yes, it's definitely a bigger project than you were probably envisioning when you sat down to tackle it. By all means, ask any questions that come up. Starting tomorrow I'll be on the road for several days visiting family, but I'll check in on my phone. – 15ee8f99-57ff-4f92-890c-b56153 Dec 24 '15 at 17:57
  • There's no other way to say that, that's anymore true. But I'm willing, and thank you. Enjoy your time with your family and have a Merry Christmas/Happy Hanukkah, whichever you celebrate. :) – Tsotmix Dec 24 '15 at 19:13