views:

140

answers:

1

I'm trying to make an AJAX form that will update a twitter status when updated. I have the form working currently with php, but am not sure how to add AJAX functionality.

Here's the form:

    <form id = "yourwhisper" method = "post" >
        <label for="whisper">Enter your status update</label>
        <textarea id="whisper" name="whisper" rows="2" cols="50" required></textarea>
        <label class="error" for="whisper" id="whisper_error">Must be no more than 140 characters.</label>

        <input id="lat" name="lat" style = "display:none"></input>
        <input id="lon" name="lon" style = "display:none"></input>
        <button type="submit" id = "submit">Pass it on</button>
    </form>

This is the php which I had as the form action (it calls a php function from a twitter api library). I've now moved it to form-manager.php:

$t->update($_POST["whisper"], false, $_POST["lat"], $_POST["lon"]); 

Finally, this is the jQuery code that adds the AJAX functionality. It takes the text for the update, along with the geolocation data, and passes it to the form-manager.php file in the form of the 'dataString'.

<script type="text/javascript" charset="utf-8">
        $(function() {  
          $('.error').hide();  
          $(".submit").click(function() {  
            // validate and process form here  

            $('.error').hide();  
            var whisper = $("textarea#whisper").val();
            var lat= $("input#lat").val();
            var lon = $("input#lon").val();
            if (whisper == "") {  
                $("label#whisper_error").show();  
                $("textarea#whisper").focus();
                return false;  
            }

            var dataString = 'whisper='+ whisper + '&lat=' + lat + '&lon=' + lon;  
            //alert (dataString);return false;  
            $.ajax({  
              type: "POST",  
              url: "form-manager.php",  
              data: dataString,  
              success: function() {  
                // alert ("form sent");
                });  
              }  
            });  
            return false;

          });  
        });

    </script>

My problem is, how do I then get form-manager.php to take that info and put it into the 3 variables it needs to update twitter?

+1  A: 

the dataString should be available to PHP as $_POST['dataString']. It is only a single var that contains a string. You should explode it.

Or if you want you can set the data property of the ajax method like { whisper: "Foo", lat: "fooLat" } so they will show up like $_POST['whisper'] and $_POST['lat']

Sinan
So if I format the data string to make sure it's exactly what should be being posted, it should work?
Chris Armstrong
data: { whisper: "Foo", lat: "xxx", lon: "xxx"} should the work
Sinan
Sinan
That works great, thanks
Chris Armstrong