2012-01-18 21 views
19

Tengo problemas para que mi jQuery ajax funcione correctamente. Dirige a la página de PHP para actualizar la base de datos, pero nunca regresa al script para las opciones de éxito o error.Error de la función de éxito y error de Ajax

Mi código es el siguiente:

$(document).ready(function(){ 
     $("form#updatejob").submit(function() { 
      function textreplace(x) {return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");} 
      // we want to store the values from the form input box, then send via ajax below 
      var job  = $("#job").attr("value"); 
      var description  = $("#description").val(); 
      description.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 
      var startDate = $("#startDate").attr("value"); 
      var releaseDate = $("#releaseDate").attr("value"); 
      var status = $("#status").attr("value"); 
      $.ajax({ 
       beforeSend:textreplace(description), 
       type: "POST", 
       url: "updatedjob.php", 
       data: "jobID="+ job +"& description="+ description +"& startDate="+ startDate +"& releaseDate="+ releaseDate +"& status="+ status, 
       success: function(){ 
        $("form#updatejob").hide(function(){$("div.success").fadeIn();}); 
       }, 
       error: function(XMLHttpRequest, textStatus, errorThrown) { 
        alert("Status: " + textStatus); alert("Error: " + errorThrown); 
       }  
      }); 
      return false; 
     }); 
}); 

Y el PHP:

<?php 
    include("connect.php"); 
    $job = trim($_POST['job']); 
    $startDate = trim($_POST['startDate']); 
    $releaseDate = trim($_POST['releaseDate']); 
    $mysqlstartdate = date('Y-m-d', strtotime($startDate)); 
    $mysqlreleasedate = date('Y-m-d', strtotime($releaseDate)); 
    $description = trim($_POST['description']); 
    $status = trim($_POST['status']); 
    $update = "UPDATE jobs SET startDate = '$mysqlstartdate', releaseDate = '$mysqlreleasedate', description = '$description', status = '$status' WHERE jobID = '$job' "; 
    $rsUpdate = mysql_query($update); 
// or die(mysql_error()); mysql_close(); 
?> 
+0

Lo que sucede si se pone un 'alerta()' en la primera línea de la función de devolución de llamada Success' '? 'success: function() {alert ('foobar'); ...' – Jasper

+0

Parece lógico que proporcione el código php también. ¿Te haces eco de una respuesta? –

+0

Aquí está el PHP: '' – michael

Respuesta

48

Prueba esto:

$.ajax({ 
    beforeSend: function() { textreplace(description); }, 
    type: "POST", 
    url: "updatedjob.php", 
    data: "jobID="+ job +"& description="+ description +"& startDate="+ startDate +"& releaseDate="+ releaseDate +"& status="+ status, 
    success: function(){ 
     $("form#updatejob").hide(function(){$("div.success").fadeIn();}); 
    }, 
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
     alert("Status: " + textStatus); alert("Error: " + errorThrown); 
    }  
}); 

La propiedad beforeSend se establece en lugar de function() { textreplace(description); }textreplace(description). La propiedad beforeSend necesita una función.

+0

Cambié esa parte, pero todavía no regresa a la función. Gracias por el intento. – michael

0

Esto puede no resolver todos sus problemas, pero la variable que está utilizando dentro de su función (texto) no es lo mismo que el parámetro que está pasando en (x).

cambiante:

function textreplace(x) { 
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 
} 

Para:

function textreplace(text) { 
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 
} 

parece que sería hacer algo bueno.

3

Puede implementar la lógica de error específico de la siguiente manera:

error: function (XMLHttpRequest, textStatus, errorThrown) { 
    if (textStatus == 'Unauthorized') { 
     alert('custom message. Error: ' + errorThrown); 
    } else { 
     alert('custom message. Error: ' + errorThrown); 
    } 
} 
2

Esto puede ser una entrada antigua, pero me di cuenta que no es otra cosa que ser devuelto desde el php y la función de su éxito no tiene entrada como la siguiente manera , success:function(e){}. Espero que eso te ayude.

4

También se puede utilizar el siguiente para atrapar a los errores:

$.ajax({ 
    url: url, 
    success: function (data) { 
     // Handle success here 
     $('#editor-content-container').html(data); 
     $('#editor-container').modal('show'); 
    }, 
    cache: false 
}).fail(function (jqXHR, textStatus, error) { 
    // Handle error here 
    $('#editor-content-container').html(jqXHR.responseText); 
    $('#editor-container').modal('show'); 
}); 
3

que estaba teniendo el mismo problema y lo arreglaron por simple adición de un tipo de datos = línea "texto" a mi llamada AJAX. Haga que el tipo de datos coincida con la respuesta que espera obtener del servidor (su mensaje de error "inserción exitosa" o "algo salió mal").

0

Está enviando un tipo de publicación con datos implementados para obtener. su forma debe ser el siguiente:

$.ajax({ 
url: url, 
method: "POST", 
data: {data1:"data1",data2:"data2"}, 
... 
Cuestiones relacionadas