Jump to content

PHP coded button


pepsinator
Go to solution Solved by gizmola,

Recommended Posts

<meta charset="utf-8">
<title>Work intergrated learning</title>



<style>

 #btnSubmit{
  padding: 10px;
  background-color: red;
  font-size: 20px;
  border-radius: 10px;
  font-weight: bolder;
  transition: background-color 2s ease Os;
  cursor: pointer;
 }

 #btnCancel{
  padding: 10px;
  background-color:yellow;
  font-size: 20px;
  border-radius: 10px;
  font-weight: bolder;
  transition: background-color 2s ease Os;
  cursor: pointer;
 }


 #btnSubmit:hover{
  background-color: green;
 }

 #btnCancel:hover{
  background-color: orange;
 }
</style>

<style>
    body {  
      font-size: 30px;
    }

    p {
      font-size:x-large;
    }  
  </style> 

 

This is my first task of creating a button using php code, it is my first time coding in php and i am so excited!!! 

 

<p>Creating a button</p>
<br>

<!--?php
if(isset($_POST['btn-atc'])){
   echo 'You have added an item to your shopping chart';
}
?-->

<input type="submit" name="btn-atc" value="Add to Cart">
<!--?php
$btnSubmit= $_POST['btnSubmit'];
if (btnSubmit){
   echo 'Your query has been successfully submited, our consultant will get in touch with you as soon as possible';}
   $btnCancel= $_POST['btnCancel'];
elseif(btnCancel){
echo 'You have cancelled your query.';
}
?-->

 <input type="submit" value="Submit query" id="btnSubmit"><br>
        <input type="submit" value="Cancel" id="btnCancel">
Link to comment
Share on other sites

Please in the future use the <> button to insert your code blocks.  Setting the language for the code block correctly is also nice.  We can assume here you have some php script (maybe index.php?), so I set the blocks to be of type PHP.  That causes PHP syntax highlighting to kick in, as it would in an editor.  I will edit your post to insert those blocks for you this time.

Link to comment
Share on other sites

  • Solution

