Cómo puedo capturar la respuesta de la forma.presentar


Tengo el siguiente código:

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

            form1.submit();
        }

        function ShowResponse()
        {

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

Quiero capturar la respuesta html de form1.submit? ¿Cómo hago esto? Puedo registrar cualquier función de devolución de llamada en form1.método de envío?

Author: sblundy, 2008-12-17

20 answers

No podrá hacer esto fácilmente con javascript simple. Cuando publica un formulario, las entradas del formulario se envían al servidor y su página se actualiza; los datos se manejan en el lado del servidor. Es decir, la función submit() en realidad no devuelve nada, solo envía los datos del formulario al servidor.

Si realmente desea obtener la respuesta en Javascript (sin actualizar la página), entonces necesitará usar AJAX, y cuando comience a hablar sobre el uso de AJAX, necesitará para usa una biblioteca. jQuery es, con mucho, el más popular, y mi favorito personal. Hay un gran plugin para jQuery llamado Form que hará exactamente lo que parece que quieres.

Así es como usarías jQuery y ese plugin:

$('#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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-11 09:02:21

Una alternativa Ajax es establecer un <iframe> invisible como destino de su formulario y leer el contenido de ese <iframe> en su controlador onload. ¿Pero por qué molestarse cuando hay Ajax?

Nota: Solo quería mencionar esta alternativa ya que algunas de las respuestas afirman que es imposible lograr esto sin 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-06 19:26:25

Lo estoy haciendo de esta manera y su trabajo.

$('#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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-25 11:02:42

No estoy seguro de que entiendas lo que hace submit ()...

Cuando lo hace form1.submit(); la información del formulario se envía al servidor web.

El servidor web hará lo que se supone que debe hacer y devolverá una nueva página web al cliente(generalmente la misma página con algo cambiado).

Por lo tanto, no hay manera de que pueda "atrapar" el retorno de un formulario.submit() acción.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-17 14:20:14

Forma no jQuery, del comentario de 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-11 12:59:39

No hay devolución de llamada. Es como seguir un enlace.

Si desea capturar la respuesta del servidor, use AJAX o publíquela en un Iframe y capture lo que aparece allí después del evento onload() del 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-17 14:20:49

Futuros buscadores de Internet:

Para los nuevos navegadores (a partir de 2018: Chrome, Firefox, Safari, Opera, Edge y la mayoría de los navegadores móviles, pero no IE), fetch es una API estándar que simplifica las llamadas de red asíncronas (para las que solíamos necesitar XMLHttpRequest o $.ajax de jQuery).

Aquí hay una forma tradicional:

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

Si se te entrega un formulario como el anterior (o lo creaste porque es html semántico), entonces puedes envolver el código fetch en un receptor de eventos como abajo:

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
    });
});

(O, si como el póster original desea llamarlo manualmente sin un evento submit, simplemente coloque el código fetch allí y pase una referencia al elemento form en lugar de usar event.target.)

Docs:

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

Otros: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript Esa página en 2018 no menciona fetch (todavía). Pero it menciona que el truco target="myIFrame" está obsoleto. Y también tiene un ejemplo de forma.addEventListener para el evento '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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-29 07:43:52

Este es mi código para este problema:

<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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-20 07:04:18

En caso de que desee capturar la salida de una solicitud AJAX utilizando Chrome, puede seguir estos sencillos pasos:

  1. Abre la caja de herramientas de programadores
  2. Vaya a la consola y en cualquier lugar dentro de ella
  3. En el menú que aparece, haga clic en"Habilitar registro XMXHTTPRequest"
  4. Después de hacer eso cada vez que realiza una solicitud AJAX, un mensaje que comienza con "XHR finished loading:http://......"aparecerá en tu consola.
  5. Al hacer clic en el enlace que aparece, se traiga la "Pestaña de recursos" donde puede ver los encabezados y el contenido de la respuesta!
 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-07 15:29:48

Puede event.preventDefault() en el controlador de clics para su botón enviar para asegurarse de que el evento predeterminado del formulario HTML submit no se active (que es lo que lleva a la actualización de la página).

Otra alternativa sería usar el marcado de formularios hacker: Es el uso de <form> y type="submit" lo que se está interponiendo en el camino del comportamiento deseado aquí; ya que estos finalmente conducen a eventos de clic que refrescan la página.

Si desea seguir utilizando <form>, y no desea escribir controladores de clics personalizados, debe puede usar el método ajax de jQuery, que abstrae todo el problema para usted exponiendo los métodos promise para success, error, etc.


Para recapitular, puede resolver su problema mediante:

* evitar el comportamiento predeterminado en la función de manejo usando event.preventDefault()

* usar elementos que no tienen un comportamiento predeterminado (por ejemplo, <form>)

* usando jQuery ajax


(acabo de notar que esta pregunta es de 2008, no estoy seguro de por qué apareció en mi feed; en cualquier caso, esperemos que esta sea una respuesta clara)

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-11 20:42:53

Basándose en la respuesta de @ rajesh_kw ( https://stackoverflow.com/a/22567796/4946681 ), me ocupo de los errores de publicación de formularios y el éxito:

    $('#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 : ''));
            }
        });
    });

Hago uso de this para que mi lógica sea reutilizable, espero que se devuelva HTML en un éxito, por lo que lo renderizo y reemplazo la página actual, y en mi caso espero una redirección a la página de inicio de sesión si la sesión se agota, por lo que intercepto esa redirección para preservar el estado de la página.

Ahora los usuarios pueden iniciar sesión a través de otra pestaña y probar su presentación de nuevo.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:24

Puede hacerlo utilizando la tecnología javascript y AJAX. Echa un vistazo a jquery y a este complemento de formulario . Solo necesita incluir dos archivos js para registrar una devolución de llamada para el formulario.presentar.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-17 14:24:09

Esto Se puede lograr usando jQuery y el ajax() método:

<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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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

Primero de todo uso $(documento).ready (function ()) dentro de este uso ('formid').submit(function(evento)) y luego evitar la acción predeterminada aftyer que llaman ajax envío de formulario $.ajax({, , , , }); tomará el parámetro u puede elegir acordar su requisito a continuación, llame a afunction success: function (data){ // haz lo que quieras mi ejemplo para poner html de respuesta en 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-07 12:30:12

En primer lugar necesitaremos 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;
};

Luego haces un post básico y obtienes respuesta

$.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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-14 15:33:47

Tengo el Siguiente código ejecutándose con ajax con datos de formulario de varias partes

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 04:07:51

Puede usar jQuery.post () y devuelve respuestas JSON bien estructuradas desde el servidor. También le permite validar / desinfectar sus datos directamente en el servidor, lo cual es una buena práctica porque es más seguro (e incluso más fácil) que hacerlo en el cliente.

Por ejemplo, si necesita publicar un formulario html en el servidor (para guardar profilechanges.php) con datos de usuario para registro simple:

I. Partes del cliente:

I. a. HTML parte:

<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. Script parte:

$(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. Parte del servidor (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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-01 16:02:48

Necesita usar AJAX. Enviar el formulario generalmente resulta en que el navegador cargue una nueva página.

 -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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-17 14:19:19

Puedes hacerlo sin ajax.

Escribe tu like a continuación.

.. .. ..

Y luego en "acción.php "

Luego después de frmLogin.presentar ();

Leer variable subm submit_return..

Subm submit_return contiene el valor devuelto.

Buena suerte.

 -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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-11 17:56:02