Is there a way to access previously created divs? - php

I'm creating divs with dynamic names using php such as:
echo "<div class=\"".$row['country']."\">"
So it's going to first create a series of divs such as ...
<div class="America">
//stuff goes in here
</div>
<div class="Germany">
//stuff goes in here
</div>
<div class="Singapore">
//stuff goes in here
</div>
But later on in the code after the "Germany" div has already been created, I'm going to make another mysql query to a different table and I want to access the "Germany" class and add content in it. It then becomes something like...
<div class="Germany">
<p> Germany has x number of people </p>
<p> The most popular car in Germany is x </p>
</div>
I know with Jquery there is the append() function. Is there something similar in PHP where I can access a div that's already been created and add stuff to it?
Note: all of this is in one php file that loads all the content when the page loads.

It can be done. You can use output buffering to capture all output. Then you can use an HTML DOM parser to modify that output. After that, you can flush the lot.
But this will work only once and it will seriously slow down your script. Don't do it, it smells of bad design.

Your best option would be to create multiple variables like
$css['America'];
$css['Germany'];
$general_output;
etc and, while you are building your site, just add info to the required variable.
Once you get to the end of the page, print them in the right order and you are done.

I think you can create an array like
$div["Amereica"] = "America"
And in future you can append value to this array. eg.
$div["Amereica"] .= 'text to append';
And finally you can use implode function or using other array functions you can crate final html.

If you really need to re-access that element, you're probably looking for DOM functions or phpQuery

Simple answer is no.
You can't change HTML code produced by PHP, because that code is already sent to browser, and PHP works on server side.
One of complicated answers is #GolezTrol answer.

Related

Submission form that will insert content on another page

Me and My friends are starting a website. I'm the only one who knows any type of coding. Since they don't know any programming language I'd like to make a form submission page that will allow them to just type in basic info, updates and have it generate and insert PHP or HTML into the main content page for them.
For example if name in box 1="Rob" I want it to insert <p>Rob #HH:MM MM:DD:YY</p>
And whatever info is typed into box 2 to be in the following paragraph.
I know something like above is possible with PHP and SQL, but I'm just kinda stumped as to know what it needs to be searched to learn it.
Thank you in advance for your help.
It sounds as though you don't necessarily even need any PHP for this. This is something you could just as easily do in the client itself. Of course, for something more elaborate, you're going to need to build this out more and can undoubtedly make use of a more elaborate system, but for your example, just piece together what you're aiming to join with some JavaScript.
I've assembled a sample at http://codepen.io/anon/pen/VjdPgm but here's the important bit:
HTML
<p>Box 1</p>
<input id="box1">
<p>Box 2</p>
<input id="box2">
<br/>
<button onclick="generate()">Generate</button>
<p>Result</p>
<textarea id="result" cols="100" rows="10"></textarea>
JavaScript
var generate = function() {
var output = "";
//Append the text for box1
var box1 = document.querySelector('#box1').value;
output = '<p>' + box1 + '#HH:MM MM:DD:YY</p>';
//Append the text for box2
var box2 = document.querySelector('#box2').value;
output += '<p>' + box2 + '#HH:MM MM:DD:YY</p>';
//Set the output in the result box
document.querySelector('#result').value = output;
}
You click on the button, it executes this JavaScript function that pulls the values from the boxes you filled in and drops the values into the inline templates.
Now, if you actually want this to save the logic somewhere, you're going to need to incorporate the logic to save this via PHP and potentially store somewhere with the rest of your templates or the like. For this, you'll need to consider a number of other aspects including validation, escaping and how you're designing your own pages to build them with their content (e.g. does this script overwrite an existing file or do you assemble the webpage based on some MySQL lookups), but this is a bit outside the scope of your question.
If you're utilizing a CMS of sorts, you might consider using something like the above example to generate the markup so they can just drop what they want in the CMS and avoid having to write all that other stuff yourself.

Get data from HTML and save it as a PHP variable

I have started learning php and I have a question.Let's say I have the following html code:
<p id='tobeChanged'>I wil be changed throughout the execution<p>
This paragraph is not static.Its content can be changed from the user with a button which will produce a random number and will replace the paragraphs html.
E.g. from
p id='tobeChanged'>I wil be changed throughout the execution<p>
to
<p id='tobeChanged'>42<p><!--changed with a button-->
Now my question.Is it possible to pass the new produced value to a php variable?If possible i would like a long explanation.
Also i would like not to use forms(if possible).
Thanks In advance
You need to fire an AJAX request on that button click, that will send that value to server making php to read it.
You can do something like this (you need to include jQuery on page):
$.post("/saveVariable.php",{randNum:randomNum},function(data){alert("Data saved successfully");})
At PHP end, you will get the value in
$_POST['randNum']
Maybe that will help.