There's a lot to work through here, so I'll start with this:

  • With CSS, always start with more general rules, then more specific ones.  You have multiple embedded style blocks here, and I'm not sure why, but your general rules were added after the specific ones
    • Keep in mind that styles "cascade" per the name.
      • You don't need to re-declare all the attributes for a modification.  Just use a modification class
        • Many popular css frameworks like tailwind depend on this idea
        •  
    • Getting familiar with a naming convention for css like BEM will help you create clear and logical css class names and avoid pitfalls and making your css inconsistent spaghetti
      • It also will help you keep things clear.  Use camel case for your PHP variables, and for class naming and general code formatting and style start with PSR-1 and perhaps graduate to PSR-12
        • It might not seem that important to you starting out, but it will help you get the most out of whatever editor/IDE you are using
          • Most people are using either PHPStorm (the choice of most pro's) or Visual Studio code with the Inteliphense plugin installed
            • If you go with vscode/Inteliphense make sure to read the installation instructions carefully and disable the built in plugin as directed
      • Take a look at my changes to your css and html markup to see how I implemented these ideas on your code
  • You rarely will want or need to use css id rules.  
    • ID's are reserved for a single instance on an page.  For buttons, you are typically re-using those styles throughout the page, so use css classes for those and not id's
      • Most css pros rarely/never use #name css styles.  If this is tutorial type stuff, might tell you something about the freshness of the tutorial
  • PHP code runs on/in the PHP server.  It does not run in the browser like javascript code that is included or embedded in the html page.
    • In other words, your PHP code will be run in response to a request, and returned immediately.
  • You can intermix html and PHP blocks inside a php script, and that will work fine, but the PHP code needs to be in a PHP block, which starts with <?php 
    • As you should be able to see here, you have commented out all the PHP code you wrote using html comments.  Thus none of that is going to run.
    • There is an alternate syntax that can be used to make everything look a bit cleaner if you plan to do a lot of intermixing
      • You can look up those options in the PHP manual.  It allows shorthand for echo, and if - then -else type constructs and other PHP loop
  • For superglobal array variable or array keys (or any other variable that may or may not exist) you want to check before blindly trying to utilize it.  There are various language helpers that you can use to get around the situation where a variable doesn't exist.
    • isset
    • empty() function
    • null coalescing operator
  • Take care with PHP blocks inside if-then or if-then-else constructs.  In general, it's a good idea to always make sure you have a block { ... } to handle each case.   Your blocks don't look correct.
    • Try not to chain if-then else, when instead you can use multiple if blocks.  The code is easier to read and update in most cases.  

 

The issue with the code presented is that you have buttons but no form, so this invokes a lot of confusing default behavior and questions you might want to ask yourself like:

  • Why/where is the form submitted?
  • What type of submission is it?
    • For example, if the type of submission is not a POST, can you expect $_POST variables to exist?

 

I don't address these questions for you, but I expect you will need to figure them out soon.

 

Here's some modifications to your code illustrating these thoughts:

<meta charset="utf-8">
<title>Work intergrated learning</title>

<style>
  body {  
    font-size: 30px;
  }
  p {
    font-size: x-large;
  }
  
 .btn {
  padding: 10px;
  font-size: 20px;
  border-radius: 10px;
  font-weight: bolder;
  transition: background-color 2s ease Os;
  cursor: pointer;
 }
  

 .btn--submit {
   background-color: red;
 }

 .btn--submit:hover {
   background-color: green;
 }   

 .btn--cancel {
   background-color: yellow;
 }

 .btn--cancel:hover{
   background-color: orange;
 }
</style>
 

Rest of code...

<p>Creating a button</p>
<br>

<?php
if (isset($_POST['btn-atc'])){
   echo 'You have added an item to your shopping chart';
}
?>

<input type="submit" name="btn-atc" value="Add to Cart">
<?php
  $btnSubmit = isset($_POST['btn-submit']);
  if ($btnSubmit) {
    echo 'Your query has been successfully submited, our consultant will get in touch with you as soon as possible';
  }
  $btnCancel = isset($_POST['btn-cancel']);
  if $btnCancel {
    echo 'You have cancelled your query.';
  }
?>
<input type="submit" name="btn-submit" class="btn btn--submit" value="Submit query"><br>
<input type="submit" name="btn-cancel" class="btn btn--cancel" value="Cancel">

 

Link to comment
Share on other sites

I just want to point out that ids are great for buttons if you are changing a single button's appearance or you want a certain button to do a certain action. A good example is doing a trivia game as you can have each button be a possible answer.

You would still use a class for general styling of the buttons and the id to personalize the button either in CSS or JavaScript (Which I did a lot in developing a trivia game).

 

Here's an example:

                    <div id="questionBox">
                        <h2 id="question">What is the Question?</h2>
                        <button class="buttonStyle" id="ans1">Ans1</button>
                        <button class="buttonStyle" id="ans2">Ans2</button>
                        <button class="buttonStyle" id="ans3">Ans3</button>
                        <button class="buttonStyle" id="ans4">Ans4</button>
                    </div>

Though I am using JavaScript to control the buttons.

A small snippet -

    let q = document.querySelector('#question');
    let answer1 = document.querySelector('#ans1');
    let answer2 = document.querySelector('#ans2');
    let answer3 = document.querySelector('#ans3');
    let answer4 = document.querySelector('#ans4');
    let index = 0;
    let totalRecords = 0;
    let triviaData = null;

    const checkAnswer = () => {

    }

    const displayData = ({ans1, ans2, ans3, ans4, id, question}) => {

        console.log('trivia data', question);

        console.log(`The database table id is ${id}`)
        q["textContent"] = question;
        answer1["textContent"] = ans1;
        answer2["textContent"] = ans2;
        answer3["textContent"] = ans3;
        answer4["textContent"] = ans4;

I am updating my online Trivia Game, but I just wanted to show that ids can be important to the <button></button> element.

 

The CSS

        .buttonStyle {
            display: block;
            width: 100%;
            height: 3.125em;
            border: none;
            outline: none;
            cursor: pointer;
            background-color: #F5F5F5;
            font-family: 'Rubik', sans-serif;
            font-size: 1.2em;
            color: #2E2E2E;
            text-transform: capitalize;
            text-align: left;
            padding-left: 0.625em;
            margin: 0 auto;
        }

 

Edited by Strider64
Link to comment
Share on other sites

@Strider64

I appreciate your long time presence and many helpful answers here, however in this case I have to disagree strongly with you.

HTML id's should never represent anything other than a unique page element.  

That is possible with your example, in that there is only one question on a page, but that would be a very limiting design, once you decided to have 2 or more questions.  A much better and more standard way of doing what you are doing there is to utilize data attributes.

 

9 minutes ago, Strider64 said:
                    <div id="questionBox">
                        <h2 id="question">What is the Question?</h2>
                        <button class="buttonStyle" id="ans1">Ans1</button>
                        <button class="buttonStyle" id="ans2">Ans2</button>
                        <button class="buttonStyle" id="ans3">Ans3</button>
                        <button class="buttonStyle" id="ans4">Ans4</button>
                    </div>

 

I'd probably expect to see something more like this these days:

<div class="question-box">
  <h2 class="question-box__question">What is the Question?</h2>
  <button class="btn question-box__answer" data-question="1" data-answer="1">Ans1</button>
  <button class="btn question-box__answer" data-question="1" data-answer="2">Ans2</button>
  <button class="btn question-box__answer" data-question="1" data-answer="3">Ans3</button>
  <button class="btn question-box__answer" data-question="1" data-answer="4">Ans4</button>
</div>

Here I employed BEM standards and data elements which match up with the type of scheme you might see in a database model that has a questions table and related rows in an answer table.  Each button has all the data that's needed (the id of the parent question as well as the id of answer.  

In javascript you can get access to these values using the DOM getAttribute function, but even simpler than that the values are exposed as properties.  So, assuming you are doing this in an onclick handler attached to the answer buttons, you can just get those values via the built-in dataset property.

btn.dataset.question
btn.dataset.answer

This code illustrates how you would make this work with the markup changes I show above:

function btnClickHandler(event) {
   console.log(`question: ${event.target.dataset.question}, Answer: ${event.target.dataset.answer}`)
}

let elements = document.getElementsByClassName("question-box__answer");
for (let i = 0; i < elements.length; i++) {
   elements[i].onclick = btnClickHandler
}

If you want to explore this further I made a Codepen of it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.