krrr25 krrr25 - 5 months ago 20
PHP Question

How to get the response data in ajax call

I have a php file(index.php) with two fields when i post that form, in javascript i am doing form data serialize and send it to next php page(results.php) through ajax. When i try to print the data inside success it is not printing. FInd the below code.

<html>
<head>
<title></title>
<script src="../scripts/jquery-1.9.1.js"></script>
</head>
<body>
<form method="post" name="index" id="indexform">
<table border="1">
<tr>
<td>Name:</td>
<td><input type="text" name="fname"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="sendData"></td>
</tr>
</table>
</form>
</body>
<script type="text/javascript">
$( "#indexform" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $(this).serialize() );
var formdata = $(this).serialize();
// alert(formdata);
$.ajax({
type:"POST",
url:"result.php",
dataType:'json',
data:formdata,
success: function(data){
alert(data);
}
});
});
</script>




In the above i cant print the data inside the success callback.

Answer

Try this

<script type="text/javascript">
        $( "#indexform" ).on( "submit", function( event ) {
              event.preventDefault();
              console.log( $(this).serialize() );
              var formdata = $(this).serialize();
              $.ajax({
                    type:"POST",
                    url:"result.php",
                    data:formdata,
                    success: function(html){
                        alert(html);
                    }
              });
            });
        </script>

In your result.php page

 $name=$_REQUEST['fname'];
    $email=$_REQUEST['email'];
    echo $name." ".$email;
Comments