Find and store all innerhtml of div to php variable

Iā€™m trying to store the content of a div to a variable.
Example:
<div class="anything">
<p>We don't know the content of this div</p>
</div>
I want to search for <div class="anything"> and store everything between opening and the end tag.
We also want to avoid using absolute pathnames, so that it only searches the current HTML/PHP file for this div where the code is present.
Is this possible with PHP, or is this only possible with JavaScript ?
PHP is not that intelligent. He doesn't even know what he says.
PHP is a server-side language. It has absolutely NO clue about what the DOM (ie. what is displayed in your browser's window) is when it delivers a page. Yeah I know, PHP rendered the DOM, so how could it not know what's in there?
Simply put, let's say that PHP doesn't have a memory of what he renders. He just knows that at one particular moment, he is delivering strings of characters, but that's all. He kind of doesn't get the big picture. The big picture goes to the client and is called the DOM. The server (PHP) forgets it immediately as he's rendering it.
Like a red fish.
To do that, you need JavaScript (which is on the client's computer, and therefore has complete access to the rendered DOM), or if you want PHP to do this, you have to retrieve an full-rendered page first.
So the only way to do what you want to do in PHP is to get your page printed, and only then you can retrieve it with an http request and parse it with, in your case, a library such as simpleHtmlDom.
Quick example on how to parse a rendered page with simpleHtmlDom:
Let's say you know that your page will be available at http://mypage.com/mypage.php
$html = file_get_html('http://mypage.com/mypage.php');
foreach($html->find('div.anything') as $element)
echo $element->src . '<br>';
you probably need a combination of those.
In your Javascript:
var content = document.getElementsByClassName("anything")[0].innerHTML();
document.getElementByID('formfield').value(content);
document.getElementByID('hiddenForm').submit();
In your HTML/PHP File:
<form id="hiddenForm" action="path/to/your/script">
<input type="hidden" name="formfield" value="" />
</form>
In the script you defined in the form action:
if(!empty($_POST)){
$content = $_POST['formfield'];
// DO something with the content;
}
Alternatively you could send the data via AJAX but I guess you are new to this stuff so you should start slowly :)
Cheers!
steve
You could use JS to take the .innerHTML from the elements you wan and store them in .value of some input fields of a form and then use a submit button to run the PHP form handling as normal. Use .readOnly to make the input fields uneditle.

What is the best approach to handle dynamically generated unique DOMs on a page based on a common single template?

Suppose you have a page in which users can create a new, unique div every time they click a button. The content of the div is mostly based on a common single template on the server side, but as the user can create several of these, the content DOMs ids of the resulting div have to be dynamically generated for each request, so as to be able to select each individual div and its content separately through jQuery afterwards (otherwise, since these divs are based on the same template, they would naturally always have the same DOM Ids, thus making it impossible to select them individually using jQuery)
Let's say you are building a windows system with javascript and jquery. On the server side you have one template that represents the "folder" window; this template has its own buttons, menus, etc, all of them being dom elements with their ID.
The user is then, on the page, supposed to be able to open several "folder" windows, each of which is assigned a different id on its creation, but the contents are the same, since the template loaded is the same for all of these windows. That is to say, provided the user opens 3 "folder" windows, the actual markup loaded in the page may look like the following:
<div id="firstWindow">
<div id="windowContainer">
<div id="windowHead">
stuff
</div>
<div id="windowBody">
<div id="windowInfoButton">stuff</div>
stuff
</div>
</div>
</div>
<div id="secondWindow">
<div id="windowContainer">
<div id="windowHead">
stuff
</div>
<div id="windowBody">
<div id="windowInfoButton">stuff</div>
stuff
</div>
</div>
</div>
<div id="thirdWindow">
<div id="windowContainer">
<div id="windowHead">
stuff
</div>
<div id="windowBody">
<div id="windowInfoButton">stuff</div>
stuff
</div>
</div>
</div>
As you can see windowContainer, windowHead, etc are duplicated as a result of reading from the same template. By itself this is already bad, but moreover I need to be able to select each windowContainer or windowHead using jQuery in such a way that manipulating them in firstWindow doesn't affect secondWindow, so simply switching all ids to classes wouldn't do it.
There are two approaches I can think to solve this:
1) Since I'm using PHP directly as the templating language, I could easily attach some code that generates a randomid or string and replace every DOM e.g. from this:
<div id="someFixedID" class="someClass">stuff</div>
To this:
<div id="<?=$someRandomStuff?>someFixedID" class="someClass">stuff</div>
The problem is that, well, if the template has some 20 or 30 DOM elements, that would greatly pollute it, and I'm trying to have as little code in the templates as possible to be able to quickly iterate on the design.
2) Using jQuery, it's possible to load the template via ajax, loop through every element in the div and change their ids on the fly before showing it. This would help keeping the templates clean, but I'm concerned this method may add an unnecesary overhead on the client side, since it may have to loop through some 20 or 30 elements.
Which method would make more sense in terms of maintainability and performance? Is there another way to approach this I didn't think of?
If I understand your problem you need to create a DIV dynamically with a unique id. Add DIVs with unique IDs using jQuery and then load content from server side in these DIVs. You need to synchronize your client side IDs generate code with server side template names/content.
For Example:
HTML:
<div id='container'></div>
<input type='button' name='create' value='create' id='create'>ā€‹
jQuery:
$('#create').live( 'click', function(){
var num = $('div.mydiv').length;
var html = '<div id="myid' + num + '" class="mydiv">My Content ' + num + '</div>';
$('#container').append(html);
});ā€‹
Try Here
May be not a perfect solution but hope it will give you a direction.
You could add a parameter in the URL of the Ajax call to get the template to use your client side generated key.
A very rough (not secure) draft:
On the server (template.php):
<div id='<?= $_GET["container_key"] ?>' class='main-container'>
....
</div>
Your ajax call:
var containerKey = Math.random();
$.ajax("/template.php?container_key=" + containerKey, ....)
Use something better than Math.random() (like timestamps, guids, ...) to prevent collisions.

