How to stop page refresh on form submit - php

I have a form which automatically refreshes the page on submit, I have tried adding:
onSubmit="return false;" to the form element, but then the form just stops and nothing happens when you click submit.
I wouldnt mind the page refresh so much but the form is at the bottom of the page and the refresh kicks you back to the top. So I tried this approach:
<form name='test' method='POST' action="index.php" onSubmit="window.scrollTo(5000,500);">
This works for a split second but then something else overrides it (not sure what)
I have also tried using php: header.location just to get a "headers have already been sent" error.
The site in question can be seen here, and the form is at the very bottom.
The only two jquery libraries I am using that I could foresee any conflicts with are nicescroll and (more likely) waypoints, but i dug through them both and couldn't find any conflicting issues.
If anyone knows of a way to keep the functionality of the form but stop the refresh of the page, that would be wonderful
Thanks
EDIT: After reading the answers below, it looks like I will have to use ajax to acomplish this, I have absolutely no experience with ajax, so I will see how that goes.

It seems you need to go through of way of AJAX submission in that case. In that case, you can use jQuery $.ajax() method to do that. A sample below:
HTML
<form name='test' method='POST' action="index.php">
jQuery
$('form[name=test]').submit(function(e) {
e.preventDefault();
window.scrollTo(5000,500);
// a sample AJAX request
$.ajax({
url : this.action,
type : this.method,
data : $(this).serialize(),
success : function(response) {
}
});
});
Here, .preventDefault() is for stop page refresh on form submit.

Why not submit the form to a hidden IFRAME?
<iframe name="myiframe" style="display: none;"></iframe>
<form name='test' method='POST' action="index.php" target="myiframe">
...
</form>

What about using AJAX instead of a normal form submit?

Related

Stop page refreshing when pressing HTML button?

Hello guys I'm new to internet languages and I would like your help explained with apples!
I'm trying to make a webserver controlled robot with a raspberry pi 3b+. I already got that working with some HTML calling some PHP code and then executing Python scripts in order to move the robot. The thing is, when I press a button to move the robot the page refreshes then loads everything again making it really annoying. (HTML and PHP are in the same document)
I've read some post where people say to use <button> tags with type="button", but when I do that nothing happens. Let me share with you the code. Other people say to use AJAX, but I don't really know how to.
HTML:
<form action="" method="post">
<div>
<div>
<button type="button" name="boton7"><img src="imagenes/up.png"></button>
</div>
<div>
<button type="button" name="boton8"><img src="imagenes/left.png"></button><!--
--><button type="button" name="boton10"><img src="imagenes/stop.png"></button><!--
--><button type="button" name="boton9"><img src="imagenes/right.png"></button><!--
-->
</div>
<div>
<button type="button" name="boton6"><img src="imagenes/down.png"></button>
</div>
</div>
</form>
PHP:
<?php
//Primera fila || mover_arriba.py
if(isset($_POST['boton6'])){
exec('python /var/www/html/mover_arriba.py');
}
//Primera fila || mover_abajo.py
if(isset($_POST['boton7'])){
exec('python /var/www/html/mover_abajo.py');
}
?>
I would like to know if it can done without using AJAX or JS (interpreted languages are confusing to me) or if I can modify something on this code to achieve what I want. As you can see I used a form, I don't really understand if a button can do something without a form, why sometimes people use input="submit", I've also seen "onclick=". Please use as clear as possible answers.
If you need anything else please let me know!
EDIT: I forgot to mention that if I remove type="button" from this <button type="button" it works.
The bad news is that you will have to use JavaScript and AJAX to accomplish this. There's simply no (reasonable) way around it.
The good news is that what you want to do is actually quite simple. Since there is no conditional data and no return data to handle, the bar is already pretty low. I also assume that you are not worried about bad actors abusing vulnerabilities in your code, so let's dive in.
First off, let's get a library that can do AJAX calls. While not necessary, this makes everything a lot easier.
Inside your <head> element, put the following line:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Next, add an ID to your <form> element so it is easier for us to access with jQuery.
<form id="robotform" action="" method="post">
Now let's add some JS below the form to handle the form submissions. It has to be placed after because the html elements need to exist before this code is called. Code below is mostly adapted from the answer to this question: Submitting HTML form using Jquery AJAX
<script type='text/javascript'>
/* Get the name of the button that was pressed */
var buttonpressed;
$('button').click(function() {
buttonpressed = $(this).attr('name');
})
/* attach a submit handler to the form */
$("#robotform").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* target url is the current page */
var url = window.location.href;
/* Create the data as a string so the button name is sent properly */
var data = buttonpressed + '=true';
/* Send the data using post with element id name and name2*/
var posting = $.post( url, data );
/* Alerts the results if unsuccessful */
posting.fail(function( xhr, status, error ) {
alert('Error sending the command: ' + error);
});
});
</script>
One possible solution could be that you could have your PHP code return a 'false' value back to the form. This would prevent the page from refreshing.
This way the PHP code will call the python code but the form will not refresh since it has received a false value back from the PHP function.

