Jak uchwycić odpowiedź formularza.submit

Mam następujący kod:

<script type="text/javascript">
        function SubmitForm()
        {

            form1.submit();
        }

        function ShowResponse()
        {

        }
</script>
.
.
.
<div>
    <a href="#" onclick="SubmitForm();">Click</a>
</div>

Chcę uchwycić odpowiedź html form1.submit? Jak to zrobić? Czy mogę zarejestrować dowolną funkcję zwrotną do form1.metoda submit?

Author: sblundy, 2008-12-17

20 answers

Nie będziesz w stanie zrobić tego łatwo za pomocą zwykłego javascript. Po wysłaniu formularza Dane wejściowe formularza są wysyłane na serwer, a strona jest odświeżana - dane są obsługiwane po stronie serwera. Oznacza to, że funkcja submit() w rzeczywistości niczego nie zwraca, po prostu wysyła dane formularza do serwera.

Jeśli naprawdę chcesz uzyskać odpowiedź w Javascript (bez odświeżania strony), musisz użyć AJAX, a kiedy zaczniesz mówić o użyciu AJAX, będziesz potrzebować aby użyj biblioteki. jQuery jest zdecydowanie najpopularniejszym i moim ulubionym. Istnieje świetna wtyczka do jQuery o nazwie Form , która zrobi dokładnie to, co chcesz.

Oto jak używasz jQuery i tej wtyczki:

$('#myForm')
    .ajaxForm({
        url : 'myscript.php', // or whatever
        dataType : 'json',
        success : function (response) {
            alert("The server says: " + response);
        }
    })
;
 90
Author: nickf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-11 09:02:21

Alternatywą Ajax jest ustawienie niewidzialnego <iframe> jako celu formularza i odczytanie zawartości tego <iframe> w jego obsłudze onload. Ale po co się męczyć, skoro jest Ajax?

Uwaga: chciałem tylko wspomnieć o tej alternatywie, ponieważ niektóre odpowiedzi twierdzą, że jest niemożliwe , aby to osiągnąć bez Ajax.

 48
Author: Ates Goral,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-06 19:26:25

Robię to w ten sposób i to działa.

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(){
        console.log('form submitted.');
      }
    });
    return false;
});
 25
Author: rajesh_kw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-25 11:02:42

Nie jestem pewien, czy rozumiesz, co robi submit ()...

Po wykonaniu form1.submit(); informacje z formularza są wysyłane do serwera www.

Serwer zrobi to, co powinien i zwróci Klientowi nową stronę internetową (Zwykle tę samą stronę z czymś zmienionym).

Więc, nie ma sposobu, aby "złapać" powrót formularza.submit () action.

 7
Author: Sergio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-17 14:20:14

Non - jQuery way, z komentarza 12me21:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php"); 
xhr.onload = function(event){ 
    alert("The server responded with: " + event.target.response); 
}; 
var formData = new FormData(document.getElementById("myForm")); 
xhr.send(formData);
 7
Author: rogerdpack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-11 12:59:39

Nie ma oddzwaniania. To jak podążanie za linkiem.

Jeśli chcesz przechwycić odpowiedź serwera, użyj AJAX lub wyślij ją do Iframe i chwyć to, co pojawia się tam po zdarzeniu onload() iframe.

 5
Author: Diodeus - James MacFarlane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-17 14:20:49

Future internet searchers:

[9]} dla nowych przeglądarek (od 2018 roku: Chrome, Firefox, Safari, Opera, Edge i większość przeglądarek mobilnych, ale nie IE), fetch jest standardowym API, które upraszcza asynchroniczne wywołania sieciowe (do których potrzebowaliśmy XMLHttpRequest lub $.ajax jQuery).

Oto tradycyjna forma:

<form id="myFormId" action="/api/process/form" method="post">
    <!-- form fields here -->
    <button type="submit">SubmitAction</button>
</form>

Jeśli formularz taki jak powyżej zostanie ci przekazany (lub stworzyłeś go, ponieważ jest to semantyczny html), możesz owinąć kod fetch w detektor zdarzeń jako poniżej:

document.forms['myFormId'].addEventListener('submit', (event) => {
    event.preventDefault();
    // TODO do something here to show user that form is being submitted
    fetch(event.target.action, {
        method: 'POST',
        body: new URLSearchParams(new FormData(event.target)) // event.target is the form
    }).then((resp) => {
        return resp.json(); // or resp.text() or whatever the server sends
    }).then((body) => {
        // TODO handle body
    }).catch((error) => {
        // TODO handle error
    });
});

(lub, jeśli tak jak oryginalny plakat chcesz wywołać go ręcznie bez zdarzenia submit, po prostu umieść tam kod fetch i podaj odniesienie do elementu form zamiast event.target.)

