Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP form button redirects (is changing the URL) even if I don't want to

So, I have a button in a form.

   <form>
      <button onclick="alert('<?php echo $value ?>')">Click me!</button>
   </form>

$value = "1.png"

When I press it changes the url like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Initial: 
index.php?id=82

After I click:
index.php?

As you can see, I want the button to only show an alert, not to change the URL

Full code:

 <form>
    <label>Title</label><br>
    <input type="text" value="<?php echo $title ?>"><br><br>
    <label>Description</label><br>
    <textarea rows="5" maxlength="120"><?php echo $desc ?></textarea><br><br>
    <div>
       <?php for($k = 0; $k < count($images); $k++) { ?>
         <div>
           <img src="<?php echo $images[$k] ?>">
           <button onclick="alert('<?php echo $images[$k] ?>')">Click me!</button>
         </div>
       <?php } ?>
    </div>
</form>

PS: I’m not sure what’s the problem but I think is the form

>Solution :

There are at least two ways of achieving this:

html:

<button type="button" onclick="alert('<?php echo $images[$k] ?>');">Click me</button>
<button onclick="alert('<?php echo $images[$k] ?>');return false;">Click me!</button>

The first option I think would be best if the only thing you want to achieve is to alert a text.

The second option might be better if call a function when you click on the button and want different responses:

<button onclick="return foo('<?php echo $images[$k] ?>');">Click me!</button>

in javascript:

function foo(image) {
    //If image is img1 then update the page
    //If any other image, don't update the page
    if (image == 'img1') {
        return true;
    }
    return false;    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading