Source: http://stackoverflow.com/questions/7945848/submit-a-form-without-refreshing-redirecting-of-the-current-page-python-django
the link above also comes with a jsfiddle with code.
So since i’ve done ‘false forms’ with jQuery i figured i would cover what i think is the right way to forms with jQuery and AJAX.
Below you can see a form, nothing to exciting, it just excludes the action and method of a form. Why? because we’ll not be using them. I’m not sure how this validates with W3C. Also, this is the just the javascript that you need for this. Tumblr wont let me post HTML to a blog, which is pretty reasonable.
$('#submitButton').click(function(){
var userInput = $('#formId').serialize();
$.post('post/to/this/place', userInput, function(data){
// do something with the data if you want.
});
});
Also, don’t forget that you can append thr $.post() method with .success() and .fail() so that they get called when the method is successful or fails. These two methods accept other methods as callback functions
Lastly, we should clear the form so that it’s fresh to go again. There are a couple of ways to do this but the easiest way to do this is
$('#formId input[type=text]').val('');
//use the below code if you have check boxes in your form
$('#formId input:checkbox').removeAttr('checked');
And that’s it. Use it wisely.
Something that i find my self constantly dealing with on newer websites is submitting data with AJAX but not wanting to handle some of the headache <form>’s bring with the action attribute. In a case like this i use a ‘false form’
A false form is something that the use still interacts with like a form, and it still behaves like a form, but it’s markup isn’t in a form tag.
$(document).keypress(function (e){
if(e.which == 13 && $('#inputBox').is(':focus')){
//send ajax
}
});
What’s actually happening here is that jquery is not listening to the whole DOM for key press events. It then passes that event down and uses the anonymous callback function we’ve written and uses this nifty little if statement.
if(e.which == 13 && $('#inputBox').is(':focus'))
This if statement ensures that the user is hitter their enter key (13) and that the input box is in focus (they’ve clicked on it and haven’t deselected anything).
Once the user then hits enter, you could call an AJAX function such as jQuery’s $.post().
Although, this type of behavior is a bit costly. jQuery is now listening to every key stroke which to me seems a bit waist full. Also, if a user were to have Javascript disabled (who does that?!) this ‘false form’ would fall apart and a standard web form would still work.
In the past couple of months i’ve been exclusively using the PHP framework Laravel. Laravel is often called the ‘Rails’ of the PHP world. Keeping the same theme as my last blog post, lets do some sort of validation with PHP and Laravel.
In the example below i’ll be accepting an email from the global POST variable, validating that it is in fact an email address, ensuring that it’s a unique email address and then either returning the errors, if the email is not unique or valid, or true if it’s valid and unique.
<?php
//Laravel uses ALOT of static methods
$validation-Rules = array('email' => 'required|email|unique:users);
//the :unique caluse requires the input to be unique.
//this also makes laravel check the users table and ensures that this email is unique
$input = Input::get('email');
$result = Validator::make($input, $rules);
if($result->fails){
return $result-errors;
}
return true;
See how easy that is? With laravel, it doesn’t much harder than that.
It really allows you to express exactly what you want to do through your code with out requiring you to write a bunch of boilerplate code. Also, it allows you to focus on the big picture and start thinking about OO concepts with your code such as inheritance and polymorphism and how to utilize them in your code.
I was introduced to the Map function recently when browsing /r/DailyProgrammer for easy programming challenges. The challenge at hand required us to create a change calculator by accepting an array of decimal and non-decimal number. This is where the Map function comes in.
The Map function allows us to, as quoted by the MDN, “[it provides] a callback function once for each element in an array, in order and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned value; it is not invoked for indexes which have been deleted or which have never been assigned values.”
Using the above change example if we wanted to see how many quaters we’re required for each set of inputs we could do something like this
function quarters(amount){
return amount / 0.25;
}
function(changeArray){
var result = changeArray.map(quarters);
console.log(result);
}
This would allow us to devide each element of the array by a quarter (24) and log the results of that devision to the console.
A different approach to using this method is using it inconjunction with input validation. For example, if a group of emails needs to validated a very similar approach could be taken
function validateEmail(email){
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
//regular expression used to check email.
//Yes i know about the debates on email
//validation. Source
return reg.test(email);
}
function checkMail(emailList)
{
var results = emailList.map(emailList);
for(var result in emailList)
{
if(result == false)
{ return false; }
}
return true;
}
As you can see the above function assesses each email, returns the results of a regular expression test, and then assesses the results of that test. If any result is false, an email was invalid and the method checkMail returns false. As you can see, using the map function greatly reduces the amount of coding you must do, makeing your job much simpler.