SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Wizard
    Join Date
    Jan 2005
    Location
    blahblahblah
    Posts
    1,447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    using AJAX with jQuery

    Hello,
    I'm new to jQuery (and AJAX for that matter). Even if the library is really easy to use, I'm still having problems "ajaxing".

    I'd like to understand how to post the following simple form to the server, and send a message to the client depending on the submission process output (telling him if what he submitted is ok or not).

    Would someone be kind enough to guide me through the steps?

    Here's the HTML bit. I am going to use jQuery with the Zend Framework (PHP).

    HTML Code:
     <html>
      <head>
        <script type="text/javascript" src="jquery-1.2.1.js"></script>
        <script type="text/javascript">
    
    //?
    
        </script>
        
      </head>
      <body>
      
      <form action="/test/ajax/record/" method="post">
    
        <input type="text" name="test" value="" />
        <input type="submit" name="ajax" value="save" />
        
      </form>
      
      </body>
     </html>

  2. #2
    SitePoint Member
    Join Date
    Dec 2007
    Location
    I live in Dublin, Ireland
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi, JJ

    jQuery's selectors work best with id's. So in order to be able to submit information to the library, you'll need to give each form input an id value. Try something like id='test' and id='submit'.

    Assuming you've added this to your form, here's some sample code to get you started using AJAX in jQuery:

    Code:
    $(document).ready(function()
    {
    
       $("#submit").click(function()
    	{
    
                $.ajax
    	    ({
    		type:	'POST',
    		url:	  '/test/ajax/record/',
    		data:	  'test=' + $('#test').val(),
    		dataType: 'json',
    
                    success: function(data)
    		{
    			alert('It worked! The response was: ' + data);
    		},
    	
    		error:function(data)
    		{
    			alert('There was an error! The response was: ' + data);
    		}
    
                });
    });

    I haven't tested it but it should work ok, so long as you enter the above code in the section of the header for JavaScript.

    If you need any help with the server side script or with formatting the JSON response, let me know and I'll post up something for that too.

    Bare in mind though that this example expects JSON as the returning format from the server, but jQuery can accept XML or plain text either depending on what you want to do with the result.

    I hope this helps.
    Last edited by iarfhlaith; Dec 21, 2007 at 06:41.
    Iarfhlaith Kelly
    Webstrong Internet Solutions
    Web: www.webstrong.net

  3. #3
    SitePoint Wizard
    Join Date
    Jan 2005
    Location
    blahblahblah
    Posts
    1,447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you very much for your answer

    Just a few questions:
    1.
    PHP Code:
    data'test=' + $('#test').val(), 
    Do you have to set each field of every form, or can you just submit the post collection as a whole and treat it server side?

    2.
    PHP Code:
    success: function(data)
    {
    alert('It worked! The response was: ' data);
    },

    error:function(data)
    {
    alert('There was an error! The response was: ' data);

    How do you trigger success or error in this example? I guess it's done server side, but I can't figure out how.

    Thanks again for your time

  4. #4
    SitePoint Member
    Join Date
    Dec 2007
    Location
    I live in Dublin, Ireland
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As far as I know, you have to build the querystring manually. But I haven't looked into that in great detail before. Take a look at the jQuery documentation and you might find something that grabs the entire set of inputs for the form.

    For example here's a code snippet from the jQuery documentation (http://docs.jquery.com/Selectors/input) that grabs all of the input values in a form. Bare in mind though that you'll need to change something like this to cater for differences in your form if you've got additional input types like <select> etc.

    Code:
    var allInputs = $(":input");
    Also, you might want to use this line in your code that's fired when the user hits the submit button so that the form doesn't reload the page using the traditional method.

    Code:
        return false;   // so it won't submit
    The success/error trap is part of jQuery's internal AJAX implementation and is all inbuilt. An error will be triggered if there is a communications problem when querying the server or if the returned string has any syntactical error's.

    I hope this helps.
    Iarfhlaith Kelly
    Webstrong Internet Solutions
    Web: www.webstrong.net

  5. #5
    SitePoint Wizard
    Join Date
    Jan 2005
    Location
    blahblahblah
    Posts
    1,447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This helps a lot indeed. Browsing the plugin repository, I've found a plugin that serializes post collections and sends it to the srver.

    I am facing now another problem though. How do you deal with error messages? I am always displaying a general error message (at the top of the form) and a specific error message (next to the problematuc field).

    What would be the Ajax mentality to approach this problem?

  6. #6
    SitePoint Member
    Join Date
    Dec 2007
    Location
    I live in Dublin, Ireland
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The best way to achieve this is not through AJAX as such but by using jQuery's ability to manipulate the DOM.

    Based on if there's a communications error or if some form field wasn't entered (which you can check for in the response from the server) you can use jQuery to append or replace code within the page on the fly.

    This new code can contain your error message and can be either loaded from a hard coded error message within the script itself or taken from part of the response from the server as part of the AJAX call.

    Try it out by using jQuery's .append feature. This lets you insert text or code into an existing element.

    For Example:

    Code:
    $('#errorBox').append('The form was not completed');
    Try adding this line or one similiar to it into the success:function and the error:function and see how you get on. If there was a field not entered correctly then you'll need to check if the form was valid. I usually use a JSON response to tell me two key things about how the data faired up on the server. These are:

    1. Using a boolean value to check if the form validated or not.
    2. Using an array of the error messages for each field that didn't validate (you can then use this in your append statements so that you can display it to the user.)

    Once you know these you have enough information to either display a thank you message, or an error message and you can also display a generic one on the top of the page as well as displaying specific error messages beside each of the fields causing the errors.

    How's that?
    Iarfhlaith Kelly
    Webstrong Internet Solutions
    Web: www.webstrong.net

  7. #7
    SitePoint Wizard
    Join Date
    Jan 2005
    Location
    blahblahblah
    Posts
    1,447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Iarfhlaith Kelly, you rock.

    Ok that's how I thought it would be done. Technically, I'm still missing a few key concepts:
    Code:
    $('#errorBox').append('The form was not completed');
    How would you replace 'The form was not completed' by a value sent by the server to Client?

  8. #8
    SitePoint Wizard
    Join Date
    Jan 2005
    Location
    blahblahblah
    Posts
    1,447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just an idea (and another question): would it be possible to send the form, process it, create an html output (with error messages) and display that html chunk instead of the previous form (that we've made disappear using jQuery)? Would that be a satisfying approach?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •