Jump to content

Self-Loading Templates (HTML: DOC or Not DOC) - A Question of Strategy


iwato

Recommended Posts

BACKGROUND:  Please go to the following webpage and note four different ways to fill the center section.

1) The center section is loads with the rest of the page as the content of <div id='main'>

2) The center is replaced with hidden content already on the page using jQuery's html( ) function. (Click in the navigation panel on the phrase "Form, Use, and Meaning'.)

3) The center is replaced with a portion of content from another page using jQuery's load( ) function. (Click in the navigation panel on the phrase "Words, Phrases, and Clauses".)

4) The center will be replaced with its original content, but without having to reload the page.  The principle is the same as in Item 2, but the link mechanism is different. (Click on the host's image.)

DILEMMA:   I want to fill the same section with an HTML-formatted template filled with information from a data base that opens simultaneously with the page.

CONSTRAINTS:

1) The host page for the content -- namely, podcasts_dev_copy.php is structurally complete.  Any changes that I make to it should be minor.

2) The content of the middle section must be filled invisibly before the host page opens, or it must fill simultaneously with the host page.

RESOURCES:

1) I have developed a PHP page that takes information sent to it from a 3rd party HTTP request, downloads  data from a database that is based on the request, and opens to the host page with a portion of the processed information using a $_SESSION superglobal and the PHP header( ) function and location property.  (This page has not been posted.)

2) A template engine that generates the replacement content from the same $_SESSION superglobal

Have you got any ideas?

Roddy

Edited by iwato
Link to comment
Share on other sites

It's common to use ajax to send a request for partial content and fill that in on the page.  I don't know if jQuery's load method will automatically execute any Javascript sent with the HTML, but if not that's something else to consider.  A common practice would be to return a JSON structure with an HTML part and a Javascript part, where you would add the HTML then execute the Javascript.

  • Like 1
Link to comment
Share on other sites

Thanks!  I just checked the jQuery webpage.  The load( ) function accepts event handlers.  This suggests the following procedure.

1)  Receive the HTTP request from a remote 3rd party website.

2)  Start a Session

3)  Fetch and prepare the corresponding data from the site's database

4) Load the host page with the PHP header( ) function and location property and signal to the loading page with an accompanying session variable whether or not to load the insert.

5) Based upon the test decide whether to the host page should be loaded with the insert or not.

6) if the test indicates the presence of a third party request, execute a jQuery load() function with an event handler.

7) Use the event handler to trigger the template engine to create and download the filled template.

8) Enjoy!

What do you think?  Does it sound like a reasonable plan?

Roddy

.

 

 

Link to comment
Share on other sites

Ouch!  I just discovered that the jQuery load( ) function has been deprecated.

Well, maybe not, apparently there were two load( ) |  load( ) functions.

Roddy

Edited by iwato
Link to comment
Share on other sites

I wasn't referring to a callback, I meant Javascript inside the returned content.  If you use it to load something like this:

<a href="http://www.google.com">Google</a>
	<script type="text/javascript">alert('test');</script>

I don't know if that Javascript will get executed or not when the content is added to the page.  The load method is just a wrapper around a regular ajax request, and when you send an ajax request and then use something like innerHTML to add the new content to the page, Javascript does not get executed.  If that is also the case with jQuery, which it would be unless they added a bunch of overhead to the load method to look for Javascript code and try to run it, and you still need to return Javascript along with the partial content, then it would be better to return a structure that contains discrete parts for the HTML and Javascript.  That way, you can get the response from the server, add the HTML, and execute the Javascript.  You wouldn't use the load method to do that, you would use a regular ajax request and handle the response yourself.

Otherwise, your suggestion sounds possible, but a little clumsy.  I'm not sure why you want to redirect the user as soon as they get to the site - did they click on a link to a page other than the one they want to go to?  Why add the overhead of an immediate redirect, and how are you going to determine whether or not to redirect?  Also, instead of using PHP to output a container page to run a Javascript function to load the content, you can also eliminate the overhead of that extra request and just have PHP load all of the content to start with.  So instead of getting the user's request, then redirecting them, then outputting a container, then using ajax to load the content, which is 3 requests, you just get the initial request, use PHP to build the page like you initially want it, and output the result.  That's only 1 request from the user.

Link to comment
Share on other sites

Quote

