?
Solved

Get Value from PHP Page

Posted on 2014-04-29
12
Medium Priority
?
877 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +2
12 Comments
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 40031275
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 53

Expert Comment

by:Scott Fell, EE MVE
ID: 40031306
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 111

Expert Comment

by:Ray Paseur
ID: 40031708
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 58

Expert Comment

by:Julian Hansen
ID: 40031789
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 111

Expert Comment

by:Ray Paseur
ID: 40031837
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
ID: 40033788
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
 
LVL 58

Expert Comment

by:Julian Hansen
ID: 40033987
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 58

Accepted Solution

by:
Julian Hansen earned 2000 total points
ID: 40033999
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 111

Expert Comment

by:Ray Paseur
ID: 40034342
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 53

Expert Comment

by:Scott Fell, EE MVE
ID: 40034556
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
ID: 40036407
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 58

Expert Comment

by:Julian Hansen
ID: 40036539
You are welcome - thanks for the points.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When it comes to write a Context Sensitive Help (an online help that is obtained from a specific point in state of software to provide help with that state) ,  first we need to make the file that contains all topics, which are given exclusive IDs. …
Originally, this post was published on Monitis Blog, you can check it here . Websites are getting bigger and more complicated by the day. Video, images and custom fonts are all great for showcasing your product or service. But the price to pay in…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

801 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