1

I would like to convert this ajax function to a jquery function but im not sure how it would be done in jquery

function ajax_posta() {
// Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
    var url = "javas.php";


    hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function () {
        if (hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById('status').innerHTML = return_data;
        }
    }
// Send the data to PHP now... and wait for response to update the status div
    hr.send("num=" + (--num)); // Actually execute the request
    document.getElementById('status').innerHTML = "<img src = 'loading.gif' height =     '30'     width = '30'>";

}
$(document).ready(function()
{
    $('.eventer.button').click(function () {
        var self = this;
        $.post('javas.php', function (data) {
            $(self).parent('div').find('.status').html(data);
        })
    });
}
)
;
</script>
1
  • +1 for putting up with my initial sloppiness :) Commented Dec 16, 2011 at 20:42

1 Answer 1

2

You're pretty much there

$.ajax('javas.php', {
    success: function(response) {
          $(".status").html(response);
    }, 
    data: "num=" + (--num)
});

If these are the only two pieces of data you need to send to your request, you could just use $.post, but the advantage here is that if you ever want to specify more options, like contentType, all you'd have to do is add it to the existing options object.

Sign up to request clarification or add additional context in comments.

18 Comments

please may you explain a little more :D
small problem, status is not an Id it is a class
@foshoeiyyy - I added in your content type like your original code, and I made the callback more similar to the original.
+1, but I think this content-type is default for post, so it isn't necessary.
@foshoeiyyy - I assumed it was an id since you were calling it with getElementById in your original code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.