Before i get to the code i posted below ill highlight what i found...
- When using input fields its best to wrap them inside a <form> element for semantic markup and so it can be used without the need for javascript
- A quick tip a co-worker taught me was to use event.preventDefault() as rather then return false it doesn't allow for the script to continue or reload the page if an error occurs.
- In your texter.php file you had isset($_POST['msg_submit']) which wouldn't have worked at all as your AJAX call didn't have any data parameters that contained that key name.
- When writing your code its best not to use classes too much as they take longer to find on a page due to them been allowed to appear multiple times. Id's are a more efficient and less time consuming way to write your markup.
form.php
HTML Code:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function(e) {
// Prevent the default form action
e.preventDefault();
// Get the value of the "textValue" field
var textValue = $('input[type="text"]', this).val();
// Make sure that the "textValue" field has a value/length
if (!textValue.lenth || textValue == '') {
$('#success').fadeOut(200);
$('#error').fadeIn(200);
return false;
}
$.ajax({
data : {text: textValue},
type : $(this).attr('method').toUpperCase(),
url : $(this).attr('action'),
success : function(data) {
if (data === 'success') {
$('#error').fadeOut(200);
$('#success').fadeIn(200);
} else {
$('#success').fadeOut(200);
$('#error').fadeIn(200);
}
}
});
});
});
</script>
<form action="texter.php" method="post" id="myForm">
<input type="text" name="textValue" />
<input type="submit" value="Submit" />
</form>
<span id="error" style="display: none;">ERROR FIELD IS EMPTY</span>
<span id="success" style="display: none;">DONE</span>
texter.php
PHP Code:
if (isset($_POST['text'])) {
$text = quote_smart3(htmlspecialchars($_POST['text']));
if (empty($text)) {
echo 'error';
} else {
// $sql = ..
echo 'success';
}
exit;
}
Bookmarks