adding a php function into javascript - php

I have a file for a calendar made with javascript called calendar_db.js, in it there is this if statment:
if (d_current.getDay() != 3 && d_current.getDay() != 6)
a_class[a_class.length] = 'available';
it checks if the day is not the 3d or the 6th then. So my question is how to make a php mysql query to get those numbers (3 and 6) because I want to change them with mysql databse.
What are your suggestions?
Thank you for your time and help.

The short answer is:
You can't
However, you can use Ajax (Google it) to make calls to an external php file, which will process your request for you. Then, the php file can print out the result, which will send the information back to you.
Take a look here:
http://www.w3schools.com/ajax/default.asp

EDIT:
Read the javascript file by using fopen(), file_get_contents(), or CURL:
http://www.php-mysql-tutorial.com/wikis/php-tutorial/reading-a-remote-file-using-php.aspx
Use some kind of regex to parse the javascript file looking for the particular match of the line with your values. If your javascript file isn't going to change much, it might be easier to just count lines and characters and get the number at exactly some position. This assumes your numbers will always be single digits.
Is this what you're after?

You have to use AJAX to interact with the server via JavaScript.
Since the code to setup an AJAX request is a bit long and tedious, I'll show you how to do it with the jQuery framework.
Basically, just make the server spit the two values out (imagine this being the output of foo.php):
12,19
Now, with AJAX you can read that output. There are two types of requests: GET and POST. If you're familiar with PHP, you can change this according to what your application uses:
var day1, day2;
$.get('foo.php', function(data) {
var split = data.split(',');
day1 = parseInt(split[0]);
day2 = parseInt(split[1]);
});
Now day1 and day2 hold your two dates.

Related

I want to do arithmetic on a returned set of SQL values

