tags:

views:

46

answers:

2

How easy is it to convert the following PHP form submission to an Ajaxy type form.

Here is the PHP:

<?php //Send Tweet
    if(isset($_POST['submit'])) {
    $qtweet = $_REQUEST['tweet'];
    $connection->post('statuses/update', array('status' => $qtweet));
    echo "<div style='padding-bottom: 5px; color: #0099FF;'>Updated your Timeline Successfully.</div>";
    }
?>

And the HTML form:

<form id="tweethis" method='post' action='index.php'>
    <textarea style="width: 346px;" name="tweet" rows="5" id="tweet" ></textarea>
    <br />
    <span id="charLeft">140</span>  Characters left
    <br />
    <input type='submit' value='Tweet This!' name='submit' id='submit' />
    <br />
</form>

I'd like to use Ajax so the page doesnt need to reload.

A: 

Pretty easy.

Use $.ajax, and check out the serialize() function to convert your form data. You will also need to prevent the default behaviour and event bubbling. This tutorial is pretty good.

Inside the ajax call you have to specify the PHP page which will handle the request. That script will handle the form submission, like in normal PHP forms and then echoes out any output. That output will be passed back to the calling client.

Extrakun
+1  A: 
$(document).ready(function() {
    $("#tweethis").submit(function() {
        $.post('index.php', $("#tweet").val(), function(html) {
            $("#resultDiv").html(html);
        });
        return false; // prevent normal submit
    });
});

Take a look at $.ajax and the $.post (and $.get) wrappers for it.

karim79