funcion form after javascript forms javascript-events form-submit

form - preventdefault submit javascript



Cómo capturo la respuesta de form.submit (19)

Antes que nada 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; };

entonces haces una publicación básica y obtienes respuesta

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

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 al método form1.submit?


Basándome en la respuesta de @rajesh_kw ( https://.com/a/22567796/4946681 ), manejo los errores y el éxito del formulario:

$(''#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://.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 el HTML sea exitoso, así 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, entonces yo 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 envío nuevamente.


Debes estar usando AJAX. Al enviar el formulario, generalmente el navegador carga una nueva página.


En caso de que desee capturar el resultado de una solicitud AJAX utilizando Chrome, puede seguir estos simples pasos:

  1. Abra la caja de herramientas de Programadores
  2. Ve a la consola y en cualquier lugar dentro de ella
  3. En el menú que aparece, haga clic en "Habilitar el registro de solicitud XMXHTTP".
  4. Después de hacer eso cada vez que realice una solicitud AJAX, aparecerá un mensaje que comience con "XHR terminado de cargar: http: // ......" en su consola.
  5. Al hacer clic en el enlace que aparece, aparecerá la "pestaña de Recursos" donde podrá ver los encabezados y el contenido de la respuesta.

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>


Lo estoy haciendo de esta manera y está funcionando.

$(''#form'').submit(function(){ $.ajax({ url: $(''#form'').attr(''action''), type: ''POST'', data : $(''#form'').serialize(), success: function(){ console.log(''form submitted.''); } }); return false; });


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

Cuando haces 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 modificado).

Por lo tanto, no hay manera de que pueda "atrapar" la devolución de una acción form.submit ().


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

Si desea capturar la respuesta del servidor, use AJAX o publíquelo en un iframe y obtenga lo que aparece allí después del evento onload() del iframe.


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 servidor. Es decir, la función submit() realidad no devuelve nada, solo envía los datos del formulario al servidor.

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

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

$(''#myForm'') .ajaxForm({ url : ''myscript.php'', // or whatever dataType : ''json'', success : function (response) { alert("The server says: " + response); } }) ;


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


Puede event.preventDefault() en el controlador de clic para su botón de envío para asegurarse de que el evento de submit predeterminado de formulario HTML 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 pirateados: es el uso de <form> y type="submit" que se interpone en el camino del comportamiento deseado aquí; ya que estos últimos conducen a hacer clic en eventos para actualizar la página.

Si desea seguir utilizando <form> y no desea escribir manejadores de clics personalizados, puede utilizar el método ajax de jQuery, que abstrae todo el problema para usted al exponer métodos prometedores de success , error , etc.

Para recapitular, puedes resolver tu problema ya sea:

• prevenir el comportamiento predeterminado en la función de manejo utilizando event.preventDefault()

• usar elementos que no tienen un comportamiento predeterminado (p. Ej. <form> )

• usando jQuery ajax

(Me acabo de dar cuenta de que esta pregunta es de 2008, no estoy seguro de por qué apareció en mi feed, de todos modos, espero que esta sea una respuesta clara)


Puede lograr esto usando jQuery y el método ajax() :

<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>


Puede usar jQuery.post() y devolver 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 (y aún más fácil) que hacerlo en el cliente.

Por ejemplo, si necesita enviar un formulario html al servidor (para guardar perfiles de registro) con datos de usuario para el registro simple:

I. partes del cliente:

La parte de HTML:

<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>

Parte del script Ib:

$(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; } }


Puedes hacerlo usando javascript y tecnología AJAX. Eche un vistazo a jquery y en esta Form . Solo necesita incluir dos archivos js para registrar una devolución de llamada para el formulario. Enviar.


Tengo el siguiente código ejecutado correctamente usando 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!"); } }); // }


Una alternativa de Ajax es establecer un <iframe> invisible como el destino de su formulario y leer el contenido de ese <iframe> en su controlador de 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.


puedes hacer eso sin ajax.

escribe tu like a continuación.

.. .. ..

y luego en "action.php"

luego después de frmLogin.submit ();

leer la variable $ submit_return ..

$ submit_return contiene valor devuelto.

buena suerte.


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


$(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 use $ (documento) .ready (función ()) dentro de este uso (''formid''). submit (función (evento)) y luego evite la acción predeterminada después de esa llamada ajax formulario submit $ .ajax ({,,, ,}); tomará el parámetro que usted puede elegir de acuerdo a su requerimiento y luego llamará al éxito de la función: función (datos) {// haga lo que quiera con mi ejemplo para poner respuesta html en div}