How to pass post results from one html to other html? - javascript

I want to pass results (return value of POST) from one page into other embedded page, and I don't know how can I do it.
The structures look like:
main html page (Welcome.html) which has ej2 file (Buttom.html):
Welcome.html:
<html>
<body>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
xhr.open("POST", "/addGrade", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
data = // logic to get the data (i skipped adding this part)
xhr.send(data);
xhr.onloadend = function () {
// HERE I WANT TO PASS THE RESULTS TO Buttom.html
};
}); // click on submit
}); // ready
</script>
<form id="gradeForm">
<p>
<label>Name:</label>
<input type="text" name="name" id="name">
</p>
<p>
<label>Grade:</label>
<input type="text" name="grade" id="grade" value="100">
</p>
<p>
<button type="button" id="submit" >submit</button>
</p>
</form>
<div>
<%include Buttom.html%>
</div>
</body>
</html>
Buttom.html:
<head>
</head>
<body>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
}); // ready
</script>
<p id="ppp">
<!-- Here I want to add the results -->
<p>
</body>
How can I pass the results from POST (in welcome.html) to Buttom.html (i.e into function of js in Buttom.html) ?

Welcome.HTML
$(document).ready(function(){
$("#submit").click(function(){
xhr.open("POST", "/addGrade", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
data = // logic to get the data (i skipped adding this part)
xhr.send(data);
xhr.onloadend = function () {
// If your data is big then use cookies or create form and send it to another page
var url = "YourPage?data=" + encodeURIComponent(YOUR_DATA);
window.location.href = url;
};
}); // click on submit
}); // ready
ON Buttom.html:
$(document).ready(function(){
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null) {
// YOUR CODE
}
});
});

Related

submit form via JS

I have created a chrome extension which send a form to GTmetrix.
This is the html code:
<html>
<head>
<title>GTmetrix Analyzer</title>
<script src="popup.js"></script>
</head>
<body>
<h1>GTmetrix Analyzer</h1>
<button id="checkPage">Check this page now!</button>
</body>
</html>
This is the JS file:
document.addEventListener('DOMContentLoaded', function() {
console.log("f")
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
console.log("f")
chrome.tabs.getSelected(null, function(tab) {
d = document;
var f = d.createElement('form');
f.action = 'http://gtmetrix.com/analyze.html?bm';
f.method = 'post';
var i = d.createElement('input');
i.type = '';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
console.log("a")
console.log(f)
});
}, false);
}, false);
I added the console.log events in order make sure that the code is executed, however, I expect the html to present the submitted form, including the response. The issue is that I only get the tab url added to the html when I click on the button due to(d.body.appendChild(f);) so I am not sure why I can't see it.
You can try this another approach of d.body.appendchild(f):
document.getElementsByTagName('body')[0].appendChild(f);
or have a null checker like this:
if ( document.body != null )
{
document.body.appendChild(element);
}

JS automated click not working

EDIT:
I think i have found a solution for this one. Might be a little primitive but inserting it here until someone comes up with a better solution.
Thanks !
<html>
<body onload="makeShort()">
<p id="button" style=display:none; onclick="makeShort()">Click me.</p>
<span id="output" style=display:none; >Wait. Loading....</span>
</body>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str =""+response.id+"";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: creating short url n"+ response.error);
}
});
}
window.onload = makeShort;
function load()
{
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxx');
gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});
}
window.onload = load;
</script>
<script>
setTimeout(function(){
document.getElementById('button').click();
},1000);
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
function SendLinkByMail(href) {
var subject= "Interesting Information";
var body = document.getElementById("output").innerHTML;
body += " Interesting Information";
var uri = "mailto:?subject=";
uri += encodeURIComponent(subject);
uri += "&body=";
uri += encodeURIComponent(body);
window.open(uri);
}
</script>
</head>
<body>
<p>Email link to this page</p>
</body>
</html>
Can some one suggest why this "auto-click" function is not working in my code below?
function makeShort() {
var longUrl = location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + longUrl + "<br>";
str += "<b>Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("output").innerHTML = str;
} else {
alert("error: creating short url n" + response.error);
}
});} window.onload = function() {
var button = document.getElementById('modal');
button.form.submit();}
function load() {
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxxxxx');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("output").innerHTML = "";
});} window.onload = load;
<html>
<input type="button" id="modal" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output">Wait. Loading....</div>
<head>
</head>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
My basic aim is to insert a "share via email" button on the page which would shorten the url on the address bar and open user's email client/whatsapp app to share that url..
Obviously I could not find a way to combine these two functions in to one since I am not a very experienced js person. The primitive solution I found is to auto-click the first function, get the short url, and then find a different code to insert this in to the body of the "mailto" link, which will be my 2nd challenge.
To programmatically click a button on page load
If you are using jQuery:
$(function() {
$('#modal').click();
});
Plain javascript:
window.onload = function(){
var event = document.createEvent('Event');
event.initEvent('input', true, true);
document.getElementById("modal").dispatchEvent(event);
};

