passing data to a new html window - javascript

Sorry guys but this is a little broad, I've searched but there are a few things coming up but I wanted a direct answer for my question.
First I am a mechanic at a truck dealership in Dallas, TX. I am writing a web based application that will make it easier for me to organize all my jobs. I'm using this project to teach myself HTML, PHP, PDO, javascript ect. Right now I'm in design and organization phase meaning I'm getting everything I want figured out so when I start the hard coding I know ahead of time where to go.
Now when a tech logs in they will be brought to the tech landing page. I'm going to have a php script that will retrieve all the 20 most recent "active" Ro's (repair orders) assigned to that particular tech. A table will display summary info on a line at the end of each line there will be a button (or I might make the RO # clickable not sure yet.
My question is what is the best way to open a new window and pass the RO# of the clicked option so scripts on the new page can begin populating the detailed RO information from the database??
I'm not necessarily looking for the code but something I can search to narrow down my options.
Thanks

There are a few ways you could do this.
A simple link with querystring:
-------------------------------
<a href='/repairs.php?mechanic=bob' target='_blank'>Bob's Repair Orders</a>
<a href='/repairs.php?mechanic=curly' target='_blank'>Curly's Repair Orders</a>
A simple link with a javascript function:
-----------------------------------------
<a href='#' onclick='getRepairs('bob')'>Bob's Repair Orders</a>
<a href='#' onclick='getRepairs('curly')'>Bob's Repair Orders</a>
javascript:
function getRepairs(name){
window.open('/repairs.php?mechanic='+name );
}

You have 2 options to do this:
(Recommended) Pass RO# (id) in address page.php?id=1001 and fetch id using get method
on new page. It will be a full page with all bars and every thing
enabled.
Collect data in a DIV and open a new page and populate data to it.
Code for Option 1:
Page 1: ROlist.php (Which Contains list of 20 ROs)
RO#1001
Page 2: ROdetails.php (Which will open only id based details)
<?php
$ROid=$_GET['id'];
$result=mysql_query("SELECT * FROM table where id='$ROid'");
if($result)
{
while($list=mysql_fetch_array($result))
{
echo $list['Id'];
echo $list['clientName'];
echo $list['foo'];
echo $list['bar'];
}}
?>

You can call the following in JavaScript:
window.open("<yourUrl to open>?ro=someValue")
and pass the ro value to the new window as a query paramter (?ro=someValue where someValue will be replaced by the value to pass over and is the url of the page to load in the new window).
In the new window you can retrieve it using:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var ro = getParameterByName('ro')
Note: getParameterByName is from How can I get query string values in JavaScript?

Use a GET parameter : index.php?ro_id=1
Now this URL should be generated through PHP, where 1 is a variable and is the RO#.
Other solutions told how to open it in a new window, you don't need JS to read $_GET though.

Like what Uchiha comment is suggesting, you can put your RO# into a link.
In your html you can put something like this:
<a target="_blank" href="ro_table.php?ro_number=RO number here"> RO# </a>
and in your ro_table.php or any php file you prefer to receive the RO# you can get the RO# by: $_GET["ro_number"] and use that to your database query.

Related

Google Web App: Can't read or write on my label after evaluate the page

I have a label on my HTML page which shows number returned values. I can't read or change that when it is loaded? but locally I can do that with a console log.
<p name= 'message' id='ftext' > This team have
<label id="teams" > <?= teamSize ?> </label>
members. </p>
it returns null for both of these tag ids document.getElementById('team') or document.getElementById('ftext'), so I can't get their innerText or text Contents.
I am using HtmlService.createTemplateFromFile(file).evaluate() for rendering the page.
here is a link to my project: Attendance Form
Thanks for your help,
M
You said that document.getElementById('team') didn't work, but you actually named your id "teams".
If that fix doesn't work, can you share your code?
It's really frustrating to get variables between the frontend and the backend in GAS!
Something like this:
google.script.run
.withSuccessHandler(finishedOutput)
.withFailureHandler(errorOutput)
.split(); // SPLIT IS THE GS SCRIPT THAT PASSES BACK THE NUMBER YOU WANT
and then this
function finishedOutput(info) //INFO IS THE THING THAT GOT PASSED BACK BEFORE
{
var br='<br />';
var outputDiv = document.getElementById('status');
outputDiv.innerHTML = 'The spreadsheet has been split.' + br +'New files in this folder: ' + info.link + br ;
document.getElementById('process').style.display="none";
};
In my example I was passing back an object that had a info key but you can do this with a number or a string rather than an object.
these are both inside on the html page, and then the "split" function is on Code.gs and is a GAS function. Messy, right?

Scrapy: Modify rules for scraping web page

I've started to use scrapy for a project of mine to scrape data off a tennis website. Here is an example page that I want to scrape data off. As you can see, I want to scrape data for a tennis player. I need to recursively go through the entire page and gather 'Match Stats' (Theres a link titled 'Match Stats' next to every match) for a player's matches. I've already written code to parse data from the opened match stats popup. All I need to do now is open these match stats pages through the initial spider.
In all the examples I've read up on, we can write rules to navigate scrapy to the different urls that need scraping. In my case, I just want to write a rule to the different match stats links. However, if you saw the page I want to scrape, 'Match Stats' links are in the following format: javascript:makePopup('match_stats_popup.php?matchID=183704502'). As I've read online (I might be wrong!), scrapy can't deal with javascript and hence cant 'click' on that link. However, since the links are javascript popups, its possible to add the match_stats_popup.php?matchID=183704502 part of the link to the main url to get a standard html page:
http://www.tennisinsight.com/match_stats_popup.php?matchID=183704502
I am hoping I could modify the rules before scraping. In summary, I just want to find the links that are of the type: javascript:makePopup('match_stats_popup.php?matchID=183704502, and modify them so that they are now of the type http://www.tennisinsight.com/match_stats_popup.php?matchID=183704502
This is what I've written in the rules so far, which doesnt open any pages:
rules = (
Rule(SgmlLinkExtractor(allow='/match_stats_popup.php?matchID=\d+'),
'parse_match', follow=True,
),
)
parse_match is the method which parses data from the opened match stats popup.
Hope my problem is clear enough!
Using BaseSgmlLinkExtractor or SgmlLinkExtractor you can specify both the tag(s) from which to extract and process_value function used for extracting the link. There is nice example in the official documentation. Here is the code for your example:
class GetStatsSpider(CrawlSpider):
name = 'GetStats'
allowed_domains = ['tennisinsight.com']
start_urls = ['http://www.tennisinsight.com/player_activity.php?player_id=1']
def getPopLink(value):
m = re.search("javascript:makePopup\('(.+?)'\)", value)
if m:
return m.group(1)
rules = (
Rule(SgmlLinkExtractor(allow=r"match_stats_popup.php\?matchID=\d+",
restrict_xpaths='//td[#class="matchStyle"]',
tags='a', attrs='href', process_value=getPopLink), callback='parse_item', follow=True),
)
def parse_item(self, response):
sel = Selector(response)
i = TennisItem()
i['url_stats'] = response.url
return i

How to validate Stock Market data

Honestly, I am not an expert & right now very much confused about how to even state my problem...so please forgive my lack of knowledge and this long confusing question.
I was assigned a project today where the clients are displaying stock market's info on their page (image attached below). And when you click on any one of the buttons (for example, NASDAQ) more info is displayed in a pop-up box.
They are using onClick() to send the whole string to this third party to collect the data. Here is the HTML code for NASDAQ link:
<li>
<a href="#" onClick="open('https://app.quotemedia.com/quotetools/clientForward?symbol=^NASD&targetURL=http://app.quotemedia.com/quotetools/popups/quote.jsp?webmasterId=99944&locale=en_US','miniwin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=550,height=270,top=20,left=0'); return false;">
NASDAQ
<span id="imageNASDAQ"></span>
<span id="valueNASDAQ" class="share_value"></span>
<span id="textNASDAQ"></span>
</a>
<script type="text/javascript" src="/getStockInfo.php?Stocks[NASD]=NASDAQ"></script>
</li>
And then in getStockInfo.php file they are collecting the data as a JSON string and then parsing it. Here's how they are collecting the data:
<?php
if (array_key_exists("Stocks", $_GET)) {
foreach($_GET['Stocks'] as $symbol=>$stock) {
print file_get_contents("https://app.quotemedia.com/quotetools/jsVarsQuotes.go?webmasterId=99944&symbol=$symbol");
?>
So far pretty simple. But now the client wants to do some
"user input validation"
"Only accept 4 symbols: SP500, SPX, DOW & NASDAQ"
This is where I am getting confused. From their code (HTML part) looks like everything is hard coded (open('...symbol=^NASD...'); or open('...symbol=^SPX...'); or open('...symbol=^DJI...');) and each button/link is sending specific Stock symbol's info to the getStockInfo.php file (src="/getStockInfo.php?Stocks[NASD]=NASDAQ" or src="...Stocks[SPX]=SP500" or src="...Stocks[DJI]=DOW") where the stock quotes are being fetched. There is absolutely NO way my client's users can provide any other stock symbols through the site to change the display, the only way to manipulate the symbols are by changing the code itself.
BUT, my client wants to implement these above 2 conditions in the code anyhow. And I am not sure how to do this.
Not sure if I was able to explain my problem properly :( But I really need some help. Also I'm sorry for not being able to provide any link to the actual page here. Thank you so much for reading my confusing post and investing your time!! :)
Here's a proof of concept:
if (array_key_exists("Stocks", $_GET)) {
$stocks = array_filter($_GET['Stocks'], 'filterStocks');
foreach ($stocks as $symbol => $stock) {
print file_get_contents(…);
}
}
function filterStocks($symbol) {
return in_array(
$symbol,
array('SP500', 'SPX', 'DOW', 'NASDAQ')
)
}
Now getStockInfo.php will only return data for the four symbols. If you need that configurable on an individual user basis, a simple solution would be to do change the filterStocks function and callback to
function filterStocksForLoggedInUser($symbol) {
return in_array($symbol, getAllowedSymbolsForUser());
}
function getAllowedSymbolsForUser()
{
$permissions = include '/path/to/permissions/file.php';
return isset($permissions[$_SESSION['username']])
? $permissions[$_SESSION['username']]
: array();
}
}
and then in the permissions file put
return array(
'Walahh' => array('SP500', 'SPX', 'DOW', 'NASDAQ'),
'JohnDoe' => array('SP500', 'GOOG')
);
Note 1: the above assumes you have some sort of way to identify users, here $_SESSION['username']. Change that with whatever you are using and adjust the permission file accordingly.
Note 2: the permissions file will be read each time from disk. Disk I/O is usually slow, so you might want to consider moving the permissions to someplace faster.
Note 3: this is just a proof of concept. It's very pragmatic. You can certainly improve the design and structure, but I guess it's good enough to illustrate how to approach the problem.

Dumbed down Powershell web client function to let me post form data easily

Ive been using an Internet Explorer automation script found here:
http://www.pvle.be/2009/06/web-ui-automationtest-using-powershell/
That lets me easily post form data using commands (functions) like this:
NavigateTo "http://www.websiteURI/"
SetElementValueByName "q" "powershell variable scope"
SetElementValueByName "num" "30"
SetElementValueByName "lr" "lang_en"
ClickElementById "sb_form_go"
The above would let me post values to elements and click to submit the form.
I would like to do the equivalent with Powershell's web client using helper functions. I haven't found such a script. The closest I could find was The Scripting Guys, Send-WebRequest:
http://gallery.technet.microsoft.com/scriptcenter/7e7b6bf2-d067-48c3-96b3-b38f26a1d143
which I'm not even sure it does what I expect (since there's no working examples showing how to do what I want).
Anyway, I'd really appreciate some help to get me started to do the equivalent of what I showed up there with working examples (as simple as possible). A bonus would be to also be able to get a list of element names for a URI in order to know what form elements I want to submit.
PS: I also need to be able to specify user-agent and credentials; so, examples with these included would be ideal.
Have you taken a look at the Invoke-WebRequest commmand? (requires powershell 3.0 or above) I believe the following would work for submitting the data
#POSTing data
Invoke-WebRequest http://www.websiteURI/ `
-UserAgent 'My User Agent' `
-Credential $cred `
-Method Post `
-Body #{
q = 'powershell variable scope'
num = 30
lr = 'lang_en'
}
For your bonus, the result of Invoke-WebRequest contains a collection of the InputFields on the page, which you can use to get a list of form elements to set.
#List input elements
Invoke-WebRequest http://www.websiteURI/ | select -ExpandProperty InputFields

Adding new words to the game

In my spelling game new words will be added all the time so there is always a fresh selection of words to spell.
Each word added to the game has a "src" to an image and a sound that will prompts the user into getting the spelling correct in gameplay.
When I have completed making the game, the job of adding the new words in is down to one of my colleagues. This means he will have to add a link for the pic and audio as well as the word.
As they have little knowledge with this sort of thing I want to make it as easy as possible for him to add the images and sounds when adding the words I want to create a default path to a shared location where he will store all this stuff.
This way he can just type in "bug" for the word, ".bug-pic" for the picture and ".bug-audio" for the sound making it simple for him to add into the HTML.
Is this the best way to do it?
What would be the simplest way for them to input these things?
Here is how I store the word, sound and image at the moment...
<ul style="display:none;" id="wordlist">
<li data-word="mum" data-audio="file:///C:/smilburn/AudioClips/mum.wav" data-pic="http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
<li data-word="cat" data-audio="file:///C:/smilburn/AudioClips/cat.wav" data-pic="http://www.clker.com/cliparts/c/9/9/5/119543969236915703Gerald_G_Cartoon_Cat_Face.svg.med.png"></li>
<li data-word="dog" data-audio="file:///C:/smilburn/AudioClips/dog.wav" data-pic="http://www.clker.com/cliparts/e/9/4/1/1195440435939167766Gerald_G_Dog_Face_Cartoon_-_World_Label_1.svg.med.png"></li>
<li data-word="bug" data-audio="file:///C:/smilburn/AudioClips/bug.wav" data-pic="http://www.clker.com/cliparts/4/b/4/2/1216180545881311858laurent_scarabe.svg.med.png"></li>
<li data-word="rat" data-audio="file:///C:/smilburn/AudioClips/rat.wav" data-pic="http://www.clker.com/cliparts/C/j/X/e/k/D/mouse-md.png"></li>
<li data-word="dad" data-audio="file:///C:/smilburn/AudioClips/dad.wav" data-pic="http://www.clker.com/cliparts/H/I/n/C/p/Z/bald-man-face-with-a-mustache-md.png"></li>
</ul>
THANKS
I'm going to break your mold a bit here, and suggest something that looks simple enough for me in the long run (at least, simpler than what you have here).
The problems with using HTML markup to store your words is that:
it's HTML --- the browser will have to parse this, but then not display it because you've got the <ul> element as display:none (it's just sort of wasted effort), and
XML (or HTML, whichever) is pretty bloated, in the sense that there's a lot of text needed to represent information. If you're going for a spelling game, I'm assuming that you'll have hundreds, or thousands of such words, and the HTML representation for your words will be a huge crapload of bandwidth bloat.
So! Here's what I'd suggest:
// create an external JS file to store your words,
// let's say, [words.js].
// then let's just store your words in an array
var words = [
{ word : "foo" , audio : "file:///C:/smilburn/AudioClips/foo.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" },
{ word : "bar" , audio : "file:///C:/smilburn/AudioClips/bar.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" },
{ word : "mum" , audio : "file:///C:/smilburn/AudioClips/mum.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" }
];
It's just a plain Javascript array that holds a collection of Javascript objects. Each object has three properties: word, audio and pic.
Load that file into your page, and have a script read from that. It'll be much easier and faster to traverse, use and apply to your page. Reading to and fro a JS object is generally faster than having to parse and read the same information from the DOM.
Additionally, the markup is more compact, and you're not [misusing] HTML DOM for something it (arguably) wasn't supposed to be doing.
Thirdly, it's much more organized and cleaner to look at than HTML markup, and I imagine that that will be much easier for your colleagues to update and adapt to.
Lastly, one nice thing about this approach is how easy it is to write your code into modules, so you can work with stuff like expansions / word packs easier:
// something like this can work:
// [words.js]
var words = [
// some base words
{ word : "foo", audio : "foo.wmv", pic : "foo.pic" }
// ...
];
// [words.animals.js]
(function () {
// do not do anything if the base [words.js] isn't loaded
if (!words) { return; }
// extend the base words
words = words.concat([
// new animal words!
{ word : "dog", audio : "bark.wmv", pic : "brian.jpg" }
// ...
]);
})();
The idea being, you can load the words.js file into your game and it'll work perfectly. However, if the user would also like to add new words (say, words for animals) then they (you) can just load auxiliary files to augment your base words list.
This is much easier to do with JS objects than with HTML markup.
EDIT
If you really positively final-answer must have to use HTML, I recommend chopping off the data-word attribute off your <li> and just use it's text value instead.
<li data-audio="dog.wmv" data-pic="dog.jpg">dog</li>
I would recommend, that you simply store the info like this:
<li data-word="mum" data-audio="mum.wav" data-pic="/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
After reading your jsFiddle i would recommend you crate a playAudio function like this:
function playAudioFile (audioFileName) {
audioFileName = "http://www.wav-sounds.com/cartoon/" + audioFile;
$("#mysoundclip").attr('src', audioFileName);
}
after that you can replace this:
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.play();
by something like this:
playAudioFile(listOfWords[rndWord].audio);
You have to use attr() to store images in default location. Here they explain the default location to store images.
You might want to consider what server side technology you'll have available too.
If you have to add the options through html, then what you can probably do in that portion of the page, is have the html elements generated dynamically by the server.
'ASP Classic example
<%
set fs = server.createObject("scripting.filesystem")
set folder = fs.getFolder("your path here")
for each file in folder.getFiles("*.wav")
strWord = left(file.name, length(file.name)-4)
%><li data-word="cat"
data-audio="path/to/folder/<%=strWord%>.wav"
data-pic="path/to/folder/<%=strWord%>.png"></li>
<%
next
%>
This is just an asp classic example, I'm sure you'll find others out there specific to the platform your using.
But basically... you have to have SOMETHING on the server tell the output page what is available if you want to make it a drop-in-and-go operation. Otherwise you might as well be doing the html as you have been. Technology isn't always going to replace plain ol data entry.
Well, in my opinion, you can use a database, a server side script and a form for your colleague. Create a form which he will use to upload the information to the server and store the paths into the database.
The form:
<form method="POST" action="myscript.php" enctype="multipart/form-data">
<p>Word:<input type="text" name="my-word" id="my_word"></p>
<p>Audio:<input type="file" name="audio" id="my_audio" /></p>
<p>Picture:<input type="file" name="picture" id="my_picture" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The script:
<?php
$conn = mysql_connect("your_host", "your_user", "your_pass") or die (mysql_error());
mysql_select_db("your_database", $conn) or die (mysql_error());
if( ( $_FILES[ 'audio' ][ 'error' ] > 0 ) || ( $_FILES[ 'picture' ][ 'error' ] ) ){
echo "Error" . "<br />";
}
else{
move_uploaded_file($_FILES["audio"]["tmp_name"], "your/upload/directory/for/audio/" . $_FILES["audio"]["name"]);
move_uploaded_file($_FILES["picture"]["tmp_name"], "your/upload/directory/for/images/" . $_FILES["file"]["name"]);
mysql_query( 'INSERT INTO your_table ( word, audio, image ) values ( "' . $_POST[ 'word' ] . '", "' . $_FILES[ 'audio' ][ 'name' ] . '", "' . $_FILES[ 'picture' ][ 'name' ] . '" )', $conn );
}
?>
Of course your database should have a table which stores those 3 values plus some id.
I think you can add more entries to a list like this in javascript:
function addLI(id){
var Parent = document.getElementById(id);
var NewLI = document.createElement("LI");
NewLI.innerHTML = "this is a test";
Parent.appendChild(NewLI);
}
which I found from here: http://bytes.com/topic/javascript/answers/520885-add-new-list-item
I recommend having input fields with the name, location and picture for your friend to add more entries with, then use something like this js function to add a new child entry.
If you have access to a server with PHP, I would suggest putting all them items in a array and then looping through them.
I have written an example here:
<?php
$wordsArray = array(
array('word'=> 'randomword' , 'audio' => 'test.mp3', 'picture' =>'pic.jpg'),
array('word'=> 'randomword2' , 'audio' => 'test2.mp3', 'picture' =>'pic2.jpg')
);
$html = '';
foreach($wordsArray as $word){
$html .= '<li data-word="'.$word['word'].'" data-audio="'.$word['audio'].'" data-pic="'.$word['picture'].'"></li>';
}
?>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<?php echo $html; ?>
</ul>
</body>
</html>

Categories

Resources