Search code examples
jqueryhtmljquery-post

Jquery Post() not posting


The post values are not passing to the action page. Action page is returning only the static reply i.e. Thank you message without the $_POST part.

Below are the codes.

JQuery

<script>
    $(function() {
        $('#myF').submit(function (e) {

            e.preventDefault();
            $('#contactForm').html('<img src="images/ajax_small.gif" />');
            subMe();
        });
    });

    function subMe() {
        $.post('?action=contactdetails', $('#myF').serialize(),
            function(data) {
                $('#contactForm').html(data.returnValue);
            }, "json");
    }
</script>

HTML

<form id="myF">
    <div id="contactForm" valign="top" style="width:417;text-align:center" class="main">
<table width="417" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="45"><span class="style3">Name</span></td>
                <td width="373" height="30"><input name="name" id="name" style="padding-left:5px" type="text" title="Name is required." class="required form" /></td>
              </tr>
              <tr>
                <td height="14" colspan="2"><img src="images/spicer.gif" width="1" height="1" /></td>
              </tr>
              <tr>
                <td><span class="style3">Email</span></td>
                <td width="373" height="30"><input name="email" title="Please enter a valid email id." id="emailid" style="padding-left:5px" type="text" class="validate-email required form" /></td>
              </tr>
<tr colspan="2">
<input type="submit" value="Submit" />
</tr>
          </table>
</div>
</form>

Action page

<?php   
    if ( $action == 'contactdetails' ) {
        $data['layout'] = 'layout_blank.tpl.php';
            $nme = $_POST['name']; 
        echo json_encode(array("returnValue"=>"<strong>Thank you " . $nme . " for contacting us.<br /> We will get back to you soon.</strong>"));
    }
    ?>

Solution

  • Your inputs are located within the <div id="contactForm"> element until you call this line:

    $('#contactForm').html('<img src="images/ajax_small.gif" />');
    

    at which point they disappear. Once that's happened, calling .serialize() won't return any values because there aren't any inputs to be found.

    Call subMe() first, then change the content of that <div> element:

    $(function() {
        $('#myF').submit(function (e) {
            e.preventDefault();
            subMe();
            $('#contactForm').html('<img src="images/ajax_small.gif" />');
        });
    });