M
M
Mikhail Ivanov2018-10-15 06:18:09
AJAX
Mikhail Ivanov, 2018-10-15 06:18:09

Ajax form reload?

There is a form with a number input field in it, you need to get what the user entered in the field, write it to a variable, and display it on the same page, without reloading the page, like pressing the check data button and the field data that you entered was displayed

<form method="POST" id="fors" action="" >
<input type="text" name="sum" value="">
<input type="button"  value="Проверить данные">
<input type="submit" id="btn" name="sum" value="Отправить" />
</form>

<?php
$sum = $_GET["sum"];
if(!$sum)
{$sum = "Вы ничего не написали";}
echo $sum;
?>

But I don’t understand how to do processing through ajax on click, in ajax it’s zero, I ask for help, either, Google unfortunately didn’t help (

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Ao, 2018-10-15
@darknefrit

Add a name to the form, and on the check button, fire the event onclick="checkData(event)", in the checkData function, perform the check and display the result where necessary

<form method="POST" id="fors" action="" name="formName"  >
<input type="text" name="sum" value="">
<input onclick="checkDataAjax(event)" type="button"  value="Проверить данные">
<input type="submit" id="btn" name="sum" value="Отправить" />
</form>
<div id="target"></div>

function checkDataAjax(event){
  event.preventDefault(); 
  form = new FormData(document.formName);
  let options = {
                method: "POST",               
                body:formData,
                credentials: "include",
                mode: 'cors'
            };
       let URL = "АдресВашегоСервера";
      let request = new Request(URL, options);
      
            fetch(request, options).then(function (response) {				
                return response.json();
            }).then(function (response) {
               document.getElementById('target').innerHTML = response;
            }).catch(function (error) {
              console.log(error);          
            });
  
}

Demo
Only on the server not $_GET but $_POST
<?php
$sum = $_POST["sum"];
if(!$sum)
{$sum = "Вы ничего не написали";}
echo $sum;
?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question