jquery + web services?

Discussion in 'jQuery' started by mokimofiki, May 26, 2011.

  1. #1
    I am working on using jquery to pull information from a web service and fill form fields based on a zip code entered.

    Here is what I have so far:
    <form id="formname">
    <input type="text" id="zipcode" /><br />
    <input type="text" id="name" />
    </form>
    
    <script>
    $('#zipcode').bind('blur', function(evt))
    {
    $.post('http://muzak-dealers.heroku.com/dealers/33156?security_token=A26F777D-EA30-4F15-B956-648662E34F17&callback=', { 
    $('#name').attr('name') : $('#name').val(), 
    }, 
    function(data) {
    alert('Done');
    alert(data);
    }
    });
    </script>
    Code (markup):
    I am new to custom jquery so don't judge my code to badly :)

    Explanaition of how it currently works is as follows:
    1. user fills in the zip code
    2. when leaving the field the name should populate in the next field based on what was pulled from the web service.

    Right now I have a static zipcode in the url to test it.
     
    mokimofiki, May 26, 2011 IP
  2. joshpeyton

    joshpeyton Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    
    <form name="formname">
    <input type="text" id="zipcode" value="" />
    <input type="text" id="name" value="" />
    </form>
    <script>
    $('#zipcode').blur(function() {
    	
    var zpcode = document.getElementById('zipcode').value;
    jQuery.getJSON("http://muzak-dealers.heroku.com/dealers/" + zpcode + "?security_token=A26F777D-EA30-4F15-B956-648662E34F17&callback=?", 
    function(data) {
    
    	$("#name").val(data["name"]);
    	
    });
    });
    </script>
    
    <form id="formname">
    <input type="text" id="zipcode" /><br />
    <input type="text" id="name" />
    </form>
    Code (markup):
    The line "$('#zipcode').blur(function() {" says run the function onblur or when the cursor is moved from the zipcode field.

    The line "var zpcode = document.getElementById('zipcode').value;" sets the variable zpcode to whatever zipcode is entered.

    The line "jQuery.getJSON("http://muzak-dealers.heroku.com/dealers/" + zpcode + "?security_token=A26F777D-EA30-4F15-B956-648662E34F17&callback=?",
    function(data) {" gets the information for whatever zipcode is entered.

    The line "$("#name").val(data["name"]);" puts the value called back from the json value for name and puts it into the name field on your form.

    Hope this helps!
     
    joshpeyton, Jun 7, 2011 IP