Click event on button doesn't seem to fire

I'm not new to HTML or JavaScript, though I don't use them often. I am, however, very new to PHP, and am currently facing a weird issue when trying to get a click event on a button in my HTML which is imbedded in PHP:

I'm not new to HTML or JavaScript, though I don't use them often. I am, however, very new to PHP, and am currently facing a weird issue when trying to get a click event on a button in my HTML which is imbedded in PHP:

<?php
session_start();
if(!(IsSet($_SESSION["username"])) && $_SESSION["username"] == "") {
?>
<!DOCTYPE html>
<html lang="de">
<head>
<title>Blah</title>
<meta charset="utf-8">
</head>
<body>
<button type="button" onclick="function() { alert('Moo!'); }">Some button</button>
</body>
</html>
<?php
} else {
}
?>

Nothing happens when I click on the button. Yes, there's of course more markup in the original, but it's not relevant to my question. The W3C markup validation service says there are no errors, and when I alert moo from a script at the bottom of the body tag it works fine as well. It looks like the click event doesn't fire... Any idea why?

Render HTML with Vanilla JavaScript and lit-html

Render HTML with Vanilla JavaScript and lit-html

Sometimes you need to render HTML elements on a web page. And like Goldilocks' search for "just right", you have to try a few techniques before you find the right one. Using a framework may be too hard. Using pure HTML and the DOM API may be too soft. What you need is something in the middle that is just right. Is lit-html "just right"? Let's find out.

Sometimes you need to render HTML elements on a web page. And like Goldilocks' search for "just right", you have to try a few techniques before you find the right one. Using a framework may be too hard. Using pure HTML and the DOM API may be too soft. What you need is something in the middle that is just right. Is lit-html "just right"? Let's find out.

First, I'll show how this all works. Then at the end of this article, I'll explain everything you need to get started with lit-html to try this for yourself.

When you're done, you can push your HTML app with lit-html to the cloud to see it in all of its glory! I included a link to a free Azure trial, so you can try it yourself.

Resources:

The Sample App

Here is the app I'll demonstrate in this article. It fetches a list of heroes and renders them when you click the button. It also renders a progress indicator while it is fetching.

What's the Value of lit-html

When you focus on rendering content, and nothing else, lit-html is a good fit. It works closely with the DOM to render content, and refresh it in an optimal manner. The docs can provide you with more details, but the basic code for lit-html looks like this.

// Credit: As seen in official docs https://lit-html.polymer-project.org/guide/getting-started

// Import lit-html
import { html, render } from 'lit-html';

// Define a template
const myTemplate = name =>
  html`
    <p>Hello ${name}</p>
  `;

// Render the template to the document
render(myTemplate('World'), document.body);

You import lit-html, define a template, then render it to the DOM. That's it!

Rendering HTML

A progress bar is fairly basic. There is some HTML, and we show it when needed and hide it when it is not required. While we could use a template, or innerHTML, or the DOM API for this, let's see what this would look like with lit-html.

First, we get a reference to the element in the DOM where the progress bar will appear.

