Send data over to another html file - javascript

I am trying to get certain data from my database on my (1) HTML page and display it on the (2) HTML page.
My codes for (1) html file:
<html>
<head>
<script src="example.js"></script>
</head>
<body>
.
.
.
<button item="' + count + '" onclick="getData(this)">Example</button>
.
.
.
</body>
</html>
And the JS for it:
.
.
.
var currentIndex = 0;
//This function is to display the details of an individual item
function getData(element) {
var request = new XMLHttpRequest();
request.open("GET", "/theroute", true);
request.setRequestHeader("Content-Type", "application/json");
request.onload = function () {
var example = JSON.parse(request.responseText);
var item = element.getAttribute("item");
currentIndex = item;
document.getElementById("data1").textContent = example[item].name;
document.getElementById("data2").src = example[item].age;
}
request.send();
}
.
.
.
I want to get these data in my (2) HTML page (for example):
<html>
<head>
<script src="example.js"></script>
</head>
<body>
<h4 id="data1"></h4>
<h4 id="data2"></h4>
</body>
</html>
I saw this Get data from one html file and display it using another html file, but I'm not sure how to use this for my case here.
Sorry, I am new to this, so giving a detailed explanation for your solution would be very helpful. I am using vanilla JS only so please no jQuery. Any help would be appreciated

