Save HTML DOM to file on server - javascript

I have an html5 web page that allows users to drag-n-drop objects between divs. After a user has moved objects around, I would like to save the current DOM to a file on my web server.
I know I can get the current HTML DOM using javascript but of course, I cannot save to a file on my server using javascript. So I thought about passing the html to a PHP page to do the "save" function, but I cannot figure out how to get the html passed to a PHP page. I've tried sending it as an argument in the URL with URI encoding, but the PHP page is not properly getting the entire string from the URL.
Should this approach work? If so, what am I missing to get the html string passed correctly to a PHP page? Or should I be using some other method?

ajax is the way to go here. If you are not familiar with ajax, please google it and learn it well. Any modern web app needs to have ajax integration in some way.
Here is how you can use javascript to communicate with the server.
Please Note I'm using JQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".draggableDivs").mouseup(function(event){
var documentStructure = ''; // whatever js you use to get document structure
var d = {"document_structure": documentStructure};
$.ajax({
url: "test.php", //Your url both relative and fixed path will work
type: "POST", // you need post not get because you are sending a lot of data
data: d,
success: function(response) {
alert('saved');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
on the server you would then do your php and save the data.
After you are done you can just respond with a json object if needed, if not just exit

you can use the approach like
after the drag and drop with javascript, show a button to save the dom.
on click event on the button, take the current dom in a variable.
use ajax to transfer your current dom to a php file(ajax file).
in the ajax file , save it into database.

Related

Ajax call. Passing value to another php file

I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'

Updating webpage with real-time database value using AJAX+PHP response

I’m creating a Javascript game and I’m currently trying to write some code that will show the player’s “Gold Balance” in real time on a html webpage.
The Gold amount is contained in my SQL database, so I’m using setInterval with a Javascript function that contains an AJAX call which calls a PHP script that grabs the current balance amount for the player and sends it back as “response”.
I’m able to have this amount appear as a Javascript alert, however I need to have the response appear as text on the webpage inside a <div> instead.
This is my current code:
<script>
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
</script>
I have this in my html source code, I would like to place the function in a separate file and call it from there, but when I tried this I wasn't able to send the response back to the html page correctly.
I was wondering if anyone knows how to have this response appear as text on the page inside <div> </div>?
Also, I was wondering if this method will really update the div in real time (ie, will it auto-refresh the div part of the webpage, showing an up to date value (every 5000 milliseconds)?
Thanks in advance!
Since you are using jQuery, you can use text() to alter the contents of an existing div (which id is "yourDiv"):
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
$('div#yourDiv').text(response);
}
});
};
You have two questions here, so I will try to address both
1) How to append to the DOM using jQuery, instead of an alert:
in the success callback function, instead of alerting the response, you can simply call
$('body').append("<div>"+response+"</div>")
2) "Real time" Gold Balance
You should use websockets. Racthet is a good websocket PHP library to help you with this: http://socketo.me/

How to write a div with jquery or javascript?

I was looking a solution to write one table, which comes from query to a DB in PHP, to a DIV, using Jquery. I'm not looking for the append's method, which I know works, but with append every time I press the button, which executes the query, the table is append to the document. The idea is not to load every time the page, but using the Jquery option, to send the post and get data back. Thank you.
UPDATE
<script>
var values = {var1: 2, var2:"Hello"};
$.get("phpfile.php", values, function(data) {
$('#id').append(data);
});
Suppose that script is call from a "onclick()"; I don't want the append each time the data, but just write in a div.
If I get you right, you just want to "update" the contents of a single div instead of reloading the whole page and this update contains a html table?!
For this purpose you could use the .html() function of jQuery: jQuery html()
In addition you should check .ajax() function of jQuery for all options/parameters: jQuery ajax()
A sample code could look like this:
$.ajax(
{
url: "yourfile.php",
cache: false,
success: function(htmldata){
$("#IdOfYourDiv").html(htmldata);
},
error: function(jqXHR, status, errorThrown){
alert("something went wrong");
}
}
);
This would load data returned for example via an echo of the php file yourfile.php, load it in the temporary variable htmldata and write/update the html contents of YourDivID with the newly returned data.
1 - on button pressed, do ajax get request (see https://stackoverflow.com/a/5942381/1163786)
2 - server receives request
3 - server sends back json response or html fragement
4a - json arrives and you start looping over these elements to build your desired html structure, then insert into the dom
4b - html fragment arrives and you simply insert it at the desired position into the dom
It's your decision, if you return a JSON respones or a HTML response.
For 4a and 4b read:
Best way to add DOM elements with jQuery
Best Practice For Creating HTML (PHP Or Jquery)?
Every piece of these steps is already explained on StackOverflow.

fetch data from a url in javascript [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 9 years ago.
I am trying to fetch a data file from a URL given by the user, but I don't know how to do. Actually, I can get data from my server successfully. Here is my code:
$("button#btn-demo").click(function() {
$.get('/file', {
'filename' : 'vase.rti',
},
function(json) {
var data = window.atob(json);
// load HSH raw file
floatPixels = loadHSH(data);
render();
});
});
It can fetch the binary data from my server, parse the file and render it into an image. But now I want it work without any server, which means users can give a URL and javascript can get the file and render it. I know it's about the cross-site request. Can you tell me about it and how to realize it?
Thanks in advance!
assuming your URL is the address of a valid XML document this example will go grab it. if the URL is on a different domain than the one that's holding your scripts you will need to use a server side scripting language to got out and grab the resource (XML doc at URL value) and return it your domain. in PHP it would be ...
<?php echo file_get_contents( $_GET['u'] );
where $_GET['u'] is a URL value from your USER. let's call our PHP script proxy.php. now our JavaScript will call our proxy.php and concatenate the URL value to the end which will allow us to pass the URL value to the PHP script.
addy = $("#idOfInputFieldhere").val();
$.ajax({
url: 'proxy.php?u='+addy, /* we pass the user input url value here */
dataType:'xml',
async:false,
success:function(data){
console.log(data); /* returns the data in the XML to the browser console */
}
});
you'll need to use the js debugger console in chrome to view data. at this point you'd want to pull out data in a loop and use find() http://api.jquery.com/?s=find%28%29
I'm not very familiar with jQuery, but as I know, due to the same origin policy, the browser won't let any JavaScript code to make an AJAX request to a domain other than its own. So in order to retrieve some data (specially JSON formatted), you can add a <script> element to your page dynamically and set its src property to the address of the data provider. Something like this:
<script src='otherdomain.com/give_me_data.json'/>
This only works if you need to access some static data (like the url above) or you have access to the server side code. Because in this scenario, the server side code should return an string like:
callbackFunction({data1: 'value1', data2: 'value2', ...});
As the browser fetches the item specified in src property, tries to run it (because it know it's a script). So if the server sends a function call as a response, the function would be called immediately after all data has been fetched.
You can implement the server side in such a way that it accepts the name of the callback function as a parameter, loads requested data and generates an appropriate output that consists of a function call with loaded data as a json parameter.

How to load an external js file as plain text and assign to variable as a string

Really sorry if this is a dumb question but I can't seem to get this to work. As the title says i am trying to load an external js file and assign it to a variable as plain text. The project is a simple js "compiler" that stitches together a number of js files and minifies them into one. I am currently using the $.get() method and appending the response to a string.
The problem is that the js file that handles the above also needs to be included in the final minified file. I can load in all the other files and stitch them together just fine but when i load this main file into itself sourcing a js file it seems to evaluate and overwrite itself and so stops the process.
For the time being i have got around the problem by loading in a copy as a .txt file but it means i have to keep two files up to date which isn't ideal.
I found this article but it refers to javascript loaded via script tags in the head.
Any help would be appreciated. I will happily post code but not sure which bits would be useful.
Update: I probably should have mentioned that the project needs to run entirely client side so i can't use PHP/.NET pages. All the files I'm loading in are on the same domain though.
Try to use Ajax.get() :
var script;
$.get('script.js', function(data) {
script = data;
});
for Ajax.get() it will work inside your domain, you can't call external domains, if your application requires loading external JS file then my guess is that you have to use PHP or another server-side language as:
var script;
$.get('getScript.php', {url: "http://test.com/script.js"}function(data) {
script = data;
});
in getScript.php you can use CURL or file_get_contents
Note that $.get() and $.post() and $.ajax() are all the same thing.
$.get and $.post are just shorthand versions of $.ajax() that come with presets (obviously, type: "GET" and type:"POST" for one...). I prefer using $.ajax because the format can be more structured, and therefore easier to learn/use.
Javascript/jQuery would look something like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "loadmyfile.php",
data: 'filename=js/myscript.js',
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#myhiddentext').val(whatigot);
} //END success fn
}); //END $.ajax
}); //END $(document).ready()
</script>
Important: Note that you would need to do all the post-AJAX processing inside the success function. See this link for some simple AJAX examples.
Note that you can send data across to the PHP file by specifying a data: parameter in the AJAX code block. Optionally, you can leave out that line and simply hard-code the filename into the PHP file.
The text of the retrieved js file comes back into the AJAX success function (from the PHP file) as a string in the variable specified as the function param (in this case, called 'whatigot'). Do what you want with it; I have stored it inside a hidden <input> control in case you wish to retrieve the text OUTSIDE the AJAX success function.
PHP would look something like this:
loadmyfile.php
<?php
$fn = $_POST['filename'];
$thefile = file_get_contents($fn);
echo $thefile;
References:
PHP file_get_contents

Categories