Then we define the template. This code looks and feels like JSX (or TSX). The advantage here is that you can write the HTML. You wrap the HTML in a template string (notice the back-tick character is used and not a single quote). Template strings allow you to span lines and insert variables where needed (we'll see this soon). The magic that makes this work is the html tag that precedes the template string. The html tag is what tells lit-html that you are about to define a template.

Next, we compile the template and pass those results to lit-html's render function, which places the results in the DOM. Finally, we hide or show the progress bar as needed.

function showProgress(show = true) {
  const container = document.getElementById('progress-placeholder');

  const template: () => TemplateResult = () => html`
    <progress class="progress is-medium is-info" max="100"></progress>
  `;
  const result = template();
  render(result, container);

  container.style.display = show ? 'block' : 'none';
}

Now you can run this showProgress function any time you want to show the progress bar.

Note that when a template is re-rendered, the only part that is updated is the data that changed. If no data changed, nothing is updated.

Rendering HTML with Dynamic Values

The progress bar does not change each time it is rendered. You will have situations where you want your HTML to change. For example, you may have a message area on your web app that shows a styled message box with a title and a message. The title and message will change every time you show the message area. Now you have dynamic values.

The HTML is defined with a template string, so it is trivial to add a variable into it. Notice the code below adds a title and text into the template, using the ${data.title} and ${data.text} syntax, respectively.

Then the template is compiled and rendered were needed.

When this template is re-rendered, the only part that is updated is the data that changed. In this case, that's the title and text.

function showMessage(text: string, title = 'Info') {
  const template: (data: any) => TemplateResult = (data: Message) => html`
    <div id="message-box" class="message is-info">
      <h3 class="message-header">${data.title}</h3>
      <p class="message-body">${data.text}</p>
    </div>
  `;

  const el = document.getElementById('message-placeholder');
  const result = template({ title, text });
  render(result, el);

  el.style.visibility = !!text ? 'visible' : 'hidden';
}

Rendering a List

Things get a little more real when we render a list. Let's think about that for a moment. A list requires that we have a plan if there is data and a backup plan if there is no data. A list requires that we render the same thing for each row, and we don't know how many rows we have. A list requires that we pass different values for each row, too. Then we have to take the rows and wrap them in a container such as a <ul> or a <table>.

So there is a little more logic here, regardless of whether we use lit-html or any other technique. Let's explore how the replaceHeroList function renders the rows using lit-html.

function replaceHeroList(heroes?: Hero[]) {
 const heroPlaceholder = document.querySelector('.hero-list');

 // Define the template
 let template: () => TemplateResult;

 if (heroes && heroes.length) {
   // Create the template for every hero row
   template = createList();
 } else {
   // Create the template with a simple "not found" message
   template = () =>
     html`
       <p>heroes not found</p>
     `;
 }

 // Compile the template
 const result = template();

 // Render the template
 render(result, heroPlaceholder);

Notice that when there are heroes, we call the createList function. This function begins by creating an array of TemplateResult. So for every hero in the heroes array, we define a template that represents the <li> containing the HTML that displays that respective hero.

Then we create another template that contains the <ul> and embeds the array of hero templates. It's pretty cool that we can embed templates like this! Finally, we return it all and let the logic compile the templates and render them.

function createList() {
  // Create an array of the templates for each hero
  const templates: TemplateResult[] = heroes.map(hero => {
    return html`
      <li>
        <div class="card">
          <div class="card-content">
            <div class="content">
              <div class="name">${hero.name}</div>
              <div class="description">${hero.description}</div>
            </div>
          </div>
        </div>
      </li>
    `;
  });

  // Create a template that includes the hero templates
  const ulTemplate: () => TemplateResult = () =>
    html`
      <ul>
        ${templates}
      </ul>
    `;
  return ulTemplate;
}

Summary

When you want to render HTML, lit-html is a fast and light-weight option. Is it better than using templates and the DOM API? You'll have to decide what is best for you. But the real story here is that you have another great option to consider when determining the right tool for your job.

Prologue

You can also get editor help with your lit-html templates. Notice the image below shows the syntax highlighting for the HTML template!

Setup

You can install the lit-html package with npm.

npm install lit-html

Alternately you can load it directly from the unpkg.com CDN

import { html, render } from 'https://unpkg.com/lit-html?module';

You have a choice here. npm is my preference, but feel 100% free to use the CDN if that suits you.

TypeScript and lit-html

You only need to include the library for lit-html and you're done. But I like to use TypeScript, and I absolutely recommend enabling your tooling to work great with typeScript and lit-html.

Let me be very clear here - you do not need TypeScript. I choose to use it because it helps identify mistakes while I write code. If you don't want TypeScript, you can opt to use plain JavaScript.

Here are the steps to make TypeScript and lit-html light up together:

  1. Install TypeScript support for lit-html
  2. Configure your tsconfig.json file
  3. Install the VS Code extension for lit-html

Run this command to install the plugin and typescript, as development dependencies to your project.

npm install --save-dev typescript-lit-html-plugin typescript

Edit your tsconfig.json by adding the following to your compilerOptions section.

"compilerOptions": {
  "plugins": [
    {
      "name": "typescript-lit-html-plugin"
    }
  ]
}

Finally, install the VS Code extension for lit-html.

Now you get syntax highlighting for all of your lit-html templates!

How to Include PHP in HTML

How to Include PHP in HTML

Welcome to this article on how to use PHP in HTML! Here, we try to get specific about exactly how PHP and HTML interact, at the level of a specific .php file. In other words, how do you actually include PHP in HTML, and what rules can and can’t you follow in weaving PHP and HTML together?

Welcome to this article on how to use PHP in HTML! Here, we try to get specific about exactly how PHP and HTML interact, at the level of a specific .php file. In other words, how do you actually include PHP in HTML, and what rules can and can’t you follow in weaving PHP and HTML together?

As a last note: to learn what works and doesn’t for using PHP in HTML, concrete examples are more helpful than theory. So the bulk of this article is examples of PHP’s proper use within HTML, with comments for each code example.

How to Include PHP in HTML: File Types and Other Considerations

The first thing to know is that, by default, you can’t use PHP in HTML files, meaning files that end with .html. It’s possible to configure your server to allow PHP in .html files, but that’s outside our scope—so for now, just remember that, if you want to write PHP, you want to be working with .php files.

In a WordPress environment, that’s largely taken care of: the entirety of WordPress is PHP-based, so you will very frequently be working with .php files, and almost never with .html files.

The other thing you should know is this: a .php file can run exactly like a .html file, with absolutely no PHP. In other words, there’s nothing about a .php file that makes it inherently “different” than a .html file, except that it can run PHP.

A few code examples will make it clearer what we mean by this.

HOW .HTML FILES RESPOND TO HTML AND PHP

Imagine we have a file, index.html, that has the following contents:

<!-- Filename: index.html -->
<h1>I am HTML markup.</h1>

Accessing this index.html file in your web browser would give you the following output: <h1>I am HTML markup.</h1>

Now what if we added the following to index.html:

<!-- Filename: index.html -->
<h1>I am HTML markup.</h1><?php echo '<p>And I am PHP.</p>'; ?>

Accessing this index.html file in your web browser would give you the following output: <h1>I am HTML markup.</h1><?php echo '<p>And I am PHP.</p>'; ?> Definitely not what we want. The issue is that, by default, HTML files don’t “speak” PHP.

HOW .PHP FILES RESPOND TO HTML AND PHP

Now, what if we simply renamed index.html to index.php and ran both examples again?

<!-- Filename: index.php -->
<h1>I am HTML markup.</h1>

This would output <h1>I am HTML markup.</h1>, exactly as before. In other words, there’s no need to actually write PHP into .php files: PHP files handle plain HTML just fine.

Here’s the second example:

<!-- Filename: index.php -->
<h1>I am HTML markup.</h1><?php echo '<p>And I am PHP.</p>'; ?>

This would output the following clean HTML: <h1>I am HTML markup.</h1><p>And I am PHP.</p>

This example demonstrates that PHP files (that is, .php files) can automatically interpret PHP code—anything inside the <?php ?> tag—and turn the resulting output into HTML.

Basic Use of PHP in HTML

Here are the basics of how to include PHP in HTML. This relies on knowledge of PHP’s echo statement, which we’ve covered in a previous article.

PRINTING HTML CONTENT WITH PHP’S ECHO

To output HTML content within PHP, echo it:

<div><?php echo 'Hello'; ?></div>

Output to browser will be: <div>Hello</div>

OUTPUTTING HTML TAGS USING PHP

You can use PHP to output HTML tags into the page’s markup:

<div><?php echo '<p>Hello</p>'; ?></div>

Output to browser will be: <div><p>Hello</p></div>

USING PHP INSIDE HTML TAGS

PHP can go anywhere, including inside HTML tag declarations, and including inside quotes ("):

<div class="<?php echo 'big-element'; ?>">Hello</div>

Output to browser will be: <div class="big-element">Hello</div>

Details on Opening and Closing the PHP Tag in HTML

This section relies on a basic understanding of PHP functions, which we’ve covered in an earlier article.

OPENING AND CLOSING THE PHP TAG

You can swap between HTML and PHP at any time by opening (<?php) and closing (?>) the PHP tag:

<?php echo '<p>I came from PHP.</p>' ?><p>And I came from HTML.</p><?php echo '<p>Back to PHP and '; ?>now HTML.</p>

Output to browser will be: <p>I came from PHP.</p><p>And I came from HTML.</p><p>Back to PHP and now HTML.</p>

LINE BREAKS IN PHP CODE

Line breaks (as well as spaces and indentation) can work any way within the PHP tag:

<?php

echo '<p>I am PHP.</p>';

echo '<p>Still PHP.</p>';

?><p>Now HTML.</p>

Output to browser will be: <p>I am PHP.</p><p>Still PHP.</p><p>Now HTML.</p>

HTML INSIDE PHP OPERATORS

HTML can go inside PHP operators of all kinds–such as if()-statements and functions, and will simply print like echo when the relevant lines of code are run.

<?php function print_greeting() { ?>
<p>HTML output from inside function.</p>
<?php } ?>

<?php print_greeting(); ?>

Output to browser will be <p>HTML output from inside function.</p>

Another way to describe this code example is to note that you can close a PHP tag, and revert to plain HTML, insidea function definition, if()-statement, or other PHP operator.

Those lines of HTML will print to the page when they are executed, which depends on the control flow of the PHP logic on the page.

DECLARATIONS FROM PREVIOUS <?PHP ?> TAGS ARE STILL STORED

PHP will remember variables, functions, and other declarations from previously opened and closed PHP tags higher on the page:

<?php function print_greeting() { ?>
<p>Hello from function.</p>
<?php } ?>

<div>Plain HTML between two PHP tags.</div>

<?php $my_string = '<p>Hello from variable.</p>'; ?>

<div>Plain HTML between two PHP tags again.</div>

<?php print_greeting();
echo $my_string; ?>

Output to browser will be: <div>Plain HTML between two PHP tags.</div><div>Plain HTML between two PHP tags again.</div><p>Hello from function.</p><p>Hello from variable.</p>

Controlling HTML Output with PHP Operators

PHP can control the logic flow across the page, altering output.

ITERATING HTML OUTPUT USING A WHILE() LOOP

Here’s an example that iterates (repeats) HTML output using a PHP while() loop:

<p>
$i = 0; // $i starts out at 0
// This while()-loop will keep running as long as $i is less than 3
<?php while( $i < 3; ) : ?>
<span>Hello</span>
$i++; // This means "increase $i by 1"
<?php endwhile; ?>
</p>

Output to browser will be: <p><span>Hello</span><span>Hello</span><span>Hello</span></p>

INSERTING DYNAMIC VALUES INTO HTML USING PHP

Inserting dynamic values—values that are not pre-defined, but change as variables—into HTML using a PHP while() loop:

<p>
<?php while( $i = 0; $i < 3; $i++ ) : ?>
<span>Number <?php echo $i; ?></span>
<?php endwhile; ?>
</p>

Output to browser will be: <p><span>Number 0</span><span>Number 1</span><span>Number 2</span></p>

This basic pattern—dynamic HTML output within a PHP while loop—is shared by WordPress’s content engine, the Loop.


CONTROLLING HTML OUTPUT USING PHP CONDITIONALS

You can control HTML output using PHP conditionals (if()-statements):

<?php if( 1 === 1 ) { ?>
<p>Now you see me</p>
<?php } ?>

<?php if( 1 === 2 ) { ?>
<p>Now you don't</p>
<?php } ?>

Output to browser will be: <p>Now you see me</p>

In the example above, we asked two things, one which is always true and one which is always false:

  1. “Does 1 equal 1?” (This is always true, so the code inside its if statement will alwaysrun, printing that HTML to the page.)
  2. “Does 1 equal 2?” (This is never true, so the code inside its if statement will neverrun, and its HTML does not print to the page.)
And That’s Our PHP-in-HTML Primer

Hopefully these code examples have given you a good sense of some of the basics of how to add PHP to HTML, and how PHP and HTML interact in practice.

Thanks for reading! If you liked this post, share it with all of your programming buddies!

Originally published on wpshout.com

PHP variable to JavaScript In Laravel

PHP variable to JavaScript In Laravel

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

However, we know the Laravel framework is having the largest community. Similarly, Laravel having large package base. So, sometimes it is easy to use package rather use custom code. Moreover, you can use existing packages.

Pass PHP variable to JavaScript

Many times you often find the need to pass PHP variable or string to the javascript file. But for this, you can use the below package.

Install package

Just copy below package and paste into the composer.json file.

"laracasts/utilities": "^2.1"

Or similarly from command line or terminal run command:

composer require laracasts/utilities

Provider

Further, add the Service provider into the config/app.php file. Which is used for the binding. After this, you will get Javascript facade.

'providers' => [
    '...',
    'Laracasts\Utilities\JavaScript\JavaScriptServiceProvider'
];

Publish the Configuration:

Finally, publish the config using the below command.

php artisan vendor:publish --provider="Laracasts\Utilities\JavaScript\JavaScriptServiceProvider"

Further, it will copy the javascript.js file to the config folder. There are two variable you can assign the values. Firstly, you can set bind_js_vars_to_this_view. This will set the name of the view. Basically, this is a partial view. If more than one view then you can set in array. Secondly, js_namespace is where you can define the namespace of the js variable. By default, Laracasts is the variable but you can change it to something else.

Usage in controller

Import the Dependency

You can initialize the JavaScript variable in the controller. Initialize and import into the controller.

use Javascript;

Set Variable

Now, you can define the variable into the controller using Javascript. You can set the values in the key-value pair. Assign a value to the key.

$array = [
    'key' => value_here,
];
 
JavaScript::put($array);

So, put your value into the JavaScript variable using the value of an array. Once you define into the array and assign to the variable you can access it into the js file.

Now, your controller will look like below.

<?php
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use JavaScript;
 
class VarController extends Controller
{
 
 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        \JavaScript::put([
            'foo' => 'bar',
            'user' => 'user',
            'time' => '2019-04-29'
        ]);
        return view('pages/home');
    }
}

Access In JS file

Now, your blade file will look like below.

@extends('layouts.default')
@section('content')
    <div style="text-align:center">
        <h1>PHP var to JavaScript</h1>
         
    </div>
     
@stop
@section('scripts')
<script src='assets/app.js'></script>
@stop

In js file, you can access the set variable into the Laracasts namespace. Which you define in the javascript.js file.

console.log(Laracasts.foo); // access foo variable
console.log(Laracasts.user);// access user variable
console.log(Laracasts.time);// access time variable

In this way, you can directly access the set variable. This will give simple access for getting value into the js file. There is a limitation for getting the value into the js file. So this package will give you direct access into js file.

In many cases, this will give you the simplest solution. Many developers have to face this problem in developement. So, this post will give some relief from this problem. Let me know if you face any issue.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!