views:

129

answers:

3

How can I post data using ajax and display the posted data in a div on the same page without page refresh??

A: 

best jquery form plugin http://jquery.malsup.com/form/ even possible uploading files - ajaxed

vertazzar
A: 

Try markup something like this...

<form action="http://google.co.uk/search" method="get" onsubmit="postTheForm(this); return false;">
    <input type="hidden" name="q" value="Stackoverflow"/>
    <input type="submit" value="Click here"/>
</form>
<div id="postResults"></div>

With script like this...

function postTheForm(theForm){
    $.post(
        theForm.action, 
        $(theForm).serializeArray(), 
        function(data, textStatus, xmlHttpRequest){
            $("#postResults").html(data);
        }
    );
}

This example uses the GET method, but this is only because Google doesn't accept POST - but the principple should get you working and then you can change to a POST (Assuming that a POST is appropriate in your case)

belugabob
+5  A: 

To do this, you should not submit the form, but capture the form data with a click event, submit the data via AJAX and as the last thing... enter the data into the DIV element. E.g.

jQuery

$("#submitdata").click(function() {
  var FormVal={ datafield1:$('#field1').val(),
                datafield2:$('#field2').val()};

  $.ajax({
    type: "POST",
    url: "myupdatepage.cfm",
    dataType: "json",
    data: FormVal,
    async: false,
    success: function(response) { 
               $('#fillmein').html($('#field1').val()+'<br />'+$('#field1').val()); // Assign the values to the DIV
             }
  });
});

HTML

<form action="">
  <input type="text" id="field1">
  <input type="text" id="field2">

  <input type="button" id="submitdata" value="Submit data" />
</form>

<div id="fillmein"></div>
Gert G