I’m stumped. I’m using jquery and ajax to POST some fields from a form to the database.
This is for a “edit form” – so all the fields are pre-filled with data existing in the mysql database. I’m passing input from 4 fields, and it only works for 2 of them. Here’s the 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>
Now here’s the code I’m using to POST this to the page.
$("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()
This code is successfully sending over the authorID and newsID, but no luck with the postTitle or postText. I can’t see what I’m doing wrong. Maybe I’m missing something?
Also, I’m a totally newbie to ajax/jquery – so I’d appreciate any tips if something looks weird in the code. It’s been a lot of trial and error to get this far.
For your text inputs and textarea, you want to use the val() method instead of attr(‘value’). Using attr(‘value’) is correct for hidden inputs. Even better, just use $(this).serialize() as your data parameter.