I am successfully executing a query on an SQL database.
$sql = "SELECT id, scdTempC, scdRH, ..., gt1pt0um, reading_time FROM Sensor order by reading_time desc limit 96";
Then, there is this and I don't know, at all, what it is doing.
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
It returns a set of 96 values for each column selected. Those go into a HighCharts chart for presentation in a browser.
Then, there is this and I have no idea, at all, what it is called or what it is doing:
var scdTempC = <?php echo $scdTempC; ?>;
var scdRH = <?php echo $scdRH; ?>;
var bmeBP = <?php echo $bmeBP; ?>;
And those vars feed into the HighCharts code:
series:
[{
marker: { symbol: 'dot' }, showInLegend: false,
name: 'SCD41 Temp', data: scdTempC
}],
Is there any way to get to the individual values and do arithmetic on them? Specifically, adjust centigrade temperature to Fahrenheit or Barometric pressure in hPa to inches of Mercury. Yes, I could add another column and feed in °F or inHG, but that seems wasteful if I can adjust the numbers on the fly. The result would need to look like what came from SQL and, as far as I know, that is a CSV string of numeric values. This is being done in a .PHP file. I don't know PHP yet. If this is too crazy or complicated, then just say so and I will go the other way with adding another column of data. Maybe it is SQL that I need, not PHP. Sorry, a bit lost and it shows!
It seems like I would use "foreach" and loop through the original list making up a new list with the same format (CSV?) and adjusted values. Is that even close?
I am a long-time programmer having worked with at least 12 languages but very new to PHP and SQL. Just started working with it inside an existing project a week ago and needing some pointers for modifying it. I have done a lot, already, but got stuck, here. Since I am jumping into the middle of this, it is difficult to even know what to search for. Search hints would be gladly accepted. THANKS for any help!!!
Mike
These lines appear to be the most important for you
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
Since you say that the numbers are feeding through to the HighCharts configuration, the above must be working fine.
What the above is doing, is that each line is converting one column of the database query results into a JSON array that can be used in the JavaScript.
Since you say you have little experience in PHP, but you do have experience in SQL, I recommend you stick to what you know and use the SQL for the arithmetic. That way you have one less problem to work on, and you can concentrate on just getting that data to the chart.
What you're asking to do is quite basic, and beyond the scope of a single answer here - the short answer is that you really need to read or watch a PHP tutorial, sorry! But since you say you've used 12 languages, you should find it easy to pick up - PHP is very much like most other C-like languages, so you should not have a problem catching on.
A clue: when you want to know what a PHP function does, just put it after "https://php.net/" in a browser. example: https://php.net/array_column
It’s important to recognize that there are 4 languages in play here: SQL, PHP, HTML, and Javascript.
In a script using best practices, you will see PHP on the top, doing all the logic and data collection/manipulation (SQL calls). Under that, you’ll see a PHP close tag (?>) followed by HTML with embedded Javascript. PHP looping, conditionals, and variable substitution are accomplished as seen here:
<?php
// work with user input
// get sql stuff
// work with sql results
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
// send output to browser
?>
<html>
… snip …
<!-- simple looping example; there are other ways to do it -->
<ul>
<?php foreach($rows as $row) { ?>
<li><?php echo $row; ?></li>
<?php } ?>
</ul>
… snip …
<!-- now starts javascript -->
<script>
// note the javascript is not running yet; we are filling in values from PHP
// The javascript will run in the browser after PHP serves it
var scdTempC = <?php echo $scdTempC; ?>;
var scdRH = <?php echo $scdRH; ?>;
var bmeBP = <?php echo $bmeBP; ?>
// more javascript
// your solution is down here somewhere. While iterating through the array,
// make a call to the appropriate javascript converter function to translate
function toFahrenheit(celsius)
{
return celsius * 9 / 5 + 32;
}
function toCelsius(fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
</script>
Here’s the important part for you: the javascript is not executed on the server, it’s executed in the browser after the php has finished and sent its output.
It appears that you are passing an array to javascript, which is then creating the desired output.
The solution then would be to create a function in javascript to convert to the desired unit of measure, as javascript is creating its output.
My advice is to concentrate on the javascript and solve the problem there.

VBScript find text in HTML

I am trying to use VBS to gather names of files from a website. I can get the HTML code but I don't know how to extract the name. I haven't yet found anything that can do what I need. I need to extract the name of a file from a table. The HTML around what I need looks like this tsc_details.php?show_id=NEEDED INFO"> There are many different names formatted this same way and the number of names will vary from time to time.
NOTE: There will be multiple of these at various places in the HTML code.
Here is my code
On Error Resume Next
Set ie = CreateObject("InternetExplorer.Application")
ie.Navigate "WWW.Webpage.com"
ie.Visible = True
While IE.ReadyState <> 4 : WScript.Sleep 100 : Wend
ie.document.getElementById("f_user").Value = "user"
ie.document.getElementById("f_pass").Value = "pass"
ie.document.All.Item("submitb").Click
While IE.ReadyState <> 4 : WScript.Sleep 100 : Wend
This is all of the code I have. It works perfectly for logging in to the page I just don't know how to get the Information I need.
Figured it out and wanted to share my findings in case it helped someone out.
For Each a In IE.Document.GetElementsByTagName("A")
If InStr(a.GetAttribute("href"),"tsc_details.php?show_id=") > 0 Then
var = a.GetAttribute("href")
var = Replace(var,"tsc_details.php?show_id=","")
exit for
end if
next
Used this code

Why isn't a .post and .html call able to compare in an if(condition) in jQuery?

The following script has been created to test if the value of a db field has changed and if so then reload the page and if not, alert the user that the change has not happened.
The alert is just to see what is being returned by the .post function.
The auto_refresh works fine as i need it to check every 5 seconds, when the if() condition is set to '==' the page alert shows and if it is set to '!=' the page continually reloads.
jQuery.post is getting the db field data but it doesn't seem to be able to compare the 2 values correctly.
any help would be greatly appreciated, thanks
var auto_refresh = setInterval(function(){
$.post("/index.php/listen", function(data) {
if($('#slide').html() != data)
{
window.location.reload()
}
else
{
alert('its the same'+ data);
}
});
}, 5000);
EDITED
Rather than trying to parse raw data, why not pass HTML from the $.post() like:
<p>4</p>
Then the jQuery inserts the the replaces the p tag with the new version from the $.post()
because the html is passed on there is no white space and the comparison can be made correctly.
I don't think it is very safe to compare the new value with an html. Some browsers might add spaces or unwanted chars. I'd try to save the old value in an input of type hidden and use the .val() or, event better, in a variable. It depends of your scenario.
If $('#slide').html() == data
then that means that the conditional failed, it was not equal, so it showed the alert.
The problem is that the data variable might come back with a few extra white spaces. If I were you, I'd try to parse a small section of the data variable, and a small section of the html in slider and compare those values.
Like if slider has something within a p tag or an input value, compare it to the data to see if it has that same value returned in that p tag or input value, then replace all the whitespaces with an empty string just to be safe.
Btw, try not to use alerts since you can't really know for sure if there is an extra whitespace. Try to use something like "debugger" if using IE with visual studios, or console.log when using chrome or firefox.
You are comparing two html strings: one is serialized from the DOM, and another is from a server response.
There's no guarantee that the two strings will ever be the same! Think about it: the same rendered html can have many string differences. E.g. click and click are both the same HTML, but different strings.
You can take two different approaches here:
You can create some kind of canonicalization routine that guarantees that two html fragments you consider "the same" will have the same string form. Run both html fragments through this routine, then compare.
You can manage versions more explicitly.
Include some kind of version indicator:
You can use the ETAG header (which means you can take advantage of http caching mechanisms).
You can include some kind of version number in the html itself (maybe in a data-version attribute), and compare those.
You can keep the html string from your server separately and compare against that.

Select text from a specific table cell on another page?

I have a weird question. I want to create script in javascript (or PHP if I have to, I'm just more comfortable in javascript) that reads through a table until it finds specific text (know how to do that) and then returns the text three cells to the right.
To be specific, I want a script that finds a row for a specific printer on this site and returns the printer's status. I know how to select unique text, but not so much about nonunique text.
Try this
$('.epi-dataTable tr:gt(0) td:first-child:contains("printerName")')
.closest('tr').find('td:eq(4)').text();
var printerName = 'yourname',
status = $(':contains(' + printerName + ')').siblings().eq(2).text();
If I understood your question correctly, this is how you could do it using jQuery:
$("td").filter(function() {
return $(this).text() === yourSeachText;
}).next().next().next().text();
Clarifying: the filter function will select only the column whose text equals your search text, and each call to next will return the column's next sibling - another td. Three calls later, you have the column you want, so you can get its text.
Update: you might also be interested in this question, if the site you're querying is not in the same domain as your script. If it is, you can simply load its contents to a div before querying it:
$("#placeholder").load("http://clusters.andrew.cmu.edu/printerstats/", function() {
// The contents were loaded to #placeholder, do your query here
});
If it's not, then you'll have to load that html data somehow, and according to an anwser to that question, your best route is really to do it in PHP (or at least use it to echo the other site's contents to your own).

Is there a php function for using the source code of another web page?

I want to create a PHP script that grabs the content of a website. So let's say it grabs all the source code for that website and I say which lines of code I need.
Is there a function in PHP that allows you too do this or is it impossible?
Disclaimer: I'm not going to use this for any illegal purposes at all and not asking you too write any code, just tell me if its possible and if you can how I'd go about doing it. Also I'm just asking in general, not for any specific reason. Thanks! :)
file('http://the.url.com') returns an array of lines from a url.
so for the 24th line do this:
$lines = file('http://www.whatever.com');
echo $lines[23];
This sounds like a horrible idea, but here we go:
Use file_get_contents() to get the file. You cannot get the source if the web server first processes it, so you may need to use an extension like .txt. Unless you password protect the file, obviously anybody can get it.
Use explode() with the \n delimiter to split the source code into lines.
Use array_slice() to get the lines you need.
eval() the code.
Note: if you just want the HTML output, then ignore the bit about the source in step 1 and obviously you can skip the whole eval() thing.

Categories