简体   繁体   中英

How to submit data without reloading page?

I have been trying to solve this problem for a long long time. I'm new to web developing. What I'm trying to do is that when I'm click to submit button for submitting the values, the page should remains to it's position, but instead it's automatically goes to top, which I don't want that.

<!DOCTYPE html>
<html >
<head>
   <style>
   .bigbox{
    height: 600px;
    width: 500px;
    background: olive;
    margin: 10px;
}
   </style>
</head>
<body>
<div class="bigbox">1</div>
<div class="bigbox">2</div>
<h4>type the range of numbers:</h4>
    <form id="myform">
            <input type="text" name="num1" placeholder="num1">
            <input type="text" name="num2" placeholder="num2">
            <button type="submit" name="submit" value="submit">Submit</button>
            <button type="reset">Reset</button>
    </form>
    <?php
        if(isset($_GET['submit']))
        {
            $num1=$_GET['num1']; 
            $num2=$_GET['num2'];
            $prefix=array("st","nd","rd","th");
         for($j = $num1 ; $j<=$num2;$j++)
         {
             switch($j)
             {
                 case ( $j%100==11 || $j%100==12 || $j%100==13 ); $i=3; break;
                 case $j%10==1: $i=0;break;
                 case $j%10==2; $i=1;break;
                 case $j%10==3; $i=2;break;
                 default : $i=3;
             }
             echo "this is the ".$j.$prefix[$i]." number "."<br>";
         } 
        } 
    ?>
</body>
</html>

I have created a pen with the closest approach to solve such problem, To achieve this using javascript Fetch API

 const formElement= document.getElementById("myform");
 formElement.addEventListener('submit',(e)=>{
   e.preventDefault();
   const formData = new FormData(formElement);
   fetch(`api/url`, {
     method: 'POST',
     body: formData,
   })
   .then(result  => result .json())
   .then(data=> console.log(data)) //after form submit
   .catch((err)=>console.log(err));
});

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values.

For browser compatibility of fetch API check This link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM