Request.JSON
sending a JSON request to the jsFiddle backend. Later on parse and display the data.
by keif
HTML
<h2>Add a User:</h2>
<form>
<input type="text" name="username" placeholder="name">
<input type="email" name="email" placeholder="email">
<button>add user</button>
</form>
<h2>Users:</h2>
<ul id="users"></ul>
CSS
body {
font-family: Helvetica, Sans, Arial;
}
p, ul {
padding: 10px;
}
ul {
margin: 5px;
border: 2px dashed #999;
}
.error {
border: 1px solid #f00;
color: #f00;
padding: 10px;
}
JavaScript
/*
Requirements:
- Use ajax via the add_user function to submit the user entered data.
- You can assume the service will respond with 200 status.
- Display an error in red at the top of the form when the add user service responds with success property with a value of false.
Use the error property as the message.
- Display new users in the users list when the response returns a success property
- Highlight the email input when a user enters an invalid email address. Also, display the text "please enter a valid email address" in red.
NOTE: The service will not provide this validation functionality, and will accept invalid emails.
*/
//example usage.
// addUser('john', 'smith', function(response){
// console.log('response is: ' + JSON.stringify(response));
// });
(function($){
// quick dirty email regex
var emailPattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,4}))$/,
// handle display of error messages
errorHandler = function(errorText) {
var $errorMsg = $('.error');
// show the error message
if (errorText) {
// check if we have generated an error message
if (!$errorMsg.length) {
$errorMsg = $('<div/>', {
'class': 'error',
text: errorText
});
$form.prepend($errorMsg);
} else {
$errorMsg.text(errorText).show();
}
} else { // hide it
$errorMsg.hide();
}
},
$list = $('ul'),
// stop default form submit
$form = $('form').on('submit', function(e) {
// check that the email is valid before submitting to service
emailPattern.lastIndex = 0;
var username = $username.val();
...