print div With unspecified background html,javascript,php - php

I have a project for kids cards where the child selects the background from specific backgrounds and write his name and print
But the problem is that I only want to print the card (apDiv14 with background) not the full page Or if there was a way to convert certain content to pictures for print
<div id="apDiv14">
<div id="for1">
<h1 ID="head1"> <br>
<h1 ID="head2"> <br>
<h1 ID="head3"> <br>
<br>
</h1>
</div>
<div id="apDiv17"><form name="form1">
<p>
<br>
<input type="text" name="newtitle" size="25">
</p>
<input type="text" name="newtitle2" size="25">
<br>
<br>
<select name="newtitle3" style="width: 150px;">
<option value="">age</option>
</select>
<br>
</p>
<p> <img src="img/BB.gif" width="80" height="45" onClick="ChangeTitle();"><img src="img/PB.gif" width="80" height="45" onClick="pri();"> </p>
<p>
</form> </div></div>
<script>
function pri() {
window.print(); }
</script>
function pic1(apDiv14)
{
// background 1
document.getElementById("apDiv14").style.backgroundImage="url('img/1st card Jeddah.jpg')";
document.body.style.zIndex='4';
document.getElementById("apDiv14").style.backgroundSize = "527px 307px";
document.getElementById("apDiv14").style.backgroundRepeat='no-repeat';
}
function pic2(apDiv14)
{
//background 2
document.getElementById("apDiv14").style.backgroundImage= "url('img/2nd card Jeddah.jpg')";
document.body.style.zIndex='4';
document.getElementById("apDiv14").style.backgroundSize = "527px 307px";
document.getElementById("apDiv14").style.backgroundRepeat='no-repeat';}

