2011-02-15 27 views
533

Estoy tratando de enviar datos de un formulario a una base de datos. Aquí está la forma que estoy utilizando:jQuery Ajax POST ejemplo con PHP

<form name="foo" action="form.php" method="POST" id="foo"> 
    <label for="bar">A bar</label> 
    <input id="bar" name="bar" type="text" value="" /> 
    <input type="submit" value="Send" /> 
</form> 

El enfoque típico sería la de enviar el formulario, pero esto hace que el navegador para redirigir. Con jQuery y Ajax, ¿es posible capturar todos los datos del formulario y enviarlo a un script PHP (en el ejemplo, form.php)?

+3

Consulte [meta discusión relacionada] (http://meta.stackexchange.com/q/161943/147191) para el razonamiento detrás de la restauración. – TRiG

+0

mejor respuesta aquí: http://stackoverflow.com/questions/19029703/jquery-using-ajax-to-send-data-and-save-in-php/19029778#19029778 controlado y regulado probado trabajando – rohitcopyright

Respuesta

816

uso básico de .ajax sería algo como esto:

HTML:

<form id="foo"> 
    <label for="bar">A bar</label> 
    <input id="bar" name="bar" type="text" value="" /> 

    <input type="submit" value="Send" /> 
</form> 

JQuery:

// Variable to hold request 
var request; 

// Bind to the submit event of our form 
$("#foo").submit(function(event){ 

    // Prevent default posting of form - put here to work in case of errors 
    event.preventDefault(); 

    // Abort any pending request 
    if (request) { 
     request.abort(); 
    } 
    // setup some local variables 
    var $form = $(this); 

    // Let's select and cache all the fields 
    var $inputs = $form.find("input, select, button, textarea"); 

    // Serialize the data in the form 
    var serializedData = $form.serialize(); 

    // Let's disable the inputs for the duration of the Ajax request. 
    // Note: we disable elements AFTER the form data has been serialized. 
    // Disabled form elements will not be serialized. 
    $inputs.prop("disabled", true); 

    // Fire off the request to /form.php 
    request = $.ajax({ 
     url: "/form.php", 
     type: "post", 
     data: serializedData 
    }); 

    // Callback handler that will be called on success 
    request.done(function (response, textStatus, jqXHR){ 
     // Log a message to the console 
     console.log("Hooray, it worked!"); 
    }); 

    // Callback handler that will be called on failure 
    request.fail(function (jqXHR, textStatus, errorThrown){ 
     // Log the error to the console 
     console.error(
      "The following error occurred: "+ 
      textStatus, errorThrown 
     ); 
    }); 

    // Callback handler that will be called regardless 
    // if the request failed or succeeded 
    request.always(function() { 
     // Reenable the inputs 
     $inputs.prop("disabled", false); 
    }); 

}); 

Nota: Desde jQuery 1.8, .success(), .error() y .complete() están en desuso en favor de .done(), .fail() y .always().

Nota: Recuerde que el fragmento anterior se tiene que hacer después de DOM listo, por lo que debe ponerlo dentro de un manejador $(document).ready() (o utilizar la abreviatura $()).

Consejo: Puede chain los manejadores de devolución de llamada de esta manera: $.ajax().done().fail().always();

PHP (es decir, form.php):

// You can access the values posted by jQuery.ajax 
// through the global variable $_POST, like this: 
$bar = isset($_POST['bar']) ? $_POST['bar'] : null; 

Nota: Siempre sanitize posted data, para evitar inyecciones y otro código malicioso.

También puede utilizar la abreviatura .post en lugar de .ajax en el anterior código JavaScript:

$.post('/form.php', serializedData, function(response) { 
    // Log the response to the console 
    console.log("Response: "+response); 
}); 

Nota: El anterior código JavaScript se hace para trabajar con jQuery 1.8 y posteriores, pero debería funcionar con versiones anteriores hasta jQuery 1.5.

+0

Puedo hacer algo con eso;) Pero, ¿cómo debería ser el código form/php? – Thew

