Solved

Get Value from PHP Page

Posted on 2014-04-29
12
809 Views
Last Modified: 2014-05-02
I have a very simple HTML page called "Schedule".  I have some javascript variable in the "Schedule" page.  One variable in the "Schedule" page is a date called "CurrentDate" that I need to get from a database.  I have a separate PHP page called "getTheDate.php" that accesses the database and displays the date I need (ie if your browser points to this PHP page it will only display the date I want from the database - source code shows only the date I want as well).  What I want to do I is somehow reference this PHP file in my "Schedule" HTML file and set my variable "CurrentDate" to the value displayed by the working PHP page.

Should be pretty basic I would think, but I want to keep my HTML and PHP files separate and can't figure out an easy way to do this.  Any help is appreciated.
0
Comment
Question by:MrBeedge
  • 4
  • 3
  • 2
  • +2
12 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
AJAX (Asynchronous Javascript and XML) can do that.  Here's a tutorial to show you the steps needed: http://www.w3schools.com/ajax/ajax_intro.asp
0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
Comment Utility
First, if you are not familiar with basic javascript and jquery, it would save you a lot of frustration if you spend some time at least getting the very basic http://www.codecademy.com/tracks/javascript and http://www.codecademy.com/tracks/jquery.  This assumes you already have a very good understanding of html and css.  

Assume you have a getTheDate.php page that looks like this.
<?php
echo "5/1/2014"

Open in new window

Now to place this data on your page.  You can use plain old javascript, but I prefer using jquery. It is widely used and can be easier to understand for some.  The instructions for jquery ajax are at https://api.jquery.com/jQuery.ajax/

I have a sample here but instead of my url being getTheDate.php, it is http://jsbin.com/depes/1/ which simply outputs 5/1/2012

http://jsbin.com/detek/1/edit?html,output
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
  $(function(){ // Loads when the DOM is ready
  //https://api.jquery.com/jQuery.ajax/
  $.ajax({
  url: "depes/1",
  cache: false
})
  .done(function( data ) { // data is the output 5/1/2014
    
    // place the data in the div with id=date
    $( "#date" ).append( data );
  });
  
});  
  </script>
  <meta charset="utf-8">
  <title>padas Q_28422885</title>
</head>
<body>
  <div id="date"></div>
</body>
</html>

Open in new window

If you use your browsers console, you will see the div id=date filled in with the date.

An important concept to understand when first working with this is your serverside code (php) that you may have on the main page runs on the server before the html is ever drawn on the page.  Once the server is ready, the html is sent to the browser.  Once that loads, any javascript (jquery, ajax) will run.  Your PHP and JS never 'touch'.   In this case, the main page loads, sends the request to your getTheDate.php page which then runs on the server, sends out put to the browser which is retrieved by the main page.  The end result may be a short delay in the date being sent to the page.

The reason this is important is if you are using this date for other calculations for your calendar, you will want to run a function in the done(function) area that tells the rest of your script the data is available.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
From the "feel" of the question you might want to hire a professional programmer to help you get this done.  But if you want to learn all the things a professional already knows, so you can do it yourself, this article can help you get started.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

The nature of client/server protocols is explained here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

A "hello world" example using jQuery and AJAX is available here:
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
This very simple to do - it can be done in a couple of lines of Javascript.

Following on from Scotts solution here is a simpler AJAX solution
getTheDate.php
<?php
echo date('Y-m-d H:i:s');
?>

Open in new window

Schedule.html
<!doctype html>
<html>
<head>
<title>Julianh Q_28422885</title>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function(){ 
  $('#date').load('getTheDate.php');
});  
</script>
</head>
<body>
  <div id="date"></div>
</body>
</html>

Open in new window

Working sample here http://www.marcorpsa.com/ee/t660.html
The main difference is that we use the JQuery .load() function instead of .ajax(). They do essentially the same thing - but in this case we are doing a very simple operation and the additional functionality provided by the .ajax() call is not necessary.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
somehow reference this PHP file in my "Schedule" HTML file and set my variable "CurrentDate" to the value displayed by the working PHP page
It might be even easier than you think.  Just change "Schedule" from an HTML page to a PHP page.  Then you have all of the power of PHP at your fingertips for this and any other server-side interaction you need. Example here:
http://www.iconoun.com/demo/temp_mrbeedge_schedule.php

<?php // demo/temp_mrbeedge_date.php
echo date('c');

Open in new window

<?php // demo/temp_mrbeedge_schedule.php
include('temp_mrbeedge_date.php');

Open in new window

0
 

Author Comment

by:MrBeedge
Comment Utility
Getting close, but I probably didn't provide enough info.  I am a very weak programmer especially in javascript and php.  I have a html page with a lot of javascript already in it.  I want to keep it as an HTML page and stick with pure javascript because I don't want to mix in a bunch of other stuff (even jscript) because I just don't have enough knowledge about how this will work with different browsers, etc.  

I have a variable in my HTML page that is hardcoded.  Basically, let's say it is:

<script>
theWeek = "5/4/2014";
</script>

My PHP page is (getTheWeek.php), is separate and is as follows:

<?php

require("../codebase/connector/db_sqlsrv.php");

$myServer = "----";
$myUser = "----";
$myPass = "----";
$myDB = ""----";
$connInfo = array("Database"=>$myDB, "UID"=>$myUser, "PWD"=>$myPass);

$conn = sqlsrv_connect($myServer, $connInfo) or die("Couldn't connect to SQL Server");

$query = "SELECT * ";
$query .= "FROM WeeklyNotes ";
$query .= "WHERE WeeklyNotesID='1'";

$result = sqlsrv_query($conn, $query);

while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC )) {
    $result1 = $row["WeekBeginning"];

    $newDate = $result1->format('m/d/Y');

    echo $newDate;
}
sqlsrv_close($conn);

?>

Loading this PHP page in a browser will display:

5/4/2014

The date is dynamic depending on the date in the database.  What I want to do is remove the hardcoding for theWeek in my HTML page, and put the dynamic date from the PHP page in the variable from the HTML page.

I think this should be possible.  There are probably several better approaches here.  But, it I can keep my PHP page separate, keep my HTML page as a simple HTML page with javascript code only, that would be ideal.

Thanks!
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
I don't want to mix in a bunch of other stuff (even jscript
jscript? did you mean JQuery? jscript = javascript.
JQuery is javascript - and is extensively used.
However, you can do it either way.

Firstly the javascript way
<!doctype html>
<html>
<head>
<title>Pure Javascript</title>
<script type="text/javascript">
var theWeek;
// FUNCTION TO DO SIMPLE AJAX CALL
// COPY AND PASTE INTO YOUR CODE AS IS
function loadXMLDoc(page, method, callback) {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        callback(xmlhttp.responseText);
      }
    }

    xmlhttp.open(method, page, true);
    xmlhttp.send();
}
// THIS FUNCTION WILL EXECUTE WHEN THE PAGE IS LOADED (DOM READY)
// ADD TO YOUR ONLOAD WITHOUT THE ENCLOSING $(function() { })();
// i.e. IF YOU ALREADY HAVE AN ONLOAD THEN ONLY COPY THE LINES BETWEEN (A) AND (B)
// IF YOU DON'T HAVE AN ONLOAD THEN COPY EVERYTHING FROM HERE
(function() {
  // (A) 
  loadXMLDoc('getTheDate.php',"GET", function(val) {
    // WHEN THE CALL RETURNS SET THE INTERNAL theWeek
    theWeek = val;
    // JUST FOR THIS DEMO
    document.getElementById('date').innerHTML = theWeek;
  });
  // (B)
})();
// TO HERE
</script>
</head>
<body>
  <div id="date"></div>
</body>
</html>

Open in new window

Alternatively the JQuery way
<!doctype html>
<html>
<head>
<title>Pure Javascript</title>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var theWeek;
$(function() {
  $.get('getTheDate.php',{},function(resp) {
    theWeek = resp;
    $('#date').html(theWeek);
  });
});
</script>
</head>
<body>
  <div id="date"></div>
</body>
</html>

Open in new window

0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
Actually to make it simpler you can do this
Create the following javascript file
getthedate.js
// FUNCTION TO DO SIMPLE AJAX CALL
function loadXMLDoc(page, method, callback) {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        callback(xmlhttp.responseText);
      }
    }

    xmlhttp.open(method, page, true);
    xmlhttp.send();
}
// THIS FUNCTION WILL EXECUTE WHEN THE PAGE IS LOADED (DOM READY)
(function() {
  loadXMLDoc('getTheDate.php',"GET", function(val) {
    // WHEN THE CALL RETURNS SET THE INTERNAL theWeek
    theWeek = val;
  });
})();

Open in new window

Then simply add the following (change path  to .js file as needed)
<script src="getthedate.js"></script>

Open in new window

After the following
<script>
var theWeek;
</script>

Open in new window

Full demo html listing
test.html
<!doctype html>
<html>
<head>
<title>Pure Javascript</title>
<script type="text/javascript">
var theWeek;
</script>
<script src="getthedate.js"></script>
</head>
<body>
 ...
</body>
</html>

Open in new window

Note: an AJAX call is asynchronous so anything you do with 'theWeek' you need to do only after the call to getTheDate.php completes.
Whatever you want to do with the date you need to do it here
  loadXMLDoc('getTheDate.php',"GET", function(val) {
    // WHEN THE CALL RETURNS SET THE INTERNAL theWeek
    theWeek = val;
    // USE THE DATE HERE. ACCESSING theWeek BEFORE THIS POINT
    // WILL YEILD A BLANK VALUE FOR theWeek.
  });

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
This was already answered:

A "hello world" example using jQuery and AJAX is available here:
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html

0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
Comment Utility
JulianH's pure javascript answer http:#a40033987 seems like what you are looking for to answer the basic question.  

Is the WeeklyNotesID always hardcoded to "1"?
0
 

Author Closing Comment

by:MrBeedge
Comment Utility
I ended up putting the javascript code in my html file rather than a separate js file and got it to work just fine after monkeying around with it a bit.  Thanks for help.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
You are welcome - thanks for the points.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now