You can use a print media stylesheet to limit which content gets printed (by setting other content to display: none but most browsers are configured to not print background images (since they are rarely important and use a lot of ink).
I'd approach this by using some server side code to generate a PDF version for printing and using a form to submit the options to the server.

javascript code:
var content = document.getElementById("divcontents");
var pri = document.getElementById("ifmcontentstoprint").contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();
html code:
<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>

Related

Display SVG in dropdown <select> [duplicate]

I have a select list of genders.
Code:
<select>
<option>male</option>
<option>female</option>
<option>others</option>
</select>
I want to use an image in drop down list as drop-down-icon.jpeg.
I want to add a button in place of drop down icon.
How to do that?
In Firefox you can just add background image to option:
<select>
<option style="background-image:url(male.png);">male</option>
<option style="background-image:url(female.png);">female</option>
<option style="background-image:url(others.png);">others</option>
</select>
Better yet, you can separate HTML and CSS like that
HTML
<select id="gender">
<option>male</option>
<option>female</option>
<option>others</option>
</select>
CSS
select#gender option[value="male"] { background-image:url(male.png); }
select#gender option[value="female"] { background-image:url(female.png); }
select#gender option[value="others"] { background-image:url(others.png); }
In other browsers the only way of doing that would be using some JS widget library, like for example jQuery UI, e.g. using Selectable.
From jQuery UI 1.11, Selectmenu widget is available, which is very close to what you want.
With countries, languages or currency you may use emojis.
Works with pretty much every browser/OS that supports the use of emojis.
select {
height: 50px;
line-height: 50px;
font-size: 12pt;
}
<select name="countries">
<option value="NL">🇳🇱 Netherlands</option>
<option value="DE">🇩🇪 Germany</option>
<option value="FR">🇫🇷 France</option>
<option value="ES">🇪🇸 Spain</option>
</select>
<br /><br />
<select name="currency">
<option value="EUR">🇪🇺 € EUR 💶</option>
<option value="GBP">🇬🇧 £ GBP 💷</option>
<option value="USD">🇺🇸 $ USD 💵</option>
<option value="YEN">🇯🇵 ¥ YEN 💴</option>
</select>
You can use iconselect.js; Icon/image select (combobox, dropdown)
Demo and download; http://bug7a.github.io/iconselect.js/
HTML usage;
<div id="my-icon-select"></div>
Javascript usage;
var iconSelect;
window.onload = function(){
iconSelect = new IconSelect("my-icon-select");
var icons = [];
icons.push({'iconFilePath':'images/icons/1.png', 'iconValue':'1'});
icons.push({'iconFilePath':'images/icons/2.png', 'iconValue':'2'});
icons.push({'iconFilePath':'images/icons/3.png', 'iconValue':'3'});
iconSelect.refresh(icons);
};
My solution is to use Font Awesome and then add library icons as text, using the unicode in HTML directly.
You just need the Unicode value for whatever icon you want, and they are all found here: Font Awesome full list of icons, including unicode
Here is an example state filter:
<select name='state' style='height: 45px; font-family:Arial, Font Awesome;'>
<option value=''> All States</option>
<option value='enabled' style='color:green;'> Enabled</option>
<option value='paused' style='color:orange;'> Paused</option>
<option value='archived' style='color:red;'> Archived</option>
</select>
Note the font-family:Arial, FontAwesome; is required to be assigned in style for select like given in the example.
You already have several answers that suggest using JavaScript/jQuery. I am going to add an alternative that only uses HTML and CSS without any JS.
The basic idea is to use a set of radio buttons and labels (that will activate/deactivate the radio buttons), and with CSS control that only the label associated to the selected radio button will be displayed. If you want to allow selecting multiple values, you could achieve it by using checkboxes instead of radio buttons.
Here is an example. The code may be a bit messier (specially compared to the other solutions):
.select-sim {
width:200px;
height:22px;
line-height:22px;
vertical-align:middle;
position:relative;
background:white;
border:1px solid #ccc;
overflow:hidden;
}
.select-sim::after {
content:"▼";
font-size:0.5em;
font-family:arial;
position:absolute;
top:50%;
right:5px;
transform:translate(0, -50%);
}
.select-sim:hover::after {
content:"";
}
.select-sim:hover {
overflow:visible;
}
.select-sim:hover .options .option label {
display:inline-block;
}
.select-sim:hover .options {
background:white;
border:1px solid #ccc;
position:absolute;
top:-1px;
left:-1px;
width:100%;
height:88px;
overflow-y:scroll;
}
.select-sim .options .option {
overflow:hidden;
}
.select-sim:hover .options .option {
height:22px;
overflow:hidden;
}
.select-sim .options .option img {
vertical-align:middle;
}
.select-sim .options .option label {
display:none;
}
.select-sim .options .option input {
width:0;
height:0;
overflow:hidden;
margin:0;
padding:0;
float:left;
display:inline-block;
/* fix specific for Firefox */
position: absolute;
left: -10000px;
}
.select-sim .options .option input:checked + label {
display:block;
width:100%;
}
.select-sim:hover .options .option input + label {
display:block;
}
.select-sim:hover .options .option input:checked + label {
background:#fffff0;
}
<div class="select-sim" id="select-color">
<div class="options">
<div class="option">
<input type="radio" name="color" value="" id="color-" checked />
<label for="color-">
<img src="http://placehold.it/22/ffffff/ffffff" alt="" /> Select an option
</label>
</div>
<div class="option">
<input type="radio" name="color" value="red" id="color-red" />
<label for="color-red">
<img src="http://placehold.it/22/ff0000/ffffff" alt="" /> Red
</label>
</div>
<div class="option">
<input type="radio" name="color" value="green" id="color-green" />
<label for="color-green">
<img src="http://placehold.it/22/00ff00/ffffff" alt="" /> Green
</label>
</div>
<div class="option">
<input type="radio" name="color" value="blue" id="color-blue" />
<label for="color-blue">
<img src="http://placehold.it/22/0000ff/ffffff" alt="" /> Blue
</label>
</div>
<div class="option">
<input type="radio" name="color" value="yellow" id="color-yellow" />
<label for="color-yellow">
<img src="http://placehold.it/22/ffff00/ffffff" alt="" /> Yellow
</label>
</div>
<div class="option">
<input type="radio" name="color" value="pink" id="color-pink" />
<label for="color-pink">
<img src="http://placehold.it/22/ff00ff/ffffff" alt="" /> Pink
</label>
</div>
<div class="option">
<input type="radio" name="color" value="turquoise" id="color-turquoise" />
<label for="color-turquoise">
<img src="http://placehold.it/22/00ffff/ffffff" alt="" /> Turquoise
</label>
</div>
</div>
</div>
Another jQuery cross-browser solution for this problem is http://designwithpc.com/Plugins/ddSlick which is made for exactly this use.
This is using ms-Dropdown : https://github.com/marghoobsuleman/ms-Dropdown
Data resource is json. But you dont need to use json. If you want you can use with css.
Css example : https://github.com/marghoobsuleman/ms-Dropdown/tree/master/examples
Json Example : http://jsfiddle.net/tcibikci/w3rdhj4s/6
HTML
<div id="byjson"></div>
Script
<script>
var jsonData = [
{description:'Choos your payment gateway', value:'', text:'Payment Gateway'},
{image:'https://via.placeholder.com/50', description:'My life. My card...', value:'amex', text:'Amex'},
{image:'https://via.placeholder.com/50', description:'It pays to Discover...', value:'Discover', text:'Discover'},
{image:'https://via.placeholder.com/50', title:'For everything else...', description:'For everything else...', value:'Mastercard', text:'Mastercard'},
{image:'https://via.placeholder.com/50', description:'Sorry not available...', value:'cash', text:'Cash on devlivery', disabled:true},
{image:'https://via.placeholder.com/50', description:'All you need...', value:'Visa', text:'Visa'},
{image:'https://via.placeholder.com/50', description:'Pay and get paid...', value:'Paypal', text:'Paypal'}
];
$("#byjson").msDropDown({byJson:{data:jsonData, name:'payments2'}}).data("dd");
}
</script>
For those wanting to display an icon, and accepting a "black and white" solution, one possibility is using character entities:
<select>
<option>100 €</option>
<option>89 £</option>
</select>
By extension, your icons can be stored in a custom font.
Here's an example using the font FontAwesome: https://jsfiddle.net/14606fv9/2/
https://jsfiddle.net/14606fv9/2/
One benefit is that it doesn't require any Javascript.
However, pay attention that loading the full font doesn't slow down the loading of your page.
Nota bene:
The solution of using a background image doesn't seem working anymore in Firefox (at least in version 57 "Quantum"):
<select>
<option style="background-image:url(euro.png);">100</option>
<option style="background-image:url(pound.png);">89</option>
</select>
For a two color image, you can use Fontello, and import any custom glyph you want to use. Just make your image in Illustrator, save to SVG, and drop it onto the Fontello site, then download your custom font ready to import. No JavaScript!
Alvaros JS free answer was a great start for me, and I really tried to get a truly JS-free answer that still delivered all the functionality expected of a Select with images, but sadly nesting forms was the down-fall. I'm posting two solutions here; my main solution that uses 1 line of JavaScript, and a totally JavaScript-free solution that won't work inside another form, but might be useful for nav menus.
Unfortunately there is a bit of repetition in the code, but when you think about what a Select does it makes sense. When you click on an option it copies that text to the selected area, i.e., clicking 1 of 4 options will not change the 4 options, but the top will now repeat the one you clicked. To do this with images would require JavaScript, orrrr... you duplicate the entries.
In my example we have a list of games (Products), which have versions. Each product may also have Expansions, which can also have versions. For each Product we give the user a list of each version if there's more than one, along with an image and version specific text.
<h4>#Model.Name</h4>
#if (Model.Versions.Count == 1)
{
<div class="rich-select-option-body pl-2">
<img src="#Model.Versions[0].ImageUrl" alt="">#Model.Versions[0].VersionName (#Model.Versions[0].Year)
</div>
}
else
{
<h5>Select the version</h5>
<div class="rich-select custom-select">
<div class="rich-select-dropdown">
#foreach (var version in Model.Versions)
{
<div class="rich-select-option">
<input type="radio" name="game" id="game-#version.ProductId-#version.VersionId" #if (version == Model.Versions.First()) { #Html.Raw(" checked") ; } />
<div class="rich-select-option-body">
<label tabindex="-1">
<img src="#version.ImageUrl" alt="">#version.VersionName (#version.Year)
</label>
</div>
</div>
}
</div>
<input type="checkbox" id="rich-select-dropdown-button" class="rich-select-dropdown-button" />
<label for="rich-select-dropdown-button"></label>
<div class="rich-select-options">
#foreach (var version in Model.Versions)
{
<div class="rich-select-option">
<div class="rich-select-option-body">
<label for="game-#version.ProductId-#version.VersionId" tabindex="-1" onclick="document.getElementById('rich-select-dropdown-button').click();">
<img src="#version.ImageUrl" alt=""> #version.VersionName (#version.Year)
</label>
</div>
</div>
}
</div>
</div>
}
Using JS for the checkbox deselection we can have multiple instances on a form. Here I've extended to show a list of Expansions, which also have the same logic around versions.
<h5 class="mt-3">Include Expansions?</h5>
#foreach (var expansion in Model.Expansions)
{
<div class="form-row">
<div class="custom-control custom-checkbox w-100">
<input type="checkbox" class="expansion-checkbox custom-control-input" id="exp-#expansion.ProductId">
<label class="custom-control-label w-100" for="exp-#expansion.ProductId">
#if (expansion.Versions.Count == 1)
{
<div class="rich-select-option-body pl-2">
<img src="#expansion.ImageUrl" />#expansion.Name: #expansion.Versions[0].VersionName (#expansion.Versions[0].Year)
</div>
}
else
{
<div class="rich-select custom-select">
<div class="rich-select-dropdown">
#foreach (var version in expansion.Versions)
{
<div class="rich-select-option">
<input type="radio" name="exp-#version.ProductId" id="exp-#version.ProductId-#version.VersionId" #if (version == expansion.Versions.First()) { #Html.Raw(" checked") ; } />
<div class="rich-select-option-body">
<label tabindex="-1">
<img src="#version.ImageUrl" alt="">#expansion.Name: #version.VersionName (#version.Year)
</label>
</div>
</div>
}
</div>
<input type="checkbox" id="rich-select-dropdown-button-#expansion.ProductId" class="rich-select-dropdown-button" />
<label for="rich-select-dropdown-button-#expansion.ProductId"></label>
<div class="rich-select-options">
#foreach (var version in expansion.Versions)
{
<div class="rich-select-option">
<div class="rich-select-option-body">
<label for="exp-#version.ProductId-#version.VersionId" tabindex="-1" onclick="document.getElementById('rich-select-dropdown-button-#expansion.ProductId').click();">
<img src="#version.ImageUrl" alt="">#expansion.Name: #version.VersionName (#version.Year)
</label>
</div>
</div>
}
</div>
</div>
}
</label>
</div>
</div>
Of course this requires a fair bit of CSS, which I've only included in this JSFiddle to reduce the size of this already massive answer. I've used Bootstrap 4 to reduce the amount needed, and also to allow it to fit in with other Bootstrap controls and any site customisations that have been made.
The images are set to 75px, but this can easily be changed in 5 lines in .rich-select and .rich-select-option-body img
I propose an alternative
when I'm in a difficult situation like this using dxlookup from devexpress
Examples:https://js.devexpress.com/Demos/WidgetsGallery/Demo/Lookup/Templates/jQuery/Light/
I tried several jquery based custom select with images, but none worked in responsive layouts. Finally i came accross Bootstrap-Select. After some modifications i was able to produce this code.
Code and github repo here
I got the same issue. My solution was a foreach of radio buttons, with the image at the right of it. Since you can only choose a single option at radio, it works (like) a select.
Worked well for me.
I was struggling with the same problem: how to create a language selector with flags. I came up with a :ḧover solution without javascript. It does involve some server-side processing to set a class in the HTML.
The code can be easily generated from PHP or nodejs or Angular/Typescript. In this example there are 3 images contained in an A-element (< a href='./?lang=..."> ).
The trick is that you should fetch the URL GET parameter lang and set the class selected so it will be the only one visible.
The CSS hinges on the fact that there is only one flag visible based on the class selected being present. When the mouse hovers over the container (<div class="languageselect">.....</div>) the CSS will show all flags by overriding the classes div.flag:not(.selected) and div.flag.selected and setting display:block . Then the <a href="..."> will be available to the users.
Of course there is lots of other styling possible to increase useability. This is just a starting point.
Please note the first part of the CSS-line will put the language selector on top on a fixed position. This also helps prevent the flag-container to span a whole line, messing up the :hover detection.
Happy coding!
WOrking example here: codepen
HTML:
<div class="languageselect">
<div class="select">
<div class="flag ">
<a href="./?lang=en">
<img src="https://www.sciencekids.co.nz/images/pictures/flags120/United_Kingdom.jpg">
</a>
</div>
<div class="flag selected">
<a href="./?lang=en_us">
<img src="https://www.sciencekids.co.nz/images/pictures/flags120/United_States.jpg">
</a>
</div>
<div class="flag ">
<a href="./?lang=nl">
<img src="https://www.sciencekids.co.nz/images/pictures/flags96/Netherlands.jpg">
</a>
</div>
</div>
</div>
CSS:
.languageselect {
position: absolute;
top: 0;
left:0;
z-index: 1000;
}
.languageselect img {
max-height: 20px;
}
.languageselect div.flag:not(.selected) {
display: none;
}
.languageselect div.flag.selected {
display: block;
}
.languageselect:hover div.flag {
display:block;
}
UPDATE: As of 2018, this seems to work now. Tested in Chrome, Firefox, IE and Edge
UPDATE: Yes I changed the background-color, not the image, stop voting me down, showing that you can change style here is still a useful contribution.
<!DOCTYPE html>
<html>
<body>
<style>
select#newlocale option[value="volvo"] { background-color: powderblue; }
select#newlocale option[value="opel"] { background-color: red; }
select#newlocale option[value="audi"] { background-color: green; }
</style>
<select id="newlocale">
<option value="volvo"><div >Volvo</div></option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</body>
</html>

how to set value in text area

I'm working on the playground using from codemirror.net, and is works great. My next step is to have auto load set a value to file path name, each textarea will load file path from .html, .css and jquery.
currently in codemirror showing
<div id="wrap">
<!-- Code Editors --> <section id="code_editors">
<div id="html" class="code_box">
<h3>HTML</h3>
<textarea name="html"></textarea>
</div>
<div id="css" class="code_box">
<h3>CSS</h3>
<textarea name="css"></textarea>
</div>
<div id="js" class="code_box">
<h3>JavaScript</h3>
<textarea name="js"></textarea>
</div> </section>
<!-- Sandboxing --> <section id="output">
<iframe></iframe> </section> </div>
The result of preview textarea showed "Hello world" that because in javascript showed
html_editor.setValue('<p>Hello World</p>');
css_editor.setValue('body { color: red; }');
so i change set value in codemirror like this.
<textarea name="html"><?php
echo file_get_contents('testcode.php');
?>
</textarea>
</div>
this works great when I see HTML code inside of text area but unable to see the preview in the text area.
so I'm trying to solve this how to see preview too using
<?php echo file_get_contents('testcode.php');?>
I thought to make change in javascript where it said
html_editor.setValue('<p>Hello World</p>');
css_editor.setValue('body { color: red; }');
my question is that how can I write code in PHP inside of javascript file.
i tried
html_editor.setValue('<?php echo file_get_contents('testcode.php');?>');
css_editor.setValue('body { color: red; }');
it does not work.
Any other idea how to solve this to make both works!
many thanks.
AM
Try this :
var = "<?php echo file_get_contents('testcode.php')?>";
html_editor.setValue(var );
css_editor.setValue('body { color: red; }');

How to print some specific part of a page via window.print()

i'm working on a form in php mysql. so in my page there is a form and below that i shown the data of that form in table format.now i want to print only the table structure thats why i just made a PRINT button as:
<span style="float:right;">PRINT</span>
but it will print the whole page with form field and table and i just want the tableto print.
Here is the design of my whole page with form and table:
<html>
<head></head>
<body>
<div class="container">
<form class="form-horizontal" action="" method="post" name="userform1" id="company-form" enctype="multipart/form-data">
<?php if($_GET[id]){?>
<fieldset>
<legend>Add Company</legend>
<div class="control-group">
<label class="control-label">Company Name</label>
<div class="controls">
<input type="text" name="company" id="company" value="<?php echo $selup['company']?>">
</div>
</div>
<div class="control-group">another field</div>
<div class="control-group">another field</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn" name="submit" id="submit" value="Submit">Submit</button>
</div>
</div>
<table class="table table-bordered">
<tbody>
<tr>
<td>S.No.</td>
<td>Company Name</td>
<td>Type</td>
<td>Action</td>
</tr>
<?php
// to print the records
$select = "select * from company where type='Miscellaneous'";
$query1 = mysql_query($select);
while($value = mysql_fetch_array($query1)){ ?>
<tr>
<td><?php echo $value[id];?></td>
<td><?php echo $value[company ];?></td>
<td><?php echo $value[type];?></td>
<!--<td> </td>-->
<?php /*?><td><?php echo $value[amount];?></td>
<td><?php echo $value[date];?></td><?php */?>
<td><i class="icon-edit"></i>
<i class="icon-trash"></i></td>
</tr><?php }?>
</tbody>
</table>
</fieldset>
<form>
</div>
</body>
so i just want to print the table not whole page.
Use css to hide elements you don't want to print:
#media print {
.control-group {
display: none;
}
}
function printContent(el){
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My page</h1>
<div id="div1">DIV 1 content...</div>
<button onclick="printContent('div1')">Print Content</button>
<div id="div2">DIV 2 content...</div>
<button onclick="printContent('div2')">Print Content</button>
<p id="p1">Paragraph 1 content...</p>
<button onclick="printContent('p1')">Print Content</button>
</body>
</html>
You could make a print-css (which does the same as #media print, but I think it is cleaner, and you can disable the css include via javascript, if you need it):
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
In that css, you hide all elements which should not get printed, for example:
.wrapper, .header {display: none;}
One posible solution, perhaps not the best option:
1. Open a new window with JS
2. Copy the whole table into the new window (with jQuery for example)
3. Print the new window
4. Close the window
Sure it has a blink effect but It will work.

Wordpress PHP if else

I have to say that I'm a newbie when it comes to php , but still this code seems to make sense. I'm trying to display a form in 2 different ways - one way if it's on the page 'cotatie-seo' and another way if it's on any other page in the site. The code I've used is:
<div style="position: relative; float: left;">
<p>Nume (required)<br />
[text* your-name] </p>
<p>Adresă Email (required)<br />
[email* your-email] </p>
<p>Adresă website (required)<br />
[text* Website]</p>
<?php if(is_page('cotatie-seo')) { ?>
</div>
<div style="position: relative; float: left;">
<p>[textarea* observatii 30x10 id:observatii] </p>
</div>
<?php } else { ?>
<p>[textarea* observatii 30x10 id:observatii] </p>
</div>
<?php } ?>
<p>[submit "Trimite"]</p>
If it's not on the cotatie-seo page it displays the form properly, with the text area under the rest of the fields, but when it's on the cotatie-seo page the text area displays both in the first div and in the second div (so it is displayed twice, both under the rest of the fields and next to them).
Thank you in advance for the help!
Thanks for the fast reply! The function is the regular Wordpress is_page function:
function is_page( $page = '' ) { global $wp_query;
if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; }
return $wp_query->is_page( $page ); }
I'm sorry but I can't post images and I'm building the site on localhost, so I can't provide a preview of the output.
Cheers!
One thing to try would be moving this bit:
<p>[textarea* observatii 30x10 id:observatii] </p>
</div>
outside of the if-else (to just above the submit), and then dropping the else entirely since you repeat these lines in both if and else. Your snippet above would then be:
<div style="position: relative; float: left;">
<p>Nume (required)<br />
[text* your-name] </p>
<p>Adresă Email (required)<br />
[email* your-email] </p>
<p>Adresă website (required)<br />
[text* Website]</p>
<?php if(is_page('cotatie-seo')) { ?>
</div>
<div style="position: relative; float: left;">
<?php } ?>
<p>[textarea* observatii 30x10 id:observatii] </p>
</div>
<p>[submit "Trimite"]</p>

how to generate html with php to return after ajax call

I generate all my html on my page with ajax calls and never refresh my page. My setup is something like
HTML: <a id="user_click_here">test link</a>
JQUERY:
$("#user_click_here").live("click", function(event){
console.log("click on test link");
ajax_function("action=return_some_html");
});
The ajax function calls php, where I create the html. What I struggle with is to generate html with php. I try to use this:
PHP:
$html = <<<HTML
<div class="box">
<h2>
$text[0]
</h2>
<div class="block">
<div style="float:left; width: 35%; margin:5px; padding: 1em; background: white;">
HTML;
$html .= '<p>Username: <a id="username">' . $_SESSION['username'] . '</a></p>';
$html .= <<<HTML
<div style="float:left; width: 30%; margin:5px;">
<p>
Level:<br />
Weapon:<br />
Power:<br />
Bullets:<br />
</p>
</div>
<div style="float:right; width: 60%; margin:5px;">
<p>
HTML;
$html .= '<b id="level">empty</b><br/>';
$html .= <<<HTML <---ERROR HERE unexpected '<<'
Weapon blabla<br />
2 - 5<br />
3/6<br />
</p>
</div>
</div>
I tend to just try and fail until it works with this <<<WHATEVER (dont remember what it's called). Like now where I get an unexpected '<<' error for some reason.
Do I have to use this method:
$html = '<div class="box">
<h2>
' . $text[0] . '
</h2>
<div class="block">
<div style="float:left; width: 35%; margin:5px; padding: 1em; background: white;">';
?
What is the best way to save html in php and send it back to jquery.
I send the html like this now:
PHP:
$data = array("html" => $html);
return json_encode( $data );
Off course I want it compressed as much as possible, preferably without any stuff like this: \n\t\t\t\t to take up space.
EDIT:
Ok. I don't think everybody noticed the fact that this is an ajax call and I have to return a json element. I cannot do the common <?php php code ?> html code <?php more php ?> some html
It looks like your last HEREDOC (that's what the <<< syntax is called) is unclosed, missing it's
HTML;
And don't forget that the final HTML; cannot have any whitespace on the same line before or after it.
However, you're going about it all wrong. The great thing about the HEREDOC syntax is that you can embed all your variables into it without requiring any concatenation. Just create the whole thing in one HEREDOC and echo it out to jQuery. There's no need to make it JSON if you are just going to use it as HTML when received by the AJAX call.
All your code above belongs inside one $html = <<<HTML block. Enclose all your complex variables like $_SESSION['whatever'] in {} {$_SESSION['whatever']}.
$html = <<<HTML
<div class="box">
<h2>
{$text[0]}
</h2>
<div class="block">
<div style="float:left; width: 35%; margin:5px; padding: 1em; background: white;">
<p>Username: <a id="username"> {$_SESSION['username']}</a></p>
<div style="float:left; width: 30%; margin:5px;">
<p>
Level:<br />
Weapon:<br />
Power:<br />
Bullets:<br />
</p>
</div>
<div style="float:right; width: 60%; margin:5px;">
<p>
<b id="level">empty</b><br/>
<!--etc -->
<!--etc -->
HTML;
// Now just echo it back to the AJAX caller as HTML
echo $html;
exit();
Don't use HEREDOC. It's messy, and should only be used when you need to store long strings in a variable.
Try writing out the HTML page you expect to be returned as if it was a normal HTML page. Where you need PHP output (a variable, array value, etc.), begin a PHP tag, echo the value, and then end the PHP tag. This is much easier than trying to use heredoc.
<div class="box">
<h2><?php echo $text[0]; ?> </h2>
<div class="block">
<div style="float:left; width: 35%; margin:5px; padding: 1em; background: white;">
<p>Username: <a id="username"><?php echo $_SESSION['username']; ?></a></p>
<div style="float:left; width: 30%; margin:5px;">
<p>Level:<br />Weapon:<br />Power:<br />Bullets:<br /></p>
</div>
<div style="float:right; width: 60%; margin:5px;">
<p><strong id="level">empty</b><br />Weapon blabla<br />2 - 5<br />3/6<br /></p>
</div>
</div>
If you're worried about line breaks (you shouldn't be), you can add an output handler that removes them.
ob_start("clean_linebreaks");
function clean_linebreaks($input) {
return str_replace("\n", "", str_replace("\r", "", $input));
}
Also, may I suggest using tables instead of floated divs. The level, weapon, and power will be easier to line up with their values if you use a table.

Categories