Stop form from refreshing on submit

I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});

One Form/Submit Two Actions

I have a bit of a problem with my website. I have phpbb integrated into my website and a login form on the homepage. This form needs to execute two different actions. It first needs to run the ucp.php (to log into phpbb) and also the login.php (to hide the form and add control panel on home screen). They both work by themselves, I just need a way to have them together when a user logs in. i have researched this for a while and can't find a solution. Thanks in advances, Josh
I need to combine this
<form action="./forums/ucp.php?mode=login" method="post" enctype="multipart/form-data">
with this
<form action="login.php" method="post" enctype="multipart/form-data">
I think you have a serious design issue in your code if you have to "merge" stuff like that, but in any case:
Just create a new file ie. post_handler.php and toss this code in it:
<?php
include('forums/upc.php');
include('login.php');
?>
Place it in the same directory as login.php.
Then adjust your form to point to post_handler.php?mode=login.
Ofcourse merging files like that could result in crazy unexpected results..
Another option, though more complex, would be to use the login.php as your action and do a curl request to forums/ucp.php inside it. (search for Curl on php.net documentation)
Unfortunately I can not give more suggestions, because what you are trying to do is probably more complex then something that can easily be answered here.
Well you can try trick with ajax. Here is an example that should work with jquery:
Im not sure if preventDefaut() wont make us a problem here and we still be allowed to use .submit() on it. If it wont work. Try to put whole thing into function, remove preventDefault and bind this function into submit button.
<form id="form_id" action="login.php" method="post" enctype="multipart/form-data">
User name: <inputy type="text" id="username" name="username" />
</form>
<script type="text/javascript">
$(function() {
//we prevent normal form submit
$('#form_id').preventDefault();
var data = {} ;
//here u build data u want send by taking it from form field by field
//example
data['username'] = $('#username');
//and you send this data via ajax to your upc script
$.ajax({
type: "POST",
url: '/forums/ucp.php?mode=login',
data: data,
//in case of succes we send form normal way
success: function( xhr ) { $('#form_id').submit(); },
dataType: String
});
});
<script>

Show PHP result in div without refresh

Do you know a way to display a php result inside a div dynamically, without refreshing the page?
For example, we have 2 divs: one on the top half of the page and one on the bottom of the page. The top one contains a form with 3 input fields. You type some values inside, then press a button. When you press the button, the bottom div displays the values without refreshing the page.
You can't do it with pure PHP because PHP is a static language. You have to use Javascript and AJAX. I recommend using a library like Zepto or jQuery to make it easy to implement like this:
<form>
<input name="search" />
<input type="submit" />
</form>
<div id="div2"></div>
<script>
// When the form is submitted run this JS code
$('form').submit(function(e) {
// Post the form data to page.php
$.post('page.php', $(this).serialize(), function(resp) {
// Set the response data into the #div2
$('#div2').html(resp);
});
// Cancel the actual form post so the page doesn't refresh
e.preventDefault();
return false;
});
</script>
You can accomplish it using AJAX. With Ajax you can exchange data with a server, make asynchronous request without refreshing the page.
Check this out to see how it can be implemented using Jquery:- http://api.jquery.com/jQuery.ajax/

jQuery $.get request not working

I have a file upload form, the following javascript fires as soon as the form is submitted:
$("#uploader").submit(function() {
$("#indicator").show();
alert("Submitted");
var refresh = setInterval(function() {
$.get("progress.php?getprogress&randval=" + Math.random(), function(data) {
alert("Got " + data);
$("#indicator .bar div").width(data + "%");
if (data == 100) {
clearTimeout(refresh);
$("#indicator").addClass("done");
}
});
}, 250);
});
I added some alerts to debug, I get the alert("Submitted"), but not the one alerting the data. The php is fine, opening it in a separate window gives the correct values, but the javascript does not get it. Another weird thing is that if I stop the page load, the alert() with the value fires and code is processed.
You are not cancelling the form submission, that means your page will refresh. To cancel the submission you can call event.preventDefault()
$("#uploader").submit(function(e) {
e.preventDefault();
Just moving comments into the answer since your question actually has more to it than what you wrote above.
It is impossible to do two actions on the submit and expect them both to happen. Especially when one is trying to run code as the age is submitting. There are JavaScript libraries that do file uploads, you might want to look into them. BUT the basic idea is submitting the form to a hidden iframe on the page.
<form action="YourSubmitPage.php" method="POST" target="hiddenIframe">
...fileds here...
</form>
<iframe id="hiddenIframe" name="hiddenIframe" style="display:none" />
Ok solved this by using an <iframe>:
<form action="save.php" method="post" target="theiframe">...</form>
<iframe name="theiframe" src="about:blank"></iframe>
Still using javascript, but no e.preventDefault();
I hope your function is inside a $(document).ready() statement

Categories