This is my first time using AJAX i have been reading up on it, and it is also my first time doing this with js. I think i have confused myself along the way.
I am trying to dynamically create a new restaurant page, so every time a administrator clicks the onclick button a new webpage is created, with the content from the new restaurant page, which i have already created.
At the moment i have gotten as far as on pressing a button, a new webpage is created succesfully, however, i have no idea how to access the new webpage i also wanted to display a link to the newly created webpage as it is created, like for example using before. in js to show the dynamic feature before my o'clock button for example.
HTML
<html>
<body>
<button onclick="makePage()">click</button>
<script src="makePage.js">
</script>
</body>
</html>
JS
function makePage(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = "<html><head><meta charset=\"utf-8\" /> </head><body>new website<script>alert(\"test\")</script></body></html>";
xmlhttp.open("GET","makePage.php?content=" + content,true);
xmlhttp.send();
}
PHP
<?php
$content = $_GET["content"];
$file = uniqid() . ".html";
file_put_contents($file, $content);
echo $file;
?>
Any suggestions? guidance or related pages i can read up on. Anything will be extremely appreciated.
In your js do something like this instead of alert:
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var createA = document.createElement('a');
var createAText = document.createTextNode(xmlhttp.responseText); // or whatever name you need
createA.setAttribute('href', xmlhttp.responseText);
createA.appendChild(createAText);
document.body.appendChild(createA); // or you can create some <div> or whatever and append it to that
}
This is plain javascript, but using jquery you can do it easier with ajax or get functions.
Related
Im trying to dynamically change a picture in html page according to a true/false condition using javascript.
If the variable is 0 an image and if it was 1 another picture should be shown in html page.
There are many pictures in a project that need to be changed i need a function that can do this application. But i dont know if it can be done with a single function or i should use a function for each variable.
Is siemens webserver the variable change is applied automatically by typing :="X":
when x is 0 instead of :="X": the number 0 is replaced and for the 1 instead of :="X": the number 1 is replaced.
Im familiar with html coding and how to change the picture using the image name and adding 0 or 1 after image name.
For example i name a picture stop0.png and another picture stop1.png . now in the html code i type stop:="X":.png in this way picture changes according to variable x
But this method needs the page to be refreshed to show the change. I want to do this in the easiest way possible without page refresh.
hmi should be designed in one page (for example named test.htm) and another html page with following code would update every thing in "test.htm" every second.
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>auto update page</h2>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "test.htm", true);
xhttp.send();
}
setInterval("loadDoc()", 1000);
</script>
</body>
</html>
I've got a chat function in my website for two users to chat with each other, and I'm using JavaScript, AJAX, and PHP for it.
At the moment, it won't refresh the chat area automatically unless I submit a reply to the chat or refresh the page. I can't figure out why.
JavaScript Function
function checkReply(threadid) {
// XMLHttpRequest
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("chatwrap").innerHTML = xmlhttp.responseText;
setInterval(checkReply(threadid), 10000);
}
}
xmlhttp.open("GET","inc/chatreply.php?chatid="+ threadid,true);
xmlhttp.send();
}
The event handler is on the <div> the responseText will end up in:
<div id="chatwrap" onload="checkReply('.$threadid.')"></div>
$threadid is a GET variable set at the top of the page:
$threadid = (int)$_GET['chatid'];
UPDATE
Seeing that you were in a PHP state already, the syntax was correct.
The problem is that the div doesn't possess an onload event. You'll have to attach it to the body tag, or include a script in the head or below the div, as it will only execute after the div has been rendered.
You're not including the PHP variable correctly. At the moment you are passing the string .$threadid. to the checkReply function. You will have to drop into PHP mode again before using this syntax by using the delimiters <?php & ?>.
<div id="chatwrap" onload="checkReply(<?php echo $threadid; ?>)"></div>
This should work better.
I have a site and I want it to randomly load a different HTML5 Javascript animation each time the page is loaded, JavaScript is by far one of the weakest of my skills and I appreciate any help in advance and if this happens to be duplicate (I've tried searching) then please vote for the question to be closed.
Basically the method I have used is a dirty one and most likely the reason its not working, basically I tried randommath and had no luck and put this down to my JS skills being extremely weak, the alternative method which looked easier doesn't work either and this is basically inserting a HTML on page load, so for example a.html and b.html which both contain different scripts.
This is what my code looks like:
HTML
<html>
<head>
<script src="js/insert.js"></script><!-- This inserts the Random Page -->
</head>
<body onload="loadExternalHTMLPage()">
<div id="injectjs"> </div>
<canvas="id"> </canvas>
<script src="js/animation-lib-pageA.js"></script><!--Library for pageA -->
<script src="js/animation-lib-pageB.js"></script><!--Library for pageB -->
</body>
</html>
Inject.js
function loadExternalHTMLPage() {
var xmlhttp;
var pagesToDisplay = ['a.html', 'b.html'];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("jsinsert").innerHTML = xmlhttp.responseText;
}
}
var randomnumber = Math.floor(Math.random() * pagesToDisplay.length);
xmlhttp.open("GET", pagesToDisplay[randomnumber], true);
xmlhttp.send();
}
Most JS Guru's should be able to see that I'm randomly inserting a.html and b.html on page load, now this works but the problem is the scripts contained within a.html and b.html are not executing. (using firebug I can clearly see that the scripts are being inserted as intended).
so for example a and b looks like:
a.html
<script> window.onload = function () { }</script>
b.html
<script> window.onload = function () { } </script>
Basically the code within A and B are valid and work fine within this insert and I've filled the above examples as just a placeholder. A and B both contain JavaScript that executes animation contained within the canvas but it doesn't work at present and I suspect its something to do with the fact I'm loading the scripts after the page has been loaded. Thanks in advance.
You can randomly load the html for A or B and then run its animation.
This example uses jQuery which makes the task of loading remote html easier. Here is a link to the jquery .load function which replaces an existing elements html with the downloaded html: http://api.jquery.com/load/ If you want pure javascript, you can use that [messier!] alternative, but the logic remains the same.
These are the steps:
Be sure the web page has loaded,
Randomly pick A or B to load/execute,
Replace the html in #injectjs with htmlForA or htmlForB,
Wait until the html has been fully replaced,
Run the appropriate animationA or animationB.
Here is starter code. (Be sure you include the jQuery library)
<script>
window.onload(){
// randomly load html+animation A or B
if(Math.random()<.50){
$('#injectjs').load(
'yourSite.com/HtmlForA.html', // first load the html for A
function(){ animationA(); } // then run animationA
);
}else{
$('#injectjs').load(
'yourSite.com/HtmlForB.html', // first load the html for B
function(){ animationB(); } // then run animationB
);
}
}
</script>
You can always use eval() to execute the content you downloaded ... :) (not recommended).
Or you can modify the html page on server to include the random script you want before serving the page to the user (you don't state platform) since it's anyways changed at page load.
If I am way off on how to employ this code then please forgive me, but is it possible to use something like
var url = 'http://www.maxcashtitleloans.com/lmapp.html'
document.write('<script src="'+url+'"></scr'+'ipt>')
to somehow display an html form inside many websites across different servers?
I have a single HTML form that will be continually updated as the needs of the company change, and would like to get them off of IFRAME calls.
A different questions towards the same goal "How can I display off site content on a website and not use IFRAME"
I know of an affiliate marketing company that uses
<script type='text/javascript'>
var inputOptions = {
UserID: '35696',
Product: 'payday',
ProductTemplate: 'lights',
Server: 'https://altohost.com/',
mobileDevices: true,
parseDefaultValue: true,
visitor: {
referrer: (document.cookie.match("rfrrr[\r\n\t ]*=[\r\n\t ]*(.*?)(;|$)") || [,''])[1],
subaccount: (document.cookie.match("src[\r\n\t ]*=[\r\n\t ]*(.*?)(;|$)") || [,''])[1],
keyword: (document.cookie.match("kwrd[\r\n\t ]*=[\r\n\t ]*(.*?)(;|$)") || [,''])[1],
clickid: (document.cookie.match("clcid[\r\n\t ]*=[\r\n\t ]*(.*?)(;|$)") || [,''])[1]
},
};
document.write('<scr'+'ipt type="text/javascript" src="https://altohost.com/system/applicationforms/init.php?vn=inputOptions"></scr'+'ipt>');
</script>
I'd propose a slightly different approach.
Use JavaScript to create the HTML form and include that script into all other websites using the same source.
Assume form.js is the file you want to include in every website.
Live DEMO
forms.js
var company = {};// Avoid name clashes!!!
company.form = function() {
this.render();
};
company.form.prototype.render = function() {
var url = "blablabla";
this.form = document.createElement("form");
this.form.setAttribute("method", "post");
this.form.setAttribute("name", "company-specialform");
this.form.setAttribute("action", url);
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("value", "test");
var submit = document.createElement("input");
submit.setAttribute("type", "submit");
submit.setAttribute("value", "submit");
this.form.appendChild(input);
this.form.appendChild(submit);
var that = this;
this.form.onsubmit = function(event) {
that.submit.call(that, event);
};
};
company.form.prototype.submit = function(event) {
event.preventDefault(); // if needed
alert(" Custom submit was called");
};
company.form.prototype.getForm = function() {
return this.form;
};
company.form.append = function(container) {
var form = new company.form();
container.appendChild(form.getForm());
};
var target = document.getElementById("container");
company.form.append(target);
Now simply include forms.js on any other website, but make sure you use the same src for all of those websites, so you can keep the script up to date.
Now on every of those website, they can add the form with company.form.append(someDiv) and when you update the script the update will be available on all websites.
Okay, there is solution for you. Your embed code like this;
<script>
var url = 'http://www.maxcashtitleloans.com/lmapp.js'
document.write('<script src="'+url+'"></scr'+'ipt>')
</script>
And http://www.maxcashtitleloans.com/lmapp.js like this :
function ajaxex()
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.write(xmlhttp.responseText);
}
}
xmlhttp.open("GET","lmapp.htm",true);
xmlhttp.send();
}
ajaxex();
Thats work fine. And demo for you : http://commention.com/lmappjsexample/
That solution like javascript proxy, you have to create a javascript file for render your html page.
You can use simple jQuery:
<script>
$('body').load(url);
</script>
well, a <script> tag is for including javascript, not HTML. You want to look into ajax. You want to load the html file via ajax into a div.
Alternatively, leave it as an iframe. Iframes are for including one page into another.
Edit
The example you included from the affiliate is meaningless for you. They are loading javascript that is generated programmatically from a PHP server side script based on input from client side cookies. You are trying to load en external html file, these are two different tasks.
javascript in your HEAD tag
<!-- Include the jquery library - never re-create the wheal -->
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
// Run once the page is loaded
$('#putFormHere').load('http://www.maxcashtitleloans.com/lmapp.html');
});
</script>
Replace your current iframe with this
<div id='putFormHere'></div>
Assumption
I'm assuming that www.maxcashtitleloans.com is the same domain as your current page. If not then they only way to do this is via an iframe. Javascript will not support cross-site scripting.
Script tags do not HTML rendering. You have to add HTML render to your html page. Maybe you can add this code to your html page. This code render your html codes on javascript.
document.write($(body).html());
I have a multi-level drop down menu (done using HTML + CSS) that I want to put on a number of different pages. In the future I will need to update this menu and change its contents, so I have saved the HTML in its own file so that I can roll out the changes to all the pages at once (instead of having to go through each page and repeatedly paste in the changed list items).
I have tried using iframe, but this cuts off the menu items with its limited height (setting a manual height that's big enough would leave tons of blank space, of course):
<iframe height="100%" src="menu.html" frameborder="no" width="100%" scrolling="no"></iframe>
I also tried using embed (this looks fine until you mouse over the menu items -- it just scrolls within the frame):
<embed type="text/html" src="menu.html" width="100%" height="100%"></embed>
The menu functions fine when the code is simply dumped into the individual pages I need it on, so I know that's not the issue. It's the embedding and calling it from its own HTML file that is the problem. Is there a simple way to do this that will allow the drop-down menu to appear as it should?
I should mention that while I have my IT department's blessing to do this, this is a project that they aren't supporting. I can only edit the HTML of my webpages in the body, and not the head. The exception being HTML pages I upload as files (like the menu code). So there are some constraints.
Well here is a bit of a long winded javascript approach that might keep your IT guys happy:
window.onload = new Function("load('embed-me.html','content')"); // Replace with URL of your file and ID of div you want to load into.
function ahah(url, target) {
document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
Not written by me(LINK) (I just added the run on page load bit).
Tested and working (in Chrome at least). Though your site will have no menu if the user has javascript disabled!
EDIT:
Example...
<body>
<script type="text/javascript" src="embed-me.js"></script> <!-- load the javascript -->
<div id="content"></div> <!-- html will be embedded here -->
</body>
I use the following php code and works very nice. It doesn't even show when you check the source code online.
<?php include("menu.php"); ?>
Use php Include !!
Okay first.. copy the menu code and save it on to a file called menu-1.php
then whenever you want to use your menu; just type the following code:
<?php include("menu-1.php"); ?>
This is a good way to do menu's because every time you need to update your menu, you wont have to update every single page, just update your menu-1.php
P.S. PHP might not show up on your local machine unless you are using wamp or xamp