Docs:

Aport: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Inne: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript Ta strona w 2018 roku nie wspomina o fetch (jeszcze). Ale to wspomina, że trik target= "myIFrame" jest przestarzały. I ma również przykład formy.addEventListener dla zdarzenia "submit".

 3
Author: Marcus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-07 15:08:40
    $.ajax({
        url: "/users/login/",    //give your url here
        type: 'POST',
        dataType: "json",
        data: logindata,
        success: function ( data ){
        //  alert(data);    do your stuff
        },
        error: function ( data ){
        //  alert(data);    do your stuff
        }
    });
 2
Author: Kamal Kishor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-29 07:43:52

To jest mój kod na ten problem:

<form id="formoid" action="./demoText.php" title="" method="post">
    <div>
        <label class="title">First Name</label>
        <input type="text" id="name" name="name" >
    </div>
    <div>
        <input type="submit" id="submitButton"  name="submitButton" value="Submit">
    </div>
</form>

<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $( this ), url = $form.attr( 'action' );

  /* Send the data using post with element id name and name2*/
  var posting = $.post( url, { name: $('#name').val()} );

  /* Alerts the results */
  posting.done(function( data ) {
    alert('success');
  });
});
</script>
 2
Author: xchangcheng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-20 07:04:18

Jeśli chcesz przechwycić wyjście żądania AJAX za pomocą Chrome, możesz wykonać następujące proste kroki:

  1. Otwórz programator toolbox
  2. Przejdź do konsoli i w dowolnym miejscu wewnątrz niej
  3. w menu, które się pojawi, kliknij "Enable Xmxhttprequest Logging"
  4. Po zrobieniu tego za każdym razem, gdy robisz żądanie AJAX wiadomość zaczynającą się od " XHR zakończył Ładowanie: http://......"pojawi się w konsoli.
  5. kliknięcie w link, który się pojawi, spowoduje przynieś "zakładkę zasoby", gdzie można zobaczyć nagłówki i zawartość odpowiedzi!
 1
Author: Panagiotis Spiliotis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-07 15:29:48

Możesz event.preventDefault() w oknie obsługi przycisku Wyślij, aby upewnić się, że domyślne Zdarzenie HTML submit nie zostanie wywołane (co prowadzi do odświeżenia strony).

Inną alternatywą byłoby użycie hackier form markup: jest to użycie <form> i type="submit", które wchodzi w drogę pożądanego zachowania tutaj; ponieważ ostatecznie prowadzą do zdarzeń kliknięć odświeżających stronę.

Jeśli chcesz nadal używać <form>, a nie chcesz pisać niestandardowych programów obsługi kliknięć, możesz można użyć metody jQuery ajax, która usuwa cały problem, ujawniając metody obietnic dla success, error, itd.


Podsumowując, możesz rozwiązać swój problem poprzez:

• zapobieganie domyślnemu zachowaniu w funkcji obsługi za pomocą event.preventDefault()

• Używanie elementów, które nie mają domyślnego zachowania (np. <form>)

• using jQuery ajax


(właśnie zauważyłem, że to pytanie pochodzi z 2008 roku, Nie wiem dlaczego pojawiło się w moim Feedzie; w każdym razie, mam nadzieję, że jest to jasna odpowiedź)

 1
Author: Benny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-11 20:42:53

