Forum Moderators: open

Message Too Old, No Replies

jquery and post

         

Lolalola

7:21 am on Aug 6, 2010 (gmt 0)



Hi,

why i don't get data from jQuery? Variables POST always empty.

Thanks

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$("form#submit").submit(function() {

var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
$.ajax({
type: "POST",
url: "#",
data: "fname="+ fname +"& lname="+ lname,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});

}
});
return false;
});
});
</script>
</head>
<body>
<?php
echo 'fname:' . $_POST['fname'] . '<br/>';
echo 'lname:' . $_POST['lname'];
?>
<div class="container">
<form id="submit" method="post">
<fieldset>
<legend>Enter Information</legend>
<label for="fname">Client First Name:</label>
<input id="fname" class="text" name="fname" size="20" type="text">

<label for="lname">Client Last Name:</label>
<input id="lname" class="text" name="lname" size="20" type="text">

<button class="button positive"> <img src="../images/icons/tick.png" alt=""> Add Client </button>
</fieldset>
</form>
<div class="success" style="display: none;">Client has been added.</div>
</div>
</body>
</html>

Fotiman

1:57 pm on Aug 6, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Your data is getting sent. Here is what happens in the example above:

1. The page loads initially, and the value of $_POST['fname'] and $_POST['lname'] are blank, as nothing has been posted yet. As expected.

2. When the user clicks the submit button, you are sending an AJAX request to the server, posting those values. The values are received correctly, and if you were to view the data returned (in the success method) you would see a copy of the page where the fname and lname values were written to the page. However, that is not the same page that is currently being viewed, which is why the fname and lname values remain unchanged.

If you change your success function, you can see that it is working:


success: function (data) {
alert(data);
}


I suspect what you'd want to do is use JavaScript to update those values on the current page, so you could do something like this.

1. Modify your PHP to output some markup around the values you'll need to change:

<?php
echo 'fname:<span id="postedfname">' . $_POST['fname'] . '</span><br/>';
echo 'lname:<span id="postedlname">' . $_POST['lname'] . '</span>';
?>


2. In your success method:

success: function() {
$('#postedfname').html(fname);
$('#postedlname').html(lname);
$('form#submit').hide(function(){$('div.success').fadeIn();});
}


Hope that helps.