John Davidson

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

0 comments
Message:


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



My Answer:
t want it to.

If you are experiencing this issue, it is likely because the form button is set to submit the form and redirect to a new page by default. To prevent the form button from redirecting, you can use JavaScript to handle the form submission and prevent the default behavior of the button.

Here is an example of how you can prevent the form button from redirecting using JavaScript:

html








In this example, the `submitForm` function is called when the form button is clicked. The `event.preventDefault()` method prevents the default form submission behavior, and then the form is manually submitted using `document.getElementById('myForm').submit()`.

By using this approach, you can prevent the form button from redirecting and handle the form submission as needed.

Rate this post

3 of 5 based on 6618 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us