I'm not sure why you want to redirect the user as soon as they get to the site - did they click on a link to a page other than the one they want to go to?

No, the user clicks on a third-party  link with an HTTP request that is sent to the grammar captive.com domain.  It is this request that tells the development page to fetch, process, create session variables, and redirect to the host page at www.grammarcaptive.com/podcasts_dev_copy.php.  In the absence of this request the host page opens as you see it now, and the method for triggering access to the data base and the creation of the template will likely be different (see my final comment below).

 In effect, the decision is made by the avenue taken.

Quote

Also, instead of using PHP to output a container page to run a Javascript function to load the content, you can also eliminate the overhead of that extra request and just have PHP load all of the content to start with.

If I do this, I would still have to implement the PHP header( ) function. What is more, each time the host page is opened, the question, "From where is the request coming?", would have to be answered.  In the current, imagined set-up this question would never have to be asked, for the browser would always be told.

Quote

So instead of getting the user's request, then redirecting them, then outputting a container, then using ajax to load the content, which is 3 requests, you just get the initial request, use PHP to build the page like you initially want it, and output the result.  That's only 1 request from the user.So instead of getting the user's request, then redirecting them, then outputting a container, then using ajax to load the content, which is 3 requests, you just get the initial request, use PHP to build the page like you initially want it, and output the result.  That's only 1 request from the user.

You make a good point and have caused me to rethink my design strategy.  

Up until this point my focus has been on attracting the user to the Grammar Captive podcast host page and ultimately the Grammar Captive main page. As a result of this focus I have largely ignored the user whose avenue of approach is in the reverse direction -- namely, from the Grammar Captive main page to the podcast host page. For, such users will already be on the podcast host page when looking for additional information about a particular podcast.  In effect, I will need two different triggers for generating the same template.  Maybe I should have begun with this latter, easier problem first.

Link to comment
Share on other sites

If I do this, I would still have to implement the PHP header( ) function.

If you're specifically talking about sending a location header to redirect the user, I just don't understand the technical need for that.  I don't see any problem which gets resolved by redirecting the user to another page, I don't understand why you think that's a solution to any problem you think you have.  They're already on your site, PHP can do anything you want it to do, I don't understand why you've come to the conclusion that the thing you want PHP to do is to just redirect the user and start PHP over again.  It's already running, just do what you need it to do the first time.  It almost seems like you've learned a few things about PHP, you have a solution, and now you're searching for a problem for your solution.  I just don't see the need to redirect, I don't see any problem that a redirection solves.  The only time you need to redirect someone is if you want them on a different page for whatever reason, maybe because they've just submitted a form, you processed the form, and you don't want them to hit refresh and re-submit the form.  Or they just logged in, and you're taking them to wherever they go after logging in.  Those are the cases when you might redirect someone.  You're describing your solution to redirect a user and I'm missing the problem you're trying to solve by doing that.

What is more, each time the host page is opened, the question, "From where is the request coming?", would have to be answered.

Why?  Why do you need to know that?  If you're just interested in tracking traffic and things like that, I would suggest something like Google Analytics.  Otherwise, why would any page care where the user came from, why is that relevant to what the page is supposed to produce?

I'm not sure if we're experiencing a language or terminology barrier or what, but I'm having a hard time understanding why you think you have all of these requirements.  A web page, or PHP page, or whatever, typically has a single purpose in terms of what it displays, and that purpose typically does not depend on where the user came from.  A certain URL, in general, should always show the same content regardless of how the user got there.  You wouldn't want people to share a certain URL and have it show different content for different people, that wouldn't make sense to them.  You're talking about setting session variables when the user gets to the page, why?  The session is for tracking who the user is, if they just got to your site you don't know anything about them, why do you think you have to use the session?  It sounds like you're learning individual tools in PHP and then trying to apply everything to your site even though it's not necessary.  Not every page or site needs to use every PHP function.

  • Like 1
Link to comment
Share on other sites

In answer to your response to the second quote:  At present the podcast host page serves two separate functions.  In the future it will be integrated into a protected membership forum with private access. Let us look more closely at the two functions:

Firstly, it is a catalogue of podcasts.  When the user arrives he may or may not be looking for a particular podcast.  In fact, he may not even know what a podcast is.  Should he decide to try one, the information related to the podcast (not the podcast) itself will appear in the main section of the page.  This data must be retrieved from the data base in which it is stored.  This information will be used by the user to decide whether he wants to download the podcast or not.  Should he decide in the affirmative, he will be given a variety of alternative podcast host sites.

Secondly, when the user finds a Grammar Captive podcast on a third party host page he is invited to investigate the selected podcast and other Grammar Captive podcasts further.  To this end he is provided with a link containing an HTTP request for the selected podcast.  When the Grammar Captive host page opens it will appear as if the user had selected the podcast from the host page.

Thus, how the user opens to the page is important.  Now, although it is likely that I can use the same code to retrieve and distribute the information from the database is needed,  the way I access this code will surely be different. Although I have though a great deal about how to access and distribute the data in the second instance, I have thought very little about how to do it in the first.  This is largely because I do not have any podcasts to work with, as of yet.

If you have any ideas to bring these two function together in the most efficient way possible, please fire away!

Roddy

Link to comment
Share on other sites

A "catalog" page and a "description" page for a single item are typically 2 different pages, with 2 different purposes.  If someone is going to the catalog then they're looking at the entire catalog, so that's what you show them.  If they're looking for information on a specific item - and it makes absolutely no difference how they got there - then you show them the information for that item.  Those are 2 separate things.  You can structure the URLs however you want, the most basic way is to just pass a database ID in the querystring, e.g. domain.com/getDetails.php?item=10, and you can look up the thing with that ID in the database and display information about it, or maybe redirect to the catalog page if that ID isn't in the database, or handle that however you want.  You can also use URL rewriting if you want the URLs to be more descriptive or search-engine-friendly but still tell PHP which thing you're looking for.

I think you're seriously over-complicating your site.  It's a fairly simple and basic design that is used all over the place, and for some reason it sounds like you think it's way more complex than it is.  This is a basic database CRUD site - create, read, update, delete.  You need an admin area where you can log in to create, update, and delete the records in the database (in your case, podcasts), you can set up a category or tagging system if you want to display things in some sort of hierarchy, a page to browse the category however you want (maybe you select child categories, maybe there's a search feature, whatever you want), and a page to display the information for a single item.

Link to comment
Share on other sites

This was not at all what I was expecting.  What is more, I thought that the idea was to limit the number of calls to new pages.   I will post something very soon of a very concrete nature, and we hopefully we begin afresh from there.

Roddy

Link to comment
Share on other sites

I thought that the idea was to limit the number of calls to new pages.

It is.  If you want to get details about a certain item, that's one page.  If you want to view the catalog, that's one page.  There aren't any redirects or anything else going on, each request results in a response for that request.  If you want to have a page where people can click on the details for each item and see things pop up instantly without sending another request you can do that with Javascript, but the issue there is that you're loading everything for everybody even if they aren't going to use it, and it's going to take a while to create that page.  It seems like it's more efficient to send a request for each thing the person wants.

  • Like 1
Link to comment
Share on other sites

OK.  If you are still with me, I have uploaded what I have thus far achieved with your counsel and my own apparently ill-formed improvisation.  i say this because I am receiving the following Javascript error message: "Range error: Maximum call stack exceeded".  As I do not understand it, I do not know how to fix it.  It is generated when the Proxy Link on the third-party proxy podcast hostage is selected.  Although both of the following links will eventually take you to the same page, each link produces different results for the same page.  The first link opens directly to the page with no HTTP Request, the second link opens to the same page with an HTTP Request.  I have provided the PHP, HTML, and Javascript that controls the page.  I suspect that the problem lies with the Javascript related to the HTML.

Grammar Captive Podcast Hostpage:  http://www.grammarcaptive.com/podcast_dev_copy.php

Third-Party Proxy Podcast Hostpage:  http://www.grammarcaptive.com/sender_proxy.php

The link on the Third_Party Proxy Podcast Hostpage does result in consistent behavior.  Should the resulting page appear incomplete click on the words  "Today's Podcast No. 60" beneath the image.  This is how the page is suppose to appear when you click on the proxy link on the proxy hostage.

Also, please take note of, what is for me, the completely bizarre appearance of the <title> element of a PHP include file in your browser tab window -- namely, The get_string_between( )" Function.