Bazując na odpowiedzi @rajesh_kw ( https://stackoverflow.com/a/22567796/4946681 ), zajmuję się błędami formularza i sukcesami:

    $('#formName').on('submit', function(event) {
        event.preventDefault(); // or return false, your choice
        $.ajax({
            url: $(this).attr('action'),
            type: 'post',
            data: $(this).serialize(),
            success: function(data, textStatus, jqXHR) {
                // if success, HTML response is expected, so replace current
                if(textStatus === 'success') {
                    // https://stackoverflow.com/a/1236378/4946681
                    var newDoc = document.open('text/html', 'replace');
                    newDoc.write(data);
                    newDoc.close();
                }
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            if(jqXHR.status == 0 || jqXHR == 302) {
                alert('Your session has ended due to inactivity after 10 minutes.\nPlease refresh this page, or close this window and log back in to system.');
            } else {
                alert('Unknown error returned while saving' + (typeof errorThrown == 'string' && errorThrown.trim().length > 0 ? ':\n' + errorThrown : ''));
            }
        });
    });

Używam this tak, że moja logika jest wielokrotnego użytku, oczekuję, że HTML zostanie zwrócony po sukcesie, więc renderuję go i zastępuję bieżącą stronę, a w moim przypadku oczekuję przekierowania na stronę logowania, jeśli sesja jest przekroczona, więc przechwycę to przekierowanie, aby zachować stan strony.

Teraz użytkownicy mogą logować się za pomocą innej karty i spróbuj jeszcze raz.

 1
Author: Nate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:24

Możesz to zrobić za pomocą javascript i technologii AJAX. Spójrz na jquery i na wtyczkę formularza . Wystarczy tylko dołączyć dwa pliki js, aby zarejestrować wywołanie zwrotne dla formularza.poddaj się.

 0
Author: kgiannakakis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-17 14:24:09

Możesz to osiągnąć używając jQuery i ajax() "metoda": {]}

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function submitform() {
      $.ajax({
        headers: { 
          'Accept': 'application/json',
          'Content-Type': 'application/json' 
        },
        type: "POST",
        url : "/hello.hello",
        dataType : "json",
        data : JSON.stringify({"hello_name": "hello"}),
        error: function () {
          alert('loading Ajax failure');
        },
    	onFailure: function () {
          alert('Ajax Failure');
    	},
    	statusCode: {
          404: function() {
          alert("missing info");
          }   
    	},
        success : function (response) {
          alert("The server says: " + JSON.stringify(response));
        }
      })
      .done(function( data ) {
        $("#result").text(data['hello']);
      });
};</script>
 0
Author: user5435345,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-12 05:55:17
 $(document).ready(function() {
    $('form').submit(function(event) {
        event.preventDefault();
        $.ajax({
            url : "<wiki:action path='/your struts action'/>",//path of url where u want to submit form
            type : "POST",
            data : $(this).serialize(),
            success : function(data) {
                var treeMenuFrame = parent.frames['wikiMenu'];
                if (treeMenuFrame) {
                    treeMenuFrame.location.href = treeMenuFrame.location.href;
                }
                var contentFrame = parent.frames['wikiContent'];
                contentFrame.document.open();
                contentFrame.document.write(data);
                contentFrame.document.close();
            }
        });
    });
});

Blockquote

Pierwszy ze wszystkich używa $(document).ready (function ()) wewnątrz tego use ('formid').submit (function (event)) a następnie zapobiec domyślnej akcji wywołującej złożenie formularza ajax $.ajax({, , , , }); zajmie to parametr, który można wybrać zgodnie z wymaganiami następnie wywołujemy afunction success: function(data){ // róbcie co chcecie mój przykład aby umieścić odpowiedź html na div }

 0
Author: YogeshBagdawat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-07 12:30:12

Przede wszystkim będziemy potrzebować serializeObject ();

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Następnie tworzysz podstawowy post i otrzymujesz odpowiedź

$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true 
}
else
{
//do false
}

});
 0
Author: Euphoria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-14 15:33:47

Mam następujący kod perfactly run using ajax with multi-part form data

function getUserDetail()
{
    var firstName = document.getElementById("firstName").value;
    var lastName = document.getElementById("lastName").value;
    var username = document.getElementById("username").value;
    var email = document.getElementById("email").value;
    var phoneNumber = document.getElementById("phoneNumber").value;
    var gender =$("#userForm input[type='radio']:checked").val();
    //var gender2 = document.getElementById("gender2").value;
    //alert("fn"+firstName+lastName+username+email);
    var roleIndex = document.getElementById("role");
    var role = roleIndex.options[roleIndex.selectedIndex].value;
    var jobTitleIndex = document.getElementById("jobTitle");
    var jobTitle = jobTitleIndex.options[jobTitleIndex.selectedIndex].value;
    var shiftIdIndex = document.getElementById("shiftId");
    var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value;


    var addressLine1 = document.getElementById("addressLine1").value;
    var addressLine2 = document.getElementById("addressLine2").value;
    var streetRoad = document.getElementById("streetRoad").value;

    var countryIndex = document.getElementById("country");
    var country = countryIndex.options[countryIndex.selectedIndex].value;

    var stateIndex = document.getElementById("state");
    var state = stateIndex.options[stateIndex.selectedIndex].value;

    var cityIndex = document.getElementById("city");
    var city = cityIndex.options[cityIndex.selectedIndex].value;



    var pincode = document.getElementById("pincode").value;

    var branchIndex = document.getElementById("branch");
    var branch = branchIndex.options[branchIndex.selectedIndex].value;

    var language = document.getElementById("language").value;
    var profilePicture = document.getElementById("profilePicture").value;
    //alert(profilePicture);
    var addDocument = document.getElementById("addDocument").value;


    var shiftIdIndex = document.getElementById("shiftId");
    var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value;


    var data = new FormData();
    data.append('firstName', firstName);
    data.append('lastName', lastName);
    data.append('username', username);
    data.append('email', email);
    data.append('phoneNumber', phoneNumber);
    data.append('role', role);
    data.append('jobTitle', jobTitle);
    data.append('gender', gender);
    data.append('shiftId', shiftId);
    data.append('lastName', lastName);
    data.append('addressLine1', addressLine1);
    data.append('addressLine2', addressLine2);
    data.append('streetRoad', streetRoad);
    data.append('country', country);
    data.append('state', state);
    data.append('city', city);
    data.append('pincode', pincode);
    data.append('branch', branch);
    data.append('language', language);
    data.append('profilePicture', $('#profilePicture')[0].files[0]);
     for (var i = 0; i < $('#document')[0].files.length; i++) {
            data.append('document[]', $('#document')[0].files[i]);
        }



    $.ajax({
        //url : '${pageContext.request.contextPath}/user/save-user',
        type: "POST",
        Accept: "application/json",
        async: true,
        contentType:false,
        processData: false,
        data: data,
        cache: false,

        success : function(data) {      
            reset();
            $(".alert alert-success alert-div").text("New User Created Successfully!");
         },
       error :function(data, textStatus, xhr){
           $(".alert alert-danger alert-div").text("new User Not Create!");
        }


    });


//

}
 0
