views:

69

answers:

1

I'm convinced this has been asked before and have found quite a few resources on this topic but I'm still very confused and not sure how to proceed.

I have a textarea whose data I need to send to a server and I need to capture the result which is a string. Here is my attempt:

$(document).ready(function () {

    $('#output-box').hide();

    $('#form1').submit(function () {
        var input = $('#txtinput').val()
        $.post('Default.aspx', { func: "ParseData" }, function (data) {
            $('#output-box').load(data).fadeIn();
        });
    });
});

How horribly am I off the mark?

+2  A: 

Close, but try this:

$(function () {  // I like the shorthand way

    $('#output-box').hide(); 

    $('#form1').submit(function () { 
        var input = $('#txtinput').val();
        $.post('Default.aspx', { func: "ParseData" }, function (data) { 
            $('#output-box').val(data).fadeIn(); // set the value to the returned data 
        });
        return false; // block the normal submit action
    }); 
});

Basically, you use the val() function to change the value of the textarea rather than "loading" data into it. Also, you need to return false from the event handler or you will both send the AJAX request and do the normal, post action on the form.

Edit: based on your comment. If you need to call parseData first, then something like this might be appropriate.

$(function () {

    $('#output-box').hide(); 

    $('#form1').submit(function () { 
        var input = parseData( $('#txtinput').val() );
        $.post('Default.aspx', { txtinput: input }, function (data) { 
            $('#output-box').val(data).fadeIn();
        });
        return false;
    }); 
});
tvanfosson
+1 - good point re 'return false'. this could drive a 'buddy' insane if not realised!!
jim
Thank you for the response but I guess I didn't make my question clear enough. When I put in func: "ParseData", it my form data going to be sent to the function? Also, I grabbed the textbox contents but I forgot to do anything with them - is something like func: "ParseData(input)" appropriate?
Radu
@Radu - the way you have it now, `func` will be passed as a request parameter with `parseData` as the value. If parseData is a javascript function, then you should call it and pass the result to the server-side as the appropriate parameter. I'll update with an example.
tvanfosson
ParseData is the serverside function that I need to pass the input to.
Radu