I hope this might prove of use to you. The button(s) have had the custom item attribute replaced with the dataset equivalent to ensure the html is valid. Normally I'd suggest also using external event handlers rather than adding onclick=getdata() to the elements inline but for brevity here they remain.The function, when invoked by clicking a button, will construct the relevant querystring to send to the endpoint ( for you it would be /theroute?id=X&name=Y&age=Z etc ) which queries the database and sends the response back. The response is used to generate the menu of hyperlinks which take the user to page 2 when clicked. I think this is what you were trying to explain. You could copy the entire code and create a new page to see in action.
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['item'] ) ){
ob_clean();
/*
emulate "/theroute" and send some data back to the ajax callback.
This data would really be fetched from the database but below is
simply randomly generated data for display/test purposes.
*/
$payload=[];
$item=$_GET['item'];
for( $i=0; $i < 10; $i++ ){
$payload[]=[
'id' => $i,
'name' => 'Geronimo '.uniqid().' '.$item,
'age' => mt_rand(16,80)
];
}
exit( json_encode( $payload ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
function getData( e ) {
var xhr = new XMLHttpRequest();
var ul=document.getElementById('menu');
/* The above PHP code is to emulate the real endpoint /theroute */
xhr.open( "GET", location.href +'?task=fetch&item='+e.target.dataset.item, true );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = function() {
var json = JSON.parse( xhr.response );
json.forEach(obj=>{
var id=obj.id;
var name=obj.name;
var age=obj.age;
var li=document.createElement('li');
li.appendChild( createhyperlink(id,name,age) );
ul.appendChild( li );
});
}
xhr.send();
}
function createhyperlink(id,name,age){
var a=document.createElement('a');
a.href='page2.html?id='+id+'&name='+name+'&age='+age;
a.innerHTML='View '+name;
return a;
}
</script>
</head>
<body>
<ul id='menu'></ul>
<?php
for( $i=1; $i <=10; $i++ ){
echo "<button data-item='{$i}' onclick='getData(event)'>Example #{$i}</button>";
}
?>
</body>
</html>

Related

Pass div id into PHP variable

I have passed a javascript variable into a div id element in HTML. I am now trying to send that div id to a php variable so I can access it.
However, when I try a POST request it is not grabbing what is assigned to div id. Any help is appreciated, thanks.
<?php
session_start();
$un = $_POST["result"];
echo "the username is". $un;
?>
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
if (typeof(Storage) !== "undefined")
{
var getUser = document.getElementById("result").innerHTML = sessionStorage.getItem("username");
}
else
{
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
First of all, to make a post request you'll need to be using XMLHttpRequest. You really should be using a GET request in a separate file, though.
PHP file, named getId.php:
<?php
session_start();
$_SESSION["id"] = $_GET["id"];
?>
JavaScript code, to retrieve data:
var getData = function( url, callback ) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr);
};
xhr.open( "get", url, true );
xhr.send();
};
getData('./getId.php?id=' + /* id goes here */, function(json){
if(json.status == 200){
data = json.response;
//Do something with data...
}
})
And finally, to reference the session data, back in the HTML file:
<?php
session_start();
echo "value of username is: " . $_SESSION["id"];
?>

Echoed Javascript Code from PHP Via AJAX Not Running

My code is meant to get the author of an inputted book using the Google Books API via AJAX. If nothing is inputted it prints "Empty". What it actually does is print out the Javascript code when a book is inputted. When nothing is inputted, it prints "Empty" as it should. How could I modify my code to make the echoed Javascript execute and hence get the author of an inputted book?
Just to see, I replaced the echo part with echo "<script>document.getElementById('txtBox').innerHTML = 'Hello';</script>";. It also prints out the javascript code, so I don't think it has something to do with using the API.
getAuthor.html
<!DOCTYPE html>
<html>
<body>
<!-- Input -->
<div class="form">
<form onsubmit="makeRequest(); return false">
<input type="text" id="inputText" name="inputText">
<input type="submit">
</form>
</div>
<br>
<!-- Output -->
<div class="txtBox">
<textarea id="txtBox">
</textarea>
</div>
<!-- AJAX to create output using jEcho.php file-->
<script>
function makeRequest() {
httpRequest = new XMLHttpRequest();
console.log(httpRequest.responseText);
httpRequest.onreadystatechange = function() {
document.getElementById("txtBox").innerHTML = httpRequest.responseText;
};
httpRequest.open("POST", "jEcho.php", true);
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpRequest.send("inputText=" + document.getElementById("inputText").value);
}
</script>
</body>
</html>
jEcho.php
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>
<script src='$scriptSource'></script>";
}
?>
Links
Echoing Javascript From PHP:
How to call a JavaScript function from PHP?
Echoing javascript from PHP
Google Books API:
https://developers.google.com/books/docs/v1/getting_started
https://developers.google.com/books/docs/v1/using
<script> elements are only run when your page is first loaded. Script elements created later on, either by assigning to an element's .innerHTML, creating them using document.createElement(), or otherwise, are not executed.
If you want to have a PHP script send back code to be evaluated, you'll have to do that directly, e.g:
httpRequest.onreadystatechange = function() {
eval(httpRequest.responseText);
};
(And remove the <script> tags from the response.)
Try setting header in jEcho.php file (not tested)
header('Content-Type: application/javascript');
I'm not allowed to comment so:
I'm not certain what has caused it for but could <script src='$scriptSource'></script>"; be called before the handleResponse function. I'm not too sure what is causing it, at the moment, that is my best idea.
Also could you not just have the url already in the code like this: (jEcho.php)
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
//$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "
<script src='https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse'></script>
<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>";
}
?>

Click counter when link is clicked PHP/JS

