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

So, I have a button in a form.

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

$value = "1.png"

When I press it changes the url like this:


After I click:

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

Full code:

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

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:


<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;    

Leave a Reply