Author: gajera bhavin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-26 04:07:51

Możesz użyć jQuery.post () i zwraca ładnie uporządkowane odpowiedzi JSON z serwera. Umożliwia również weryfikację / dezynfekcję danych bezpośrednio na serwerze, co jest dobrą praktyką, ponieważ jest bezpieczniejsze (a nawet łatwiejsze) niż robienie tego na kliencie.

Na przykład, jeśli chcesz opublikować formularz html na serwerze (aby saveprofilechanges.php) z danymi użytkownika do prostej rejestracji:

I. części Klienta:

I. A. HTML część:

<form id="user_profile_form">
  <label for="first_name"><input type="text" name="first_name" id="first_name" required />First name</label>
  <label for="family_name"><input type="text" name="family_name" id="family_name" required />Family name</label>
  <label for="email"><input type="email" name="email" id="email" required />Email</label> 
  <input type="submit" value="Save changes" id="submit" />
</form>

I. B. skrypt część:

$(function () {
    $("#user_profile_form").submit(function(event) {
      event.preventDefault();
      var postData = {
        first_name: $('#first_name').val(),
        family_name: $('#family_name').val(),
        email: $('#email').val()
      };
      $.post("/saveprofilechanges.php", postData,
        function(data) {
          var json = jQuery.parseJSON(data);
          if (json.ExceptionMessage != undefined) {
            alert(json.ExceptionMessage); // the exception from the server
            $('#' + json.Field).focus(); // focus the specific field to fill in
          }
          if (json.SuccessMessage != undefined) {
            alert(json.SuccessMessage); // the success message from server
          }
       });
    });
});

II. Server part (saveprofilechanges.php):

$data = $_POST;
if (!empty($data) && is_array($data)) {
    // Some data validation:
    if (empty($data['first_name']) || !preg_match("/^[a-zA-Z]*$/", $data['first_name'])) {
       echo json_encode(array(
         'ExceptionMessage' => "First name missing or incorrect (only letters and spaces allowed).",
         'Field' => 'first_name' // Form field to focus in client form
       ));
       return FALSE;
    }
    if (empty($data['family_name']) || !preg_match("/^[a-zA-Z ]*$/", $data['family_name'])) {
       echo json_encode(array(
         'ExceptionMessage' => "Family name missing or incorrect (only letters and spaces allowed).",
         'Field' => 'family_name' // Form field to focus in client form
       ));
       return FALSE;
    }
    if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
       echo json_encode(array(
         'ExceptionMessage' => "Email missing or incorrectly formatted. Please enter it again.",
         'Field' => 'email' // Form field to focus in client form
       ));
       return FALSE;
    }
    // more actions..
    // more actions..
    try {
       // Some save to database or other action..:
       $this->User->update($data, array('username=?' => $username));
       echo json_encode(array(
         'SuccessMessage' => "Data saved!"
       ));
       return TRUE;
    } catch (Exception $e) {
       echo json_encode(array(
         'ExceptionMessage' => $e->getMessage()
       ));
       return FALSE;
    }
}
 0
Author: Vlado,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-01 16:02:48

Musisz używać AJAX. Przesłanie formularza zazwyczaj skutkuje wczytaniem nowej strony przez przeglądarkę.

 -1
Author: sblundy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-17 14:19:19

Można to zrobić bez ajax.

Napisz jak poniżej.

.. .. ..

A następnie w "akcji.php "

Potem po frmLogin.submit ();

Odczyt zmiennej $submit_return..

$submit_return zawiera wartość zwracaną.

Powodzenia.

 -5
Author: annih,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-11 17:56:02