Dynamically create HTML via PHP or jQuery ajax? Which is faster or better method?

Hi I just want to know what the best practice is for dynamically creating html. I can do it in two ways
Direct PHP
<div id='id-here'>
<?php
$user->id = $_GET['id'];
$user->displayUserInformation( );
?>
</div>
jQuery ajax(js script called on page load)
$.ajax({
type: 'GET',
url: 'inc/user_information.php',
data: 'user_id=user_id', //assuming user_id value was already set.
success: function(html)
{
$('#user_information').empty().html(html);
}
});
Note: This code doesn't exist and is purely for showing what I mean^^ I also know jQuery load, but prefer to use jQuery ajax for complex stuff.
Thanks!
The PHP method is certainly more reliable, as it doesn't require javascript in the client. For information that isn't expected during a page's lifetime, or indeed a user's session it also makes a lot more sense. I don't imagine the information on a user is likely to change that much during a page view.
However, if there is some data that's expected to change, say a post count or something, then use PHP to set the initial value, then use ajax to update it only when the value actually changes.
I wouldn't worry about which is faster... the difference would probably be negligible. But bear in mind that some users do have JavaScript turned off... if you want to support those users, it's worthwhile taking the extra effort to do it in PHP.
My rule is that if it can be done on the server, do it there. Then you can be absolutely sure of the results for all users.
u get it all wrong, first one is not a 'dynamically created html", user sent a request, PHP process it, and return the HTML, and your browser render it
2nd one is your browser already load HTML, and u try to use jquery to simulate another request of the same process of the 1st one
In your examples, if you show user info like this, method 1 will not require another data fetching from the server as in example 2 (2 HTTP requests total, 1 for original webpage, 1 for the ajax), so it is faster.
usually, generating static data inside a page like this (in example 1) is different from AJAX, where content is provided to the user, and only update with the new data using AJAX without updating the whole page's content.
Maybe what you mean is: should the data be provided together with the original webpage, or should it be left empty, and then use AJAX to fetch the data to display it. It would be better usually to provided data at first, instead of letting the user wait for another trip to the server to see the data.
I believe that loading from PHP as static loading would be better and more reliable. However loading from AJAX will push the results one time, not as static loading, data will be loaded in portions...
Along the same lines, which is faster within a php file. This is more for SEO and "best practice" than for actual user experience. I'm using wordpress, and I'm working within php files. Most of it is php, but I have four lines of html within the file. All are exactly the same. I could loop through the four lines with php, or copy and paste the four lines of html. I don't expect to ever change the code, so php doesn't seem to present any other benefits.
Here's my code:
HTML version (well mostly)
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
OR the php:
for($i=0;$i++;$i<4){ ?> //start loop, 4x
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" />
//Image path using php
<?php } ?> // end loop
THANKS ALL!

Categories