I have a little script here that counts clicks when link is clicked and stores it in .txt file, but it works fine when I have only "click=yes" under href. But I can't make it to track clicks when I have link to external site.
Here is my code:
<?php
if(!file_exists('counter.txt')){
file_put_contents('counter.txt', '0');
}
if($_GET['click'] == 'yes'){
file_put_contents('counter.txt', ((int) file_get_contents('counter.txt')) + 1);
header('Location: ' . $_SERVER['SCRIPT_NAME']);
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>counter example</title>
</head>
<body>
<h1><?php echo file_get_contents('counter.txt'); ?></h1>
clickMe
</body>
</html>
My guess is it has to do something with header('Location: ' . $_SERVER['SCRIPT_NAME']); but I can't figure it out so I could really use some help.
And is it somehow possible to have multiple links save to the same file, and when I show it on website it's sorted from largest number to smallest? I have an idea how to do it with MySQL database but I can't use it at place where this will be implemented.
Thanks in advance!
Cheers!
Your server never sees the URI being accessed as the client leaves your page. To do something like this, it may be best to set up a redirect which works like this
click me
(Make sure the external site's URL is URL encoded as you're passing it as a GET component of a URL to your own page)
Then in goto.php you store your click and send a redirect header
if(!file_exists('counter.txt')){
file_put_contents('counter.txt', '0');
}
file_put_contents('counter.txt', ((int) file_get_contents('counter.txt')) + 1);
header('Location: ' . $_GET['href']);
Now you can track these clicks, you can add your domain-specific counters in goto.php instead of your text file
You could use Javascript to catch click on a link , send data via AJAX call. Here is small sample using JQuery.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(
function() {
$('a').click(linkClicked);
}
);
//this funciton will be called on every click on any link on page
function linkClicked() {
var url = $(this).attr('href');
//call PHP script to save URL ./saveurlclicks.php?url=CLICKEDURL
$.get('./saveurlclicks.php', {'url': url})
//be sure to return true so user can navigate further
return true;
}
</script>
</head>
<body>
<a href='/some href' >asasa</a>
<a href="www.google.com" >google</a>
</body>
</html>
<?php
//saveurlclicks.php
// here we save links in file but using serialized array
// if you need to get count of links clicked ,
// have a second script that unserializes array and sort it in revers order
$url = #$_GET['url'];
$counterFile = 'counter.ser';
if ($url) {
if(file_exist($filename))
$links = unserialize(file_get_contents($filename));
else $links=array();
if (!isset($links[$url])) {
$links[$url] = 0;
}
$links[$url] ++;
file_put_contents($counterFile, serialize($links));
}
I love the simple solution by Paul S., but if you want to track the clicks with date, you can do something like this:
03/03/2022 14
04/03/2022 2
<?php
$dateexists = false;
if(!file_exists('counter.txt'))
{ $fh = fopen('counter.txt', 'w');
fclose($fh); }
$datecounts = file('counter.txt', FILE_IGNORE_NEW_LINES);
foreach($datecounts as $key => $datecount){
list($date, $count) = explode("\t", $datecount);
$count = (int) $count;
if($date == date('d/m/Y'))
{ $datecounts[$key] = $date."\t".++$count;
$dateexists = true; }
}
if(!$dateexists)
{ $datecounts[] = date('d/m/Y')."\t1"; }
$fh = fopen('counter.txt', 'w');
if (flock($fh, LOCK_EX)) {
foreach($datecounts as $datecount)
{ fwrite($fh, $datecount.PHP_EOL); }
flock($fh, LOCK_UN);
}
else
{ //couldn't lock, might want to do stuff here }
fclose($fh);
header('Location: ' . $_GET['href']); // the redirect
?>

Auto fill form input fields from database using AJAX

Can't get this to work and could use an extra pair of eyes to find what I'm doing wrong or what might be missing. I created a form using the RSForm Pro component for Joomla 3.3.1. The purpose of the form is to allow a user to file warranty claims on our products. If a user needs to file a repeat claim on a product then an input field is displayed with a button to retrieve data from the database and auto fill the owner's info for the user. For every claim submitted an "id" is generated. This "id" is the number the user should be entering to retrieve data if needing to submit a repeat claim. I have an ajax function that runs onclick and looks for a php file that connects to the database and retrieves the requested info.
Here is the ajax...
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateOwnerInfo()
{
if (ajax)
{
var idValue = document.getElementById("owner_id").value;
if(idValue)
{
var url = "/templates/uma-solar/html/com_rsform/getClaimInfo.php";
var param = "?id=" + escape(idValue);
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
ownerarr = ajax.responseText.split(",");
var owner_name = document.getElementById('owner_name');
var owner_address = document.getElementById('owner_address');
var owner_city = document.getElementById('owner_city');
var owner_state = document.getElementById('owner_state');
var owner_country = document.getElementById('owner_country');
var owner_county = document.getElementById('owner_county');
var owner_zip = document.getElementById('owner_zip');
var owner_phone = document.getElementById('owner_phone');
var owner_email = document.getElementById('owner_email');
owner_name.value = ownerarr[0];
owner_address.value = ownerarr[1];
owner_city.value = ownerarr[2];
owner_state.value = ownerarr[3];
owner_country.value = ownerarr[4];
owner_county.value = ownerarr[5];
owner_zip.value = ownerarr[6];
owner_phone.value = ownerarr[7];
owner_email.value = ownerarr[8];
}
}
Here is the php...
define( '_JEXEC', 1 );
define('JPATH_BASE', '/var/www/joomla.umasolar.com/');
/* Required Files */
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
/* To use Joomla's Database Class */
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
/* Create the Application */
$app = JFactory::getApplication('site');
$app->initialise();
//-----process DB query-------
$db = JFactory::getDBO();
$sql='SELECT
owner_name,
owner_address,
owner_city,
owner_state,
owner_county,
owner_country,
owner_zip,
owner_phone,
owner_email
FROM #__rsform_warranty_claim WHERE _id=mysql_real_escape_string($_GET[
"owner_id"])';
$db->setQuery($sql);
//----------------------------
$row = $db->loadObjectList();
echo $row['owner_name'] . ", " . $row['owner_address'] . ", " . $row['owner_city'] . ", " . $row['owner_state'] . ", " . $row['owner_country'] . ", " . $row['owner_county'] . ", " . $row['owner_zip'] . ", " . $row['owner_phone'] . ", " . $row['owner_email'];
The form is not public so here are a couple screenshots that might be useful...
And here is the text that is filling in the input fields which just appears to be a 404, but in the title it shows 1064 - Error: 1064...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr">
<head>
<title>1064 - Error: 1064</title>
<link rel="stylesheet" type="text/css" href="/templates/uma-solar/html/com_rsform/templates/uma-solar/css/style.css" />
<link rel="stylesheet" type="text/css" href="/templates/uma-solar/html/com_rsform/templates/uma-solar/bootstrap/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="/templates/uma-solar/html/com_rsform/templates/uma-solar/bootstrap/css/bootstrap-responsive.css" />
<script type="text/javascript" src="/templates/uma-solar/html/com_rsform/templates/uma-solar/bootstrap/js/bootstrap.js"></script>
</head>
<body class="error">
<center>
<div class="errorbox">
<div class="block">
<h1>404</h1>
<h3>Page not found</h3>
</div>
<p>Sorry! The page you are looking for cannot be found. Please use the provided search box to find what you are looking for
There are no errors generating in the error log with this code. Had some issues figuring out the correct path to the required Joomla files in the PHP code, but it appears I fixed that issue. Any and all help would be greatly appreciated!
Finally got it working after following Joomla's instructions on selecting data using JDatabase. I'm sure this can work using standard SQL statements, but Joomla can be picky sometimes and it's just easier to follow their rules. The AJAX was fine, but here's what I changed the PHP to...
define( '_JEXEC', 1 );
define('JPATH_BASE', '../../../../');
//Required Joomla Files
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
//Connect to Joomla's Database Class
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
//Create the Application
$app = JFactory::getApplication('site');
$app->initialise();
$input = $app->input;
$id = $input->getInt('id');
//Connect to db
$db = JFactory::getDBO();
//Create new query object
$query = $db->getQuery(true);
$query->select($db->quoteName(array('owner_name', 'owner_address', 'owner_city', 'owner_state', 'owner_county', 'owner_country', 'owner_zip', 'owner_phone', 'owner_email')));
$query->from($db->quoteName('#__rsform_warranty_claim'));
$query->where($db->quoteName('_id') . '=' . $db->quote($id));
//Reset the query using our newly populated query object
$db->setQuery($query);
//Get a single record from the DB table
$row = $db->loadAssoc();
echo $row['owner_name'] . ", " . $row['owner_address'] . ", " . $row['owner_city'] . ", " . $row['owner_state'] . ", " . $row['owner_country'] . ", " . $row['owner_county'] . ", " . $row['owner_zip'] . ", " . $row['owner_phone'] . ", " . $row['owner_email'];

jquery post variable shows in html but not php

I'm not sure if it's just me or what but this seems really odd. When I click a button I have jquery send out javascript variables to a php site to be handled there. However on the php site they come up as undefined indexes. The weird part, is that they show on the html page through php's echo. NOTE: The html button is an input type="button", not a submit because I don't want to reload the page.
jquery:
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
php:
//used for troubleshooting, returns Array() on the php page and Array ( [posttimestampst] => 1399973296 [postobjNamest] => test2-1
print_r($_POST);
//when the if and else are used it the php page always echos Not Working, meaning that the $_POST is not set somehow. However, the html page shows the echoed variables in the "divResult" as it should.
//when I try the code without the if and else, the php page returns Undefined Index: posttimstamp/postobjNamest. However, the html page still shows the echoed variables.
if(isset($_POST["posttimestampst"])){
$timestamp = $_POST["posttimestampst"];
echo $timestamp;
echo "<br>";
$objName = $_POST["postobjNamest"];
echo $objName;
echo "<br>";
}
else{
echo "Not Working";
}
Any help is greatly appreciated!
EDIT:
//gets selected object from a dropdown menu
selectedObj = document.getElementById("selectObj").value;
//objName in javascript taken from $objName var in php that is and the beginning of the html page.
objName = <?php echo json_encode($objName); ?>;
//objInst takes the value of the dropdown menu and assigns it as the [] in objName array
objInst = objName[selectedObj];
//timestamp is set in php and imported to java
var timestamp = <?php echo $timestamp; ?>;
EDIT 2:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js""> </script>
</head>
<h3>Optionen und Berechnen</h3>
<form name="myForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div id="divCalc">
</div>
<input id="addObject" type="button" onclick="addObj()" value="Add Object">
<br>
<br>
<div id="divAddObj" hidden="true">
</div>
<br>
<div id="divCalc">
</div>
<div id="divResult"></div>
</form>
<script type="text/javascript" name="addObject">
var objName;
var selectedObj;
var objInst;
var timestamp = <?php echo $timestamp; ?>;
//Start select dropdown
var select_element = document.createElement("select");
select_element.setAttribute("id", "selectObj");
select_element.setAttribute("name", "selectObject");
options = new Array();
objName = <?php echo json_encode($objName); ?>;
for ( var i = 0; i < (<?php echo $arrayNum; ?>); i++ ){
options.push(new Option(objName[i], i, false, false));
}
options[0].selected = true;
for ( var option in options ){
select_element.appendChild(options[option]);
}
//End select dropdown
//check selected object
selectedObj = document.getElementById("selectObj").value;
objInst = objName[selectedObj];
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
</script>
Change your code to:
objNamest = objInst.value;
timestampst = timestamp.value;
$.post("sendCalc.php", {
postobjNamest: objNamest,
posttimestampst: timestampst },
function(data){
$("#divResult").html(data);
});
You are missing the data parameter of $.post().
From the docs about post():
data
Type: PlainObject or String:
A plain object or string that is sent
to the server with the request.
Your params postobjNamest & posttimestampst do not exist for the $.post() method
It should be
$.post("sendCalc.php", {
// An "on-the-fly" created JavaScript object, which is valid
data: {
postobjNamest: objInst,
posttimestampst: timestamp
},
function(data){
var content = $.parseJSON(data);
window.console.log(content.postobjNamest);
window.console.log(content.posttimestampst);
}
});
From the docs about parseJSON():
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
And in the PHP:
$objName = $_POST['postobjNamest'];
$timestamp = $_POST['posttimestampst'];
// Returning your values to client
// Don't echo them in PHP
echo json_encode(array(
'postobjNamest' => $objName,
'posttimestampst' => $timestamp
);
From the docs about json_encode():
json_encode — Returns the JSON representation of a value
The Javascript Object:
// Declaration
var Obj = {
propertyOne: 'value', // string
propertyTwo: 52.3654, // float
methodOne: function () {
// your function code
},
methodTwo: function () {
// your function code
}
}
//Instances
var objOne = new Obj();
objOne.methodOne();
objOne.propertyTwo;
var objTwo = new Obj();
objTwo.methodOne();
objTwo.propertyTwo;

Categories