<?php
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
/**************************************************************************************************
Test whether an HTTP Request containing the hash and podcast_no key-value pairs has been received.
**************************************************************************************************/
if (!empty($_GET['hash']) && !empty($_GET['podcast_no'])) {
/************************************************************
Receive the guid and podcast number from a third party website, or during development from http://sun.local/~kiusau/reflexive/php_practice/projects/call_filler_and_display_page/sender.php
*************************************************************/
	$guid = filter_var($_GET['hash'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
	$podcast_no = filter_var($_GET['podcast_no'], FILTER_SANITIZE_STRING, FILTER_VALIDATE_INT);
/************************************************************
Clean the variables receivied and begin a session.	
*************************************************************/
	session_start();
/************************************************************
Establish a connection with the database and set the character set.
*************************************************************/
	$host = "...";
	$user = "...";
	$pwd = "...";
	$db = "...";
	$mysqli_obj = new mysqli($host, $user, $pwd, $db);
	if (mysqli_connect_errno()) {
		printf("Connect failed: %s\n", mysqli_connect_error());
		exit();
	}
	if (!$mysqli_obj->set_charset("utf8")) {
		printf("Error loading character set utf8: %s\n", $mysqli_obj->error);
		exit();
	}
/************************************************************
Retrieve and display the contents of the rss2_podcast_item data table
*************************************************************/
	$tbl_name = "rss2_podcast_item";
/************************************************************
Select and display the podcast number that corresponds to the matched guid 
*************************************************************/
	$select_col = 'podcast_no_item';
	$match_col = 'item_guid';
	$sql_4 = "SELECT " . $select_col . " FROM " . $tbl_name . " WHERE " . $match_col . "=?";
	$sql_stmt = $mysqli_obj->stmt_init();
	$sql_stmt->prepare($sql_4);
	$match_col = $guid;
	$sql_stmt->bind_param("s", $match_col);
	$sql_stmt->execute();
	$sql_stmt->bind_result($select_col);
	$sql_stmt->fetch();
/************************************************************
Create the variable list of item variables from which to retrieve data
*************************************************************/
	$select_arr['select_col1'] = 'podcast_no_item';
	$select_arr['select_col2'] = 'item_title';
	$select_arr['select_col3'] = 'item_link';
	$select_arr['select_col4'] = 'item_description';
	$select_arr['select_col5'] = 'item_author';
	$select_arr['select_col6'] = 'item_pubdate';
	$select_arr['select_col7'] = 'revision_date_item';
	extract($select_arr);
/************************************************************
Retrieve and Display the desired data from the matched item.
*************************************************************/
	$tbl_name = 'rss2_podcast_item';
	$match_col = 'item_guid';
	$sql_6 = "SELECT " . $select_col1 . "," . $select_col2 . "," . $select_col3 . "," . $select_col4 . "," . $select_col5 . "," . $select_col6 . "," . $select_col7 . " FROM " . $tbl_name . " WHERE " . $match_col . "=?";
	$sql_stmt->prepare($sql_6);
	$match_col = $guid;
	$sql_stmt->bind_param("s", $match_col);
	$sql_stmt->execute();
	$sql_stmt->bind_result($select_col1, $select_col2, $select_col3, $select_col4, $select_col5, $select_col6, $select_col7);
	$result_obj = $sql_stmt->get_result();
	while ($row = $result_obj->fetch_assoc()) {
		foreach($row as $key => $value) {
			$row_results[$key] = $value;
		}
	$item_results = $row_results;
	}
/************************************************************
Free the result object
*************************************************************/
	$result_obj->free();
/************************************************************
Retrieve and Display the desired data from the matched itunes item.
*************************************************************/
	$itunes_select_arr['select_col1'] = 'itunes_duration';
	$itunes_select_arr['select_col2'] = 'itunes_summary';
	$itunes_select_arr['select_col3'] = 'publish_date_itunes';
	extract($itunes_select_arr,EXTR_PREFIX_IF_EXISTS,'itunes');
	$tbl_name = 'rss2_podcast_itunes';
	$itunes_match_col = 'podcast_no_itunes';
	$sql_7 = "SELECT " . $itunes_select_col1 . "," . $itunes_select_col2 . "," . $itunes_select_col3 . " FROM " . $tbl_name . " WHERE " . $itunes_match_col . "=?";
	$sql_stmt->prepare($sql_7);
	$match_col = $podcast_no;
	$sql_stmt->bind_param("s", $match_col);
	$sql_stmt->execute();
	$sql_stmt->bind_result($itunes_select_col1, $itunes_select_col2, $itunes_select_col3);
	$itunes_results = array();
	$itunes_result_obj = $sql_stmt->get_result();
	while ($row = $itunes_result_obj->fetch_assoc()) {
		foreach($row as $key => $value) {
			$row_results[$key] = $value;
		}
	$itunes_results[] = $row_results;
	}
/************************************************************
Free the result object
*************************************************************/
	$itunes_result_obj->free();
/************************************************************
Create the Session Variables and the $_SESSION Array
*************************************************************/
	$length = count($itunes_results);
	$publish_date_itunes = array();
	if ($length > 1) {
		include '_utilities/php/most_recent_date_str.incl.php';
		foreach($itunes_results as $key=>$arr) {
			$publish_date_itunes[] = $arr['publish_date_itunes'];
		}
		$most_recent_date = most_recent_date_str($publish_date_itunes);
	} else {
		$most_recent_date = $itunes_results[0]['publish_date_itunes'];
	}
	foreach ($itunes_results as $key => $arr) {
		if (strtotime($arr['publish_date_itunes']) === $most_recent_date) {
//			print_r($arr);
//			session_start();
			$_SESSION = $arr;
		}
	}
/*****************************************************************************************************
Preparation for the Podcast Insert Using the BluePhoenix Template Engine
******************************************************************************************************/
	require_once('./_utilities/php/page.php');
	$template = './podcasting/template/template.html';
	$start = "<div id='podcast_insert'>";
	$end = "</div><!-- end div#podcast_insert -->";
	$page = new Page($template, $start, $end);
	$tags = array(
		'number' => $_SESSION['podcast_no_item'],
		'title' => $_SESSION['item_title'],
		'share' => $_SESSION['item_link'],
		'description' => $_SESSION['item_description'],
		'author' => $_SESSION['item_author'],
		'date' => $_SESSION['item_pubdate'],
		'revision' => $_SESSION['revision_date_item'],
		'duration' => $_SESSION['itunes_duration'],
		'summary' => $_SESSION['itunes_summary']
	);
	$page->replace_tags($tags);
/*****************************************************************************************************
Close If-Statement Whose Condition Tests for the Presence of $_GET['hash'] and $_GET['podcast_no']
******************************************************************************************************/
}
/************************************************************
Open to the Podcast Mainpage
*************************************************************/
?>
		<div id='podcast_insert'>
			<?php
				if((session_status() == 2) && isset($_SESSION['podcast_no_item'])) {
					$page->output();
					echo
					"<script>
						var podcastInsert = $('#podcast_insert').html();
						$('#main').html(podcastInsert);
					</script>";	
				};
			?>			
		</div><!-- end div#podcast_insert -->
/***********************************************************************************************
    Today's Podcast Display and Refresh
***********************************************************************************************/ 
    //Causes the weight of the font to change when the mouse passes over the text.
	$("#today").mouseover(function() {
			$(this).css({"cursor": "pointer", "font-weight":"800"});
		})
		.mouseout(function() {
			$(this).css("font-weight", "normal");
	});
	//Causes the weight of the font to change, displays the hidden text to appear in the #main <div> element, and brings about a change in color.
	$("#today").mouseover(function() {
			$(this).css({"cursor": "pointer", "font-weight":"800"});
		})
		.click(function() {
			var aboutContent = $("#podcast_insert").html();
			$("#main").html(aboutContent);
		})
		.mouseup(function() {
			$(this).css({"color": "#fadb9d","font-weight": "normal"});
		$('body, html').animate({scrollTop: $('body').offset().top},1200);
	});             

 

Edited by iwato
Link to comment
Share on other sites

The call stack exceeded error is because you've created an infinite loop, and Javascript quits when the maximum recursion limit has been reached.  It's because you have some Javascript code to get the #podcast_insert HTML, and replace the contents of #main with that HTML.  The HTML includes the Javascript code to do that replacement, so each time you replace the code it tries to replace it again and again until Javascript hits the recursion limit.  The Javascript code to do that should not be inside that div, it shouldn't be part of the content that you're moving.

The title tag issue is probably in a template somewhere.  If you open the page in your browser and view the page source you can see that tag before the doctype.

  • Like 1
Link to comment
Share on other sites

The Javascript code to which you appear to refer is that included in the <div id=#podcast_insert> ... </div> element indicated above.  Under the assumption that you have correctly diagnosed the problem can you please help me to understand it just a little better by telling me where I am in error:

Step 1:  As PHP is the first thing to be processed, it inserts the following Javascript into the aforementioned <div> element when the conditions of the PHP if-statement are met.

<script>
	var podcastInsert = $('#podcast_insert').html();
	$('#main').html(podcastInsert);
</script>

Step: 2:  The browser upon finding the Javascript replaces <div id='main'> element with the contents of the <div id='podcast_insert'> including the just mentioned Javascript.

Step: 3:  Having completed the insertion the browser finds a copy of the same Javascript that it just inserted and executes it again.

What I do not understand is why it does not just continue down the page looking for more Javascript and stop at the bottom, if it does not find any?

_____________

Where would you recommend placing the PHP script that inserts the aforementioned Javascript?  After the code that fills the template?   Namely, 

$page->replace_tags($tags);

 

The reason that I ask this question is that the PHP statement

$page->output();

Is what inserts the portion of the template to be displayed in the <div id='main'> element.  I cannot just place it anywhere.  Further, it should only be placed and then moved when there is something to place and move.  Maybe I should just fill the <div id='main'> element directly.  This, however, would require having to go up to the data base each time that the user wanted to return to the day's podcast.

_____________

It is true that there is  a <title> element in the PHP include that selects the portion of the template page to be inserted when the page->output( ) method is called, but why does this <title> element override the <title> element of the page into which the template is inserted?

Understanding this and the above loop would likely help me greatly in my future programming needs.

_____________

Finally, do you have any insight into why clicking on the text Today's Podcast No. 60 below the image does not produce the same smooth effect that clicking on the text Form, Use, and Meaning does?  The code differs only in speed and destination.  Everything occurs on the same page.

Roddy

Edited by iwato
Link to comment
Share on other sites

What I do not understand is why it does not just continue down the page looking for more Javascript and stop at the bottom, if it does not find any?

The act of adding the new HTML content (it does not matter that the content came from somewhere on the page) causes the browser to execute whatever Javascript is in there.  The Javascript that is in there tells it to replace the HTML content again, and that keeps happening until the browser gives up.

Where would you recommend placing the PHP script that inserts the aforementioned Javascript?

The position of the PHP code is not relevant as far as the browser is concerned, the position of the Javascript code is relevant.  Don't put the Javascript code to do the replacement inside the HTML that gets added, it needs to go outside of the element that you're copying.  Now, if you need to change the PHP code to get the Javascript code to show up somewhere else, then do what you need to do.  I would expect that you only have to change something inside the template though.

Maybe I should just fill the <div id='main'> element directly.

It's always better to produce the final version the first time, instead of spending time to produce an intermediate version which then needs to spend more time to produce the final version.  Redrawing the page in the browser is a fairly expensive process (relatively speaking), it's best to limit how many times you're telling the browser to draw the page.  Browsers have gotten a lot better at that over the last decade, but it's still a good practice to try to just produce the final page the first time.

It is true that there is  a <title> element in the PHP include that selects the portion of the template page to be inserted when the page->output( ) method is called, but why does this <title> element override the <title> element of the page into which the template is inserted?

That's just how the browser handles it.  The HTML on that page is not valid, there's not much point trying to figure out how or why the browser is going to handle invalid HTML when you should just produce valid markup.

Finally, do you have any insight into why clicking on the text Today's Podcast No. 60 below the image does not produce the same smooth effect that clicking on the text Form, Use, and Meaning does?

The first link causes the Javascript loop and error in the console.  That link only shows up when clicking from the other page, right?  Why do you use a hash, what's the point?  If you have the podcast ID shouldn't that be enough to uniquely identify it?

  • Like 1
Link to comment
Share on other sites

Quote

The act of adding the new HTML content (it does not matter that the content came from somewhere on the page) causes the browser to execute whatever Javascript is in there.  The Javascript that is in there tells it to replace the HTML content again, and that keeps happening until the browser gives up.

Is all of the Javascript executed again, only that which is included in and follows after the modified HTML tag, or only that contained in the modified tag?  Does this rule hold for all HTML or only certain elements modified in certain ways?

Quote

The first link causes the Javascript loop and error in the console.  That link only shows up when clicking from the other page, right?  

No, there is no other page unless you are referring to the page that contains the Javascript and is read into the HTML document when the page is downloaded.

Quote

Why do you use a hash, what's the point?  If you have the podcast ID shouldn't that be enough to uniquely identify it?

The hash is more important than the number.  The hash is unique and unmistakable.  Whereas the hash is generated automatically and is unique to each podcast, the podcast number is generated manually and can be mistaken.  The hash is a better identifier.

Link to comment
Share on other sites

OK.  How do I get  the value of podcastInsert is the same as $page->output().  The following obviously does not work..

<?php
	echo
		"<script>
			var podcastInsert = $page->output(); 
			$('#main').html(podcastInsert);
		</script>";    
?>            

 

Link to comment
Share on other sites

Is all of the Javascript executed again, only that which is included in and follows after the modified HTML tag, or only that contained in the modified tag?

I haven't tested how jQuery handles that, but I assume that it's only going to execute whatever code was just added to the page.  The rest of the code on the page will be executed when the browser gets to that point.

No, there is no other page unless you are referring to the page that contains the Javascript and is read into the HTML document when the page is downloaded.

I'm referring to the 2 links you posted above.  The direct link does not have that link to #60, the "proxy" link does even though they go to the same page.

The hash is a better identifier.

Why, because it's longer?  There's nothing unmistakable about 60, as far as the computer is concerned.  60 is also unique and unmistakable.  Both 60 and any hash will convert to binary values that are unique, the computer will not confuse them with each other.  So they are both values in the same address space of all binary numbers, one of them is just an enormous number but that's the only real difference, they're just numbers.  Why would one of them be said to be a quantitatively "better" number than another?  Hashes are really only used for one thing - verification.  Passwords are stored as hashes and then the hashes are computed to verify that the entered password matches the stored one, or a file might be distributed along with a checksum hash to verify the integrity of the file, that the file you actually saved is the one they distributed, there was no error in transmission.  Hashes don't really offer anything as identifiers that you can't get with any other numeric value, and a hash is just a numeric value represented in a different base.  One problem I see with using both a hash and an ID is that people cannot find the pages if they only know the ID.  If I think you said something great in podcast 60 and I want to share it with someone else, I can't just check the URL and figure out where the ID goes in the URL, I also need to know some long hash that I can't calculate just by knowing that the podcast was number 60.  So the only thing I can do is try to find a link to that page somewhere else, I can't just type it in manually.  If that's your goal, if you're trying to add some sort of protection against people being able to figure out the URL for any podcast, if you're trying to control access in some way where they need the specific URL and not just the ID, then that would be the result of requiring the hash to be in the URL.

How do I get  the value of podcastInsert is the same as $page->output().

Don't think of it like that, PHP and Javascript don't share any values or anything like that, the only relationship is that you're using PHP to output Javascript code.  They don't run in the same address space, they don't even run on the same computer (PHP runs on the server, Javascript runs in the browser).  As far as PHP is concerned, it's all just text being sent to the browser, PHP doesn't care whether it's Javascript text or HTML text or any other kind, it's just output.

So all you have to do is output that Javascript code outside of the element that is being cloned or copied.  I can't specifically tell you how to do that, I'm not looking at everything that you are.  I assume you have templates or something with all of that stuff in it, so just make sure the Javascript code to copy the content is not part of the content that gets copied.

  • Like 1
Link to comment
Share on other sites

OK.  I have fixed the problem by separating the Javascript from the PHP,  setting two if-statements instead of one, and moving the Javascript outside of the copied <div> element into an external Javascript file.  It all seems so awkward, but it works, and I can move on.  

What I do not understand is why the PHP that I placed into the javascript file even works.  Is PHP always called when a page is loaded by a browser, no matter the nature of the page?

CODE: HTML and PHP

Placed into the host-page.

http://www.grammarcaptive.com/podcast_dev_copy.php

via

http://www.grammarcaptive.com/sender_proxy.php

	<div id='podcast_insert'>
		<?php
			if((session_status() == 2) && isset($_SESSION['podcast_no_item'])) {
				$page->output();
			}
		?>
	</div><!-- end div#podcast_insert -->

CODE: JAVASCRIPT and PHP

Placed into the javascript file that services the host-page when the page loads -- namely,

 <script src="_utilities/javascript/podcasts.js"></script>
 

	var sessionStatus = "<?php echo session_status(); ?>";
	var podcastNo = "<?php echo $_SESSION['podcast_no_item']; ?>";
	var podcastInsert = $('#podcast_insert').html();
	if (podcastNo) {
		$('#main').html(podcastInsert);
	}

 

Link to comment
Share on other sites

Well, I thought I had it, but now i must figure out what is suppressing the <div id='main'>...</div> element from displaying when the podcast hostage is opened directly, rather than via a third party website.

Roddy

Link to comment
Share on other sites

Is PHP always called when a page is loaded by a browser, no matter the nature of the page?

No.  PHP is executed when the web server gets a request for a file which the web server has been configured to send to PHP.  By default, that means .php files, but you can configure the web server to send anything or everything to PHP (which may not be a good idea - especially for things like images, sending binary data to PHP will eventually result in a false positive syntax error).  My application has a couple resources like Javascript files or CSS files that I need to be dynamically created by PHP, so I name those files with a .js.php or .css.php extension so that I know what they are.

If your server is configured to send .js files to PHP then that would be fairly unusual.  You can test that by entering the URL for the Javascript file in your browser to pull up that file directly.  If you see the actual PHP code printed in your browser, then PHP is not handling that file and the code is not running, it's not working.  If you see the results of the PHP code instead of the actual code then it's working.  The Javascript code you posted above would not show a Javascript error because there isn't any Javascript syntax problem there, you would just end up with strings of PHP code in Javascript variables, which wouldn't be helpful.

It doesn't look like it's working on your server.  If you open this:

http://www.grammarcaptive.com/_utilities/javascript/podcasts.js

You will see the PHP code printed in the browser.  That means that PHP is not executing that code.  If you name the file podcasts.js.php and change the references in your HTML code then PHP should run and execute the code in that file.  Or, you can change the Javascript code to send an ajax request to PHP to get the values of those variables to have them available in Javascript.  But the web server won't just automatically fire up PHP for any request unless it's specifically configured to do that, so you'll have to make sure you're using a file name that the web server is configured to send to PHP if you want it to execute PHP code.

Link to comment
Share on other sites

Another, probably better, option, is to leave your Javascript file generic, so that it doesn't depend on outside values.  Define default values for certain variables like the ones you're setting with PHP, give them a default value that tells you that they haven't been set (like an empty string, false, etc).  Then on your template you can have PHP code to overwrite those variables with values for that particular page.  That means you'll need to use document load handlers to run your initializing Javascript code, so that it runs only after the page is finished and PHP will have overwritten whatever values it's using.  So this piece of code:

    var sessionStatus = "<?php echo session_status(); ?>";
    var podcastNo = "<?php echo $_SESSION['podcast_no_item']; ?>";
    var podcastMain = $('#main').html();
    var podcastInsert = $('#podcast_insert').html();
    if (podcastNo) {
        $('#main').html(podcastInsert);
    } else {
        $('#main').html(podcastMain);
    }

Would change to something like this:

var sessionStatus = false;
var podcastNo = false;
$(document).ready(function() {
  var podcastMain = $('#main').html();
  var podcastInsert = $('#podcast_insert').html();
  if (podcastNo !== false) {
    $('#main').html(podcastInsert);
  } else {
    $('#main').html(podcastMain);
  }
});  

Then somewhere in your template or elsewhere in your PHP code you could have PHP output a Javascript chunk to set the values of those variables to something other than false:

$sessionStatus = session_status();
$podcastNo = isset($_SESSION['podcast_no_item']) ? $_SESSION['podcast_no_item'] : '';
echo <<<JS
<script type="text/javascript">
    sessionStatus = "{$sessionStatus}";
    podcastNo = "{$podcastNo}";
</script>
JS;
	

That way your Javascript can remain generic and not depend on anything from PHP, so you won't get any Javascript errors if some link with PHP isn't there.  Your Javascript code can check for the default values that you set and take action if they've later been set to something else by PHP.

Link to comment
Share on other sites

I cannot get the above to work, and I have performed many different experiments with regard to the order, placement, and formatting of the Javascript and PHP.   It simply does not work.  Have you any other ideas?

Roddy

Link to comment
Share on other sites

It's best if you can keep your Javascript generic, so that you can load it on any page without errors, and have it do only what you need for that page.  Do you understand what the point is of the above code, what it's actually trying to do?  I'm not watching you so I'm not sure why it's not working for you, but the concept definitely works.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...