jquery ajax no configura variable a POST
Pregunta
Estoy perplejo. Estoy usando jquery y ajax para POSTAR algunos campos desde un formulario a la base de datos.
Esto es para un " formulario de edición " - para que todos los campos se rellenen con los datos existentes en la base de datos mysql. Estoy pasando la entrada de 4 campos, y solo funciona para 2 de ellos. Aquí está el HTML
<form id="editSubmit" method="post" name="editSubmit" action="" enctype="multipart/form-data">
<input type="hidden" id="newsID" name="newsID" value="<?=$newsID;?>">
<input type="hidden" id="authorID" name="authorID" value="<?=$news['editorID'];?>">
<label for="postTitle">Title</label><br />
<input type="text" name="postTitle" id="postTitle" class="text" size="20" value="<?=$postTitle;?>"/><br />
<label for="postText">Post Text</label><br />
<textarea name="postText" id="postText" class="textarea"><?=$postText;?></textarea> <br /><br />
<button type="submit">Submit Edit </button>
<input type="button" onClick="closeEdit()" value="Cancel">
</form>
Ahora aquí está el código que estoy usando para POSTAR esto a la página.
$("form#editSubmit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var newsID = $('#newsID').attr('value');
var postTitle = $('#postTitle').attr('value');
var postText = $('#postText').attr('value');
postText = postText.replace(/&/g,'%26');
var authorID = $('#authorID').attr('value');
$.ajax({
type: "POST",
url: "news/editNews.php",
data: "newsID="+ newsID + "&postTitle="+ postTitle + "&postText=" + postText + "&authorID=" + authorID,
success: function(){
$('form#editSubmit').fadeOut('slow');
$('div.success').fadeIn();
}
}); // End .ajax function
return false;
}); //End submit function()
Este código se envía con éxito a través del ID de autor y el ID de la noticia, pero no hay suerte con el título o postTexto. No puedo ver lo que estoy haciendo mal. Tal vez me esté perdiendo algo?
Además, soy un novato en ajax / jquery, así que agradecería cualquier consejo si hay algo extraño en el código. Ha sido mucho ensayo y error llegar tan lejos.
Solución
Para sus entradas de texto y área de texto, desea utilizar el método val () en lugar de attr ('valor'). El uso de attr ('valor') es correcto para entradas ocultas. Aún mejor, solo use $ (this) .serialize () como su parámetro de datos.
$("form#editSubmit").submit(function() {
var $form = $(this);
$.ajax({
type: "POST",
url: "news/editNews.php",
data: $form.serialize(),
success: function(){
$('form#editSubmit').fadeOut('slow');
$('div.success').fadeIn();
}
}); // End .ajax function
return false;
}); //End submit function()
Otros consejos
Haz esto:
$.ajax({
type: "POST",
url: "news/editNews.php",
data: {
newsID: newsID,
postTitle: postTitle,
postText: postText,
authorID: authorID
},
success: function() {
$('form#editSubmit').fadeOut('slow');
$('div.success').fadeIn();
}
});
Deje que jQuery haga el trabajo pesado con respecto a escapar y así sucesivamente. Pasar un objeto anónimo al campo data
es el método preferido.
También haz esto:
$("...").val();
en lugar de:
$("...").attr("value");
Por último, en lugar de:
<input type="button" onClick="closeEdit()" value="Cancel">
La forma más " jquery " es:
<input type="button" id="cancel" value="Cancel">
con:
$(function() {
$("#cancel").click(closeEdit);
});
No necesita usar $ ('form # editSubmit')
- $ ('# editSubmit')
funcionará bien.
Puede recuperar los valores de sus campos utilizando la función val ()
:
var newsID = $('#newsID').val();
var postTitle = $('#postTitle').val();
var postText = $('#postText').val();
La otra cosa que observo es que su dataType no está definido. Si está enviando esto como un objeto JSON, sería mejor que proporcione dataType, contentType y presente sus datos reales como propiedades de objeto separadas:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "news/editNews.php",
data: "{'newsID':" newsID + ",'postTitle':'"+ postTitle + "','postText':'" + postText + "','authorID':" + authorID + "}",
success: function(){
$('form#editSubmit').fadeOut('slow');
$('div.success').fadeIn();
}
});
También puede buscar en las funciones serialize ()
o serializeArray ()
.