screamingnugget screamingnugget - 4 months ago 6
Ajax Question

How do you make the response of an HTML form update the text on a page?

I have a form in HTML as follows. I am trying to make it so the response (a string) of this POST becomes the text with id="answer".

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"> </script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="form.js"></script>
</head>
<body>
<form id="myForm"
action="http://myserver.com/post-destination/"
method="post">
<p><label>Input: <br><textarea name="formInput"></textarea></label></p>
<p><input type="submit" value="Submit" /></p>
</form>
<p id="answer">?</p>
</body>


I am attempting to use the jQuery Form plugin in a file called form.js, which consists of:

$(document).ready(function() {
$('#myForm')
.ajaxForm({
target: "#answer"
});
});


What am I doing wrong here? I'm sure it's just something really dumb, and I know there are a lot of questions about HTML forms and jQuery, yet following them is proving unsuccessful. I just can't figure this out whatsoever as it's my first time attempting anything web-related. Thanks for the help!

Answer

You jQuery ajax calls appears to be incorrect. You can refactor it as below:

$(document).ready(function() {
    $('#myForm').submit(function(e)
{
    var postData = $(this).serializeArray();
    var formURL = $(this).attr("action");
    $.ajax(
    {
        url : formURL,
        type: "POST",
        data : postData,
        success:function(data, textStatus, jqXHR) 
        {
            // set the target data 
            console.log ('set the target data');
        },
        error: function(jqXHR, textStatus, errorThrown) 
        {
            //if fails   
            console.log ('server responded something else ...');
        }
    });
});
});
Comments