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

Time:11-05

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:

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

CodePudding user response:

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

CodePudding user response:

When you fail to specify the type of a <button> element, the browser will imply that it is a submit type button. Thus, when you press the button, your browser is submitting the form with it.

You should either,

a) Specify a type for the button other then submit, or

b) Return false in the javascript code to run, to prevent the click event from bubbling.

  • Related