Getting Started With jQuery - Ajax Post |
Written by Ian Elliot | |||||||
Monday, 14 September 2015 | |||||||
Page 3 of 3
Now we have control of the submit process all we have to do is arrange for the form's data to be sent to the server but first we have to encode it appropriately because this is no longer done for us. The simplest way to do this is to use the jQuery serialize data method:
We use this in the submit event handler because it is set to the element that originated the event. Putting all this together gives:
Notice that now the data returned by the server doesn't replace the current page and in this case it is simply printed to the console. A get works in exactly the same way and the server side code doesn't need to be modified from its basic form handling to cope with data sent by Ajax rather than the default submit. The only difference is that the data returned doesn't replace the page. What advantage does this have? The answer to this question ranges from something sophisticated, e.g. because you are writing a single page application, to the fairly obvious, e.g. because you don't want the page context to change because of a form submit. For example, you could check that the form contains valid data before posting it to the server and if not the form wouldn't be cleared by the page that overwrites it. In other words, the user's context, i.e. any data they may have entered, remains unaltered by the submit. It is also the case that submitting data using Ajax means that the user isn't subjected to the loading of a new page. Where Next?We now know how to get data from the server and send it using both get and post. What more could there be? There are some lower level Ajax methods that are worth knowing about that let you tailor the interaction more finely than the easy to use get and post methods. You also need to deal with the problems posed by headers, MIME types, character codings and caching. All of these topics will cause you problems sooner or later, even if you stick to the very basic get and post method, unless you master them. Summary
More InformationJust jQuery
|
JavaScript Canvas - Fetch API Working with lower-level data is very much part of graphics. This extract from Ian Elliot's book on JavaScript Graphics looks at how to use typed arrays to access graphic data. |
JavaScript Jems - The Inheritance Tax JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way. In particular, it doesn't do inheritance [ ... ] |
Other Articles |
To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info