How to prevent from page refresh on submit button click

北城以北 提交于 2021-02-04 16:45:33

问题


i have form with one input and one submit button.

<form method='POST' action='' enctype='multipart/form-data' id="form_search">
<input type='hidden' name="action" id="form_1" value='1' />
</span><input id="query" type="text" name="mol" value="">
<input type='submit' value='Search' name="Search" id="Search" />

on form submission form input data goes to php below code

if (isset($_POST['Search'])) {
$_SESSION["query"] = $_POST["mol"];
$_SESSION["action"] = $_POST["action"];
}

i want to avoid page refresh on form submission. i tried e.preventDefault() and return false; methods in my java script but not working(this methods helping me from page refresh but does not allowing me to send data to php code)

please help me out of this problem, please suggest working ajax code for this problem.


回答1:


Page refresh will delete you previous data so to reserve it you can use $.post() or $.ajax()

You can prevent page refreshing by adding one of these two things in event handler function

for pure js

 return false;

for jquery you can use

e.preventDefault(); // e is passed to handler

Your complete code will be something like

using $.post() in js

function checkfunction(obj){
$.post("your_url.php",$(obj).serialize(),function(data){
 alert("success");
 });
 return false;
 }

html

<input type='submit' onclick="return checkfunction(this)" />

or same effect with onsubmit

<form  onsubmit="return checkfunction(this)" method="post">



回答2:


Without ajax you can simply add the checked attribute in PHP. So for example if your radio group has the name radio and one has value a, the other b:

<?php
$a_checked = $_POST['radio'] === 'a';
$b_checked = $_POST['radio'] === 'b';
?>

<input type="radio" name="radio" value="a"<?=($a_checked ? ' checked' : '')?>></input>
<input type="radio" name="radio" value="b"<?=($b_checked ? ' checked' : '')?>></input>

So when a user submits the form and you display it again, it will be like the user submitted it even the page refreshes.




回答3:


<input type="radio" name="rbutton" id="r1">R1
<input type="radio" name="rbutton" id="r2">R2
<input type="button" id="go" value="SUBMIT" />
<div id="result"></div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $('#go').click(function(){
        var val1 = $('input:radio[name=rbutton]:checked').val();
        var datastring = "partialName="+val1;
        $.ajax({
            url: "search.php",
            type: "POST",
            data: datastring,
            success: function(data)
            {
                $("#result").html(data);
            }
        });
    });
});
</script>


来源:https://stackoverflow.com/questions/27648131/how-to-prevent-from-page-refresh-on-submit-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!