Itamar
Itamar

Reputation: 534

PHP jQuery Form Submission

I've built a simple form which I want to send without refreshing the page, therefore I use jQuery. The problem comes up when I submit the form but process.php reports that the data was not transformed, and process.php prints the message "no post received". Here's the code of the form file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
</head>
<script type="text/javascript">
$(function(){
      $('#submit').click(function(){
          var getField = $("#field").val();
          $.ajax({
             url: 'process.php' , 
             type: 'POST',
             data: 'data: ' + getField,
             success: function(result){     
               $('#container').text('<p>' + result + '</p>')      
             }
          });   
          return false;     
       });
    });
</script>

<body>

<div id="container">
<form method="post" action="process.php">
<input name="field" id="field" type="text" />
<input type="submit" value="submit" id="submit" />
</form>
</div>

</body>
</html>

Here's process.php code :

<?php
if($_POST){
    echo $_POST['field'];
}
else
    echo "no post received";
?>

Do you have any idea what's wrong with the jQuery / the form ? Any suggestion is welcomed, Thank you

Upvotes: 0

Views: 1690

Answers (2)

dlwiest
dlwiest

Reputation: 655

data: 'data: ' + getField

That's posting the value of getField to process.php as "data", not "field", so you need to get the value of $_POST['data'], although naming variables "data" is usually not a good idea. You might also want to look up the jQuery post function, which was made for exactly what you're doing.

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

Looks like your data isn't formatted correctly. It should be a complete JavaScript object:

data: '{ data: "' + getField + '"}',

See http://api.jquery.com/jQuery.ajax/#entry-examples

Alternatively, and more conveniently, try using the .serialize() method.

Upvotes: 3

Related Questions