Javascript scope and sequentiality issue

I want to get an id from the query and display it in html.
I want to keep things in separate javascript files, because in the future, it will retrieve a json from php and will filter it based on some checkboxes, radio buttons, etc. and then display the result.
In this moment, I get a blank page, and the id value is not shown, so I'm doing something wrong.
http://localhost:10600/js1/index.php?id=5
index.php
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
<div class="results"></div>
</body>
</html>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript" src="display.js"></script>
<script type="text/javascript" src="sequence.js"></script>
config.js
function getId() {
id = "<?php echo $_GET['id']; ?>";
}
display.js
function updateHtml() {
window.onload = function() {
document.querySelector('.results').innerHTML = id;
}
}
sequence.js
function seq()
{
getId();
updateHtml();
}
seq();
Please try the following:
index.php
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
<div class="results"></div>
</body>
</html>
<script type="text/javascript">
var id;
function getId() {
id = "<?php echo $_GET['id']; ?>";
}
</script>
<script type="text/javascript" src="display.js"></script>
<script type="text/javascript" src="sequence.js"></script>
function getParameters() {
var url_params = window.location.search.substring(1); // Removing characters : ?
var params = url_params.split("&");
var res = {};
for (var i = 0, c = params.length; i < c; i++) {
var split = params[i].split("=");
res[split[0]] = split[1];
}
return res;
}
Returns an object {param: value}
In index.php within body you can do like this one
<input type="hidden" name="hidden_id" id="hidden_id" value="<?=$_GET['id']?>">
In JS :
If you are using jQuery,then you should do like this one.
$(document).ready(){
var strHiddenId = $("#hidden_id").val();
$(".results").html(strHiddenId);
}

Execution of multiple php pages on a single click

This is the code fragment I have :
<html>
<script type="text/javascript">
function Run()
{var a=["ONE" ,"TWO" ,"THREE", "FOUR", "FIVE"];
window.location.href = "index.php?w1=" +a;}
</script>
<body>
<input type="button" id="upload" value="RUN" onclick="Run();" />
<body>
</html>
when clicked 'RUN', I need to send array value to multiple pages one after the other without shifting between pages.
1. Page1 index.php // a has no use, executed first
2. Page2 index2.php // a is used here, executed second
3. Page3 index3.php // a is used here, executed third
Is it possible?
Sounds like you can achieve what you're trying with ajax. To make them run synchronously (one after the other), you could call the next PHP page in the success callback of the currently running ajax.
Some pseudo code below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var data = "my data";
$.ajax({ url: 'index.php',
data: { data: data },
type: 'post',
success: function(output) {
runindex2(output.data);
}
});
function runindex2(data) {
$.ajax({ url: 'index2.php',
data: { mydata: data },
type: 'post',
success: function(output) {
runindex3();
}
});
}
function runindex3()....
</script>
Best case:
Use ajax.
<html>
<head>
<script type="text/javascript">
var xmlhttp = new Array;
var url = new Array;
// Create 3 instances.
for (var i = 0; i < 3; i++) {
xmlhttp[i] = new XMLHttpRequest;
}
var arr = ["ONE", "TWO", "THREE", "FOUR", "FIVE"];
// function which will run
// on button click.
function Run() {
var url1 = "test.php?w1=" + arr;
var url2 = "test1.php?w1=" + arr;
var url3 = "test2.php?w1=" + arr;
url = [url1, url2, url3];
for (var i = 0; i < 3; i++) {
xmlhttp[i].open("GET", url[i]);
xmlhttp[i].onreadystatechange = function() {
if (this.readyState == 4) {
document.write(this.responseText);
}
}
xmlhttp[i].send(null);
}
}
</script>
</head>
<body>
<input type="button" id="upload" value="RUN" onclick="Run();" />
<body>
</html>
Complex Solution:
use 4 iframes in the document. First keep them display none. Then on button click, open the url in all the iframes.
<html>
<head>
<script type="text/javascript">
var url = new Array;
var arr = ["ONE", "TWO", "THREE", "FOUR", "FIVE"];
// function which will run
// on button click.
function Run() {
var url1 = "test.php?w1=" + arr;
var url2 = "test1.php?w1=" + arr;
var url3 = "test2.php?w1=" + arr;
url = [url1, url2, url3];
var iframes = document.getElementsByTagName("iframe");
for (var i = 0; i < iframes.length; i++) {
iframes[i].src = url[i];
}
}
</script>
</head>
<body>
<input type="button" id="upload" value="RUN" onclick="Run();" />
<iframe style='display:none;'></iframe>
<iframe style='display:none;'></iframe>
<iframe style='display:none;'></iframe>
<body>
</html>
Another method:
In your server you can include other 2 files to a file.
here I have included test1.php and test2.php in test.php
<?php
var_dump($_GET["w1"]);
include "test1.php";
include "test2.php";
?>
html:
<html>
<head>
<script type="text/javascript">
var arr = ["ONE", "TWO", "THREE", "FOUR", "FIVE"];
// function which will run
// on button click.
function Run() {
window.location.href = "test.php?w1=" +arr;
}
</script>
</head>
<body>
<input type="button" id="upload" value="RUN" onclick="Run();" />
<body>
</html>

How to reflect JStree changes to the original XML?

I'm using JStree to display an XML file, and after displaying it the user can create, rename, or delete some nodes, and sor sure these changes appear only on the displayed xml and not reflected on the original file, I want to know how to reflect this changes to the original XML fie back after clicking like a submit button, or at least how to get the data changed.
Update
The code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>menu-editor</title>
<script type="text/javascript" src="src/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="src/jstree/jquery.cookie.js"></script>
<script type="text/javascript" src="src/jstree/jquery.hotkeys.js"></script>
<script type="text/javascript" src="src/jstree/jquery.jstree.js"></script>
<link href="themes/!style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="src/jstree/!script.js"></script>
<script type="text/javascript" src="src/UIMTreeProcessor.js"></script>
<style type="text/css">
.
.
.
//css stuff
</style>
</head>
<body>
<div id="dummy"></div>
<div id="mylist">
<li id='root'><a href='#'>Root node</a><ul><li><a href='#'>Child node</a></li></ul></li>
</div>
<div id="submit" class="submit_btn">Submit</div>
</body>
<script type="text/javascript" class="source below">
var _url = "cafe.xml";
var _uimTree = null;
$(function () {
getTopContent();
});
getTopContent = function(){
$.ajax({
type: "GET",
url: _url,
dataType:"xml",
cache: false,
beforeSend:function(){
//do something before send
},
success: function(data){
processXML(data);
},
error:function(e){
alert("Error: "+e);
}
});
}
processXML = function(root){
_uimTree = new UIMTreeProcessor(root, $("#mylist"));
_uimTree.doProcess();
}
$('#submit').on('click',function(){
//alert the entire XML after edits via (getXML)
});
</script>
And the UIMtreeprocessor Library code
function UIMTreeProcessor(data, treeEl) {
this.data = data;
this.treeEl = treeEl;
}
UIMTreeProcessor.prototype.initTree = function(data){
this.treeEl.jstree({
"json_data" : {
"data":data,
"progressive_render":"true"
},
"plugins" : ["themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys","contextmenu"],
"core":{"animation":0}
});
}
UIMTreeProcessor.prototype.doProcess = function(){
//Find root:
var _root = $(this.data).children(':first-child');
var _a_feed = new Array();
this.vsTraverse($(_root), _a_feed);
var _treedata = [{"data":_root[0].nodeName,"children":_a_feed, "state":"open"}];
this.initTree(_treedata);
}
UIMTreeProcessor.prototype.vsTraverse = function(node, arr){
var _ch = $(node).children();
for(var i=0; i<_ch.length; i++){
var _vsArr = new Array();
this.vsTraverse(_ch[i], _vsArr);
var _a_att = this.vsTraverseAtt(_ch[i]);
if(null!=_a_att){
_vsArr.push([{"data":"Attributes "+"["+_ch[i].nodeName+"]","children":_a_att, attr : { "class" : "uim_attr"}}]);
}
if(null!=_ch[i].firstChild && 3==_ch[i].firstChild.nodeType){
arr.push([{"data":_ch[i].nodeName + ": " + _ch[i].firstChild.textContent,"children":_vsArr, "state":"open"}]);
}else{
arr.push([{"data":_ch[i].nodeName,"children":_vsArr, "state":"open"}]);
}
}
}
UIMTreeProcessor.prototype.vsTraverseAtt = function(node){
var _a_atts = null;
if(null!=node.attributes && node.attributes.length > 0){
_a_atts = new Array();
for(var i=0; i<node.attributes.length; i++){
_a_atts.push(node.attributes[i].nodeName + ":" + node.attributes[i].nodeValue);
}
}
return _a_atts;
}
Edit: I was really wrong in my original answer.
There is a get_xml method in the xml_data plugin, which is supposed to do what you describe. I have not tested it myself, but if it's anything like json_data.getJSON, the output will contain all kinds of JStree metadata which you will not want to put back into your XML.

Categories

Resources