+3

Editó su respuesta para corregir un error: 'request' se declaró como var local haciendo' if (request) request.abort(); 'never work. –

+0

¿No debería 'serializedData' ser' $ inputs.serialize() ', o hay alguna razón para serializar y enviar todo el formulario? –

174

para procurar de Ajax usando jQuery se puede hacer esto mediante el siguiente código

HTML:

<form id="foo"> 
    <label for="bar">A bar</label> 
    <input id="bar" name="bar" type="text" value="" /> 
    <input type="submit" value="Send" /> 
</form> 

<!-- The result of the search will be rendered inside this div --> 
<div id="result"></div> 

JavaScript:

Método 1

/* Get from elements values */ 
var values = $(this).serialize(); 

$.ajax({ 
     url: "test.php", 
     type: "post", 
     data: values , 
     success: function (response) { 
      // you will get response from your php page (what you echo or print)     

     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      console.log(textStatus, errorThrown); 
     } 


    }); 

Método 2

/* Attach a submit handler to the form */ 
$("#foo").submit(function(event) { 
    var ajaxRequest; 

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

    /* Clear result div*/ 
    $("#result").html(''); 

    /* Get from elements values */ 
    var values = $(this).serialize(); 

    /* Send the data using post and put the results in a div */ 
    /* I am not aborting previous request because It's an asynchronous request, meaning 
     Once it's sent it's out there. but in case you want to abort it you can do it by 
     abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */ 
     ajaxRequest= $.ajax({ 
      url: "test.php", 
      type: "post", 
      data: values 
     }); 

     /* request cab be abort by ajaxRequest.abort() */ 

    ajaxRequest.done(function (response, textStatus, jqXHR){ 
      // show successfully for submit message 
      $("#result").html('Submitted successfully'); 
    }); 

    /* On failure of request this function will be called */ 
    ajaxRequest.fail(function(){ 

     // show error 
     $("#result").html('There is error while submit'); 
    }); 

Los .success(), .error(), y .complete() devoluciones de llamada están en desuso como de jQuery 1.8. Para preparar su código para su eventual eliminación, use .done(), .fail() y .always().

MDN: abort(). Si la solicitud ya se ha enviado, este método cancelará la solicitud.

por lo que hemos enviado con éxito la solicitud ajax ahora es el momento de obtener datos para el servidor.

PHP

A medida que hacemos una solicitud POST en llamada AJAX (type: "post") ahora podemos tomar los datos utilizando $_REQUEST o $_POST

$bar = $_POST['bar'] 

también se puede ver lo que se obtiene en la solicitud POST simplemente, o bien, por cierto, asegúrese de que $ _POST esté configurado de otra manera obtendrá un error.

var_dump($_POST); 
// or 
print_r($_POST); 

Y va a insertar valor a la base de datos asegúrese de que está sensibilizando o escapar En todos los pedidos (si el tiempo se hizo GET o POST) correctamente antes de hacer la consulta, mejor sería utilizar declaraciones preparadas.

y si desea devolver los datos a la página, puede hacerlo haciendo eco de los datos como a continuación.

// 1. Without JSON 
    echo "hello this is one" 

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below 
echo json_encode(array('returned_val' => 'yoho')); 

y que lo puede conseguir como

ajaxRequest.done(function (response){ 
    alert(response); 
}); 

hay un par de Shorthand Methods puede utilizar a continuación el código que haga el mismo trabajo.

var ajaxRequest= $.post("test.php",values, function(data) { 
    alert(data); 
}) 
    .fail(function() { 
    alert("error"); 
    }) 
    .always(function() { 
    alert("finished"); 
}); 
+1

Puntero: ¿qué es 'bar' en' $ id = $ _POST ['bar']; 'y cómo funciona ??? – Clarence

+0

La barra @Clarence es un tipo de entrada de texto y desde entonces estoy demandando el método de publicación, así que $ _POST ['barra'] se usa para obtener el valor –

+3

Para cualquiera que desee usar json: mientras usa JSON, la llamada debe contener el parámetro dataType: 'json' –

22

Puede usar la serialización. A continuación hay un ejemplo.

$("#submit_btn").click(function(){ 
    $('.error_status').html(); 
     if($("form#frm_message_board").valid()) 
     { 
      $.ajax({ 
       type: "POST", 
       url: "<?php echo site_url('message_board/add');?>", 
       data: $('#frm_message_board').serialize(), 
       success: function(msg) { 
        var msg = $.parseJSON(msg); 
        if(msg.success=='yes') 
        { 
         return true; 
        } 
        else 
        { 
         alert('Server error'); 
         return false; 
        } 
       } 
      }); 
     } 
     return false; 
    }); 
+1

'$ .parseJSON()' es un salvavidas total, gracias. Estaba teniendo problemas para interpretar mi salida en función de las otras respuestas. – foochow

39

Me gustaría compartir una forma detallada de cómo publicar con PHP + Ajax junto con los errores devueltos en la falla.

Antes que nada, cree dos archivos, por ejemplo form.php y process.php.

Primero crearemos un form que luego se enviará utilizando el método jQuery.ajax(). El resto se explicará en los comentarios.


form.php

<form method="post" name="postForm"> 
    <ul> 
     <li> 
      <label>Name</label> 
      <input type="text" name="name" id="name" placeholder="Bruce Wayne"> 
      <span class="throw_error"></span> 
     </li> 
    </ul> 
    <input type="submit" value="Send" /> 
</form> 


Validar el formulario utilizando jQuery validación del lado del cliente y pasar los datos a process.php.

$(document).ready(function() { 
    $('form').submit(function(event) { //Trigger on form submit 
     $('#name + .throw_error').empty(); //Clear the messages first 
     $('#success').empty(); 

     //Validate fields if required using jQuery 

     var postForm = { //Fetch form data 
      'name'  : $('input[name=name]').val() //Store name fields value 
     }; 

     $.ajax({ //Process the form using $.ajax() 
      type  : 'POST', //Method type 
      url  : 'process.php', //Your form processing file URL 
      data  : postForm, //Forms name 
      dataType : 'json', 
      success : function(data) { 
          if (!data.success) { //If fails 
           if (data.errors.name) { //Returned if any error from process.php 
            $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error 
           } 
          } 
          else { 
            $('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message 
           } 
          } 
     }); 
     event.preventDefault(); //Prevent the default submit 
    }); 
}); 

Ahora vamos a echar un vistazo a process.php

$errors = array(); //To store errors 
$form_data = array(); //Pass back the data to `form.php` 

/* Validate the form on the server side */ 
if (empty($_POST['name'])) { //Name cannot be empty 
    $errors['name'] = 'Name cannot be blank'; 
} 

if (!empty($errors)) { //If errors in validation 
    $form_data['success'] = false; 
    $form_data['errors'] = $errors; 
} 
else { //If not, process the form, and return true on success 
    $form_data['success'] = true; 
    $form_data['posted'] = 'Data Was Posted Successfully'; 
} 

//Return the data back to form.php 
echo json_encode($form_data); 

Los archivos de proyecto se pueden descargar desde http://projects.decodingweb.com/simple_ajax_form.zip.

8
<script src="http://code.jquery.com/jquery-1.7.2.js"></script> 
<form method="post" id="form_content" action="Javascript:void(0);"> 
    <button id="desc" name="desc" value="desc" style="display:none;">desc</button> 
    <button id="asc" name="asc" value="asc">asc</button> 
    <input type='hidden' id='check' value=''/> 
</form> 

<div id="demoajax"></div> 

<script> 
    numbers = ''; 
    $('#form_content button').click(function(){ 
     $('#form_content button').toggle(); 
     numbers = this.id; 
     function_two(numbers); 
    }); 

    function function_two(numbers){ 
     if (numbers === '') 
     { 
      $('#check').val("asc"); 
     } 
     else 
     { 
      $('#check').val(numbers); 
     } 
     //alert(sort_var); 

     $.ajax({ 
      url: 'test.php', 
      type: 'POST', 
      data: $('#form_content').serialize(), 
      success: function(data){ 
       $('#demoajax').show(); 
       $('#demoajax').html(data); 
       } 
     }); 

     return false; 
    } 
    $(document).ready(function_two()); 
</script> 
+0

¿Qué diferencia de id entre usted y otra respuesta? –

+7

es publicado por mí otros son por otros ,. – john

18

HTML:

<form name="foo" action="form.php" method="POST" id="foo"> 
     <label for="bar">A bar</label> 
     <input id="bar" class="inputs" name="bar" type="text" value="" /> 
     <input type="submit" value="Send" onclick="submitform(); return false;" /> 
    </form> 

JavaScript:

function submitform() 
    { 
     var inputs = document.getElementsByClassName("inputs"); 
     var formdata = new FormData(); 
     for(var i=0; i<inputs.length; i++) 
     { 
      formdata.append(inputs[i].name, inputs[i].value); 
     } 
     var xmlhttp; 
     if(window.XMLHttpRequest) 
     { 
      xmlhttp = new XMLHttpRequest; 
     } 
     else 
     { 
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xmlhttp.onreadystatechange = function() 
     { 
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200) 
      { 

      } 
     } 
     xmlhttp.open("POST", "insert.php"); 
     xmlhttp.send(formdata); 
    } 
12

utilizo este way.It presentar todo como archivos

$(document).on("submit", "form", function(event) 
{ 
    event.preventDefault(); 

    var url=$(this).attr("action"); 
    $.ajax({ 
     url: url, 
     type: 'POST', 
     dataType: "JSON", 
     data: new FormData(this), 
     processData: false, 
     contentType: false, 
     success: function (data, status) 
     { 

     }, 
     error: function (xhr, desc, err) 
     { 
      console.log("error"); 

     } 
    });   

}); 
2

Estoy usando este código simple de una línea durante años sin problemas. (Se requiere jQuery)

<script type="text/javascript"> 
function ap(x,y) {$("#" + y).load(x);}; 
function af(x,y) {$("#" + x).ajaxSubmit({target: '#' + y});return false;}; 
</script> 

Aquí ap() significa la página Ajax y af() significa forma ajax. En un formulario simplemente llamando a la función af() publicará el formulario en la url y cargará la respuesta en el elemento html deseado.

<form> 
... 
<input type="button" onclick="af('http://example.com','load_response')"/> 
</form> 
<div id="load_response">this is where response will be loaded</div> 
2
handling ajax error and loader before submit and after submit success show alert bootbox with example: 
    var formData = formData; 

    $.ajax({ 
     type: "POST", 
     url: url, 
     async: false, 
     data: formData, //only input 
     processData: false, 
     contentType: false, 
     xhr: function() 
     { 
      $("#load_consulting").show(); 
      var xhr = new window.XMLHttpRequest(); 
//Upload progress 
      xhr.upload.addEventListener("progress", function (evt) { 
       if (evt.lengthComputable) { 
        var percentComplete = (evt.loaded/evt.total) * 100; 
        $('#addLoad .progress-bar').css('width', percentComplete + '%'); 
       } 
      }, false); 
//Download progress 
      xhr.addEventListener("progress", function (evt) { 
       if (evt.lengthComputable) { 
        var percentComplete = evt.loaded/evt.total; 
       } 
      }, false); 
      return xhr; 
     }, 
     beforeSend: function (xhr) { 
      qyuraLoader.startLoader(); 
     }, 
     success: function (response, textStatus, jqXHR) { 
      qyuraLoader.stopLoader(); 
      try { 
       $("#load_consulting").hide(); 

       var data = $.parseJSON(response); 
       if (data.status == 0) 
       { 
        if (data.isAlive) 
        { 
         $('#addLoad .progress-bar').css('width', '00%'); 
         console.log(data.errors); 
         $.each(data.errors, function (index, value) { 
          if (typeof data.custom == 'undefined') { 
           $('#err_' + index).html(value); 
          } 
          else 
          { 
           $('#err_' + index).addClass('error'); 

           if (index == 'TopError') 
           { 
            $('#er_' + index).html(value); 
           } 
           else { 
            $('#er_TopError').append('<p>' + value + '</p>'); 
           } 
          } 

         }); 
         if (data.errors.TopError) { 
          $('#er_TopError').show(); 
          $('#er_TopError').html(data.errors.TopError); 
          setTimeout(function() { 
           $('#er_TopError').hide(5000); 
           $('#er_TopError').html(''); 
          }, 5000); 
         } 
        } 
        else 
        { 
         $('#headLogin').html(data.loginMod); 
        } 
       } else { 
//      document.getElementById("setData").reset(); 
        $('#myModal').modal('hide'); 
        $('#successTop').show(); 
        $('#successTop').html(data.msg); 
        if (data.msg != '' && data.msg != "undefined") { 

         bootbox.alert({closeButton: false, message: data.msg, callback: function() { 
           if (data.url) { 
            window.location.href = '<?php echo site_url() ?>' + '/' + data.url; 
           } else { 
            location.reload(true); 
           } 
          }}); 
        } else { 

         bootbox.alert({closeButton: false, message: "Success", callback: function() { 
           if (data.url) { 
            window.location.href = '<?php echo site_url() ?>' + '/' + data.url; 
           } else { 
            location.reload(true); 
           } 
          }}); 
        } 

       } 
      } catch (e) { 
       if (e) { 
        $('#er_TopError').show(); 
        $('#er_TopError').html(e); 
        setTimeout(function() { 
         $('#er_TopError').hide(5000); 
         $('#er_TopError').html(''); 
        }, 5000); 
       } 
      } 
     } 
    }); 
3

Si desea enviar los datos usando jQuery Ajax, entonces no hay necesidad de etiqueta de formulario y botón de envío

Ejemplo:

<script> 
    $(document).ready(function() { 
     $("#btnSend").click(function() { 
      $.ajax({ 
       url: 'process.php', 
       type: 'POST', 
       data: {bar: $("#bar").val()}, 
       success: function (result) { 
        alert('success'); 
       } 
      }); 
     }); 
    }); 
</script> 
<label for="bar">A bar</label> 
<input id="bar" name="bar" type="text" value="" /> 
<input id="btnSend" type="button" value="Send" /> 
1

Hola por favor revisa que este es el completo e código de solicitud ajax.

 $('#foo').submit(function(event) { 
     // get the form data 
     // there are many ways to get this data using jQuery (you can use the 
    class or id also) 
    var formData = $('#foo').serialize(); 
    var url ='url of the request'; 
    // process the form. 

    $.ajax({ 
     type  : 'POST', // define the type of HTTP verb we want to use 
     url   : 'url/', // the url where we want to POST 
     data  : formData, // our data object 
     dataType : 'json', // what type of data do we expect back. 
     beforeSend : function() { 
     //this will run before sending an ajax request do what ever activity 
     you want like show loaded 
     }, 
     success:function(response){ 
      var obj = eval(response); 
      if(obj) 
      { 
       if(obj.error==0){ 
       alert('success'); 
       } 
      else{ 
       alert('error'); 
       } 
      } 
     }, 
     complete : function() { 
      //this will run after sending an ajax complete     
        }, 
     error:function (xhr, ajaxOptions, thrownError){ 
      alert('error occured'); 
     // if any error occurs in request 
     } 
    }); 
    // stop the form from submitting the normal way and refreshing the page 
    event.preventDefault(); 
});