EDIT: This works now, code updated. Big thanks to Martin Amps!
So I’ve been playing with this for a week now and have hacked together many examples but it hasn’t worked, so I won’t bother posting code since it’s a mess! I’m a jack of all trades, master of none, so I’m not sure where I’m going wrong.
Here’s what I need.
posttest.php
<html>
<head>
<script type="text/javascript" src="./js/jquery-1.7.2.min.js"></script>
</head>
<body>
<form name="processForm" id="processForm" action="process.php" method="POST">
<input type="text" id="textField" name="textField" />
<input type="hidden" id="sessionID" name="sessionID" value="myusername" />
<input type="submit" value="Process!" />
</form>
<div id="mydiv"></div>
FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>
FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>FILLER<BR><BR>
<script type="text/javascript">
$('#processForm').submit(function() {
var text = $('#textField').val();
var sid = $('#sessionID').val();
$.ajax({
url: "process.php",
type: "POST",
data: { 'text' : text, 'sessionID' : sid },
success: function(data) {
var result = $.parseJSON(data);
if (result.success) {
// Handle your result and update your form accordingly
// result.data.someKey
$('#mydiv').text('Success! With ' + result.data);
}
else {
// Error handling as applicable
}
}
});
return false;
});
</script>
</body>
</html>
process.php
<?php
$someText=$_POST['text'];
$return = array('success' => false,
'data' => $someText
);
if (isset($_POST['text'], $_POST['sessionID'])) {
// Do your queries
$return['success'] = true;
//$return['data'] = array('someKey' => 'someValue');
$return['data'] = $someText;
}
echo json_encode($return);
?>
I’ve tried so many examples, and tried making my own from scratch and can’t seem to get it to work! An example of what I’m trying to accomplish would be like when you add a comment on facebook, or a new post.
I hope someone can help out because I feel like I’ve already wasted a week here on this simple task.
Thanks in advance!
You don’t need to store the session variable in your page, as it’s stored in a cookie already. Assuming you’re using JQuery, here’s a quick sample:
The markup
The Javascript
process.php
Note
You should use absolute url’s and be aware the form/javascript is non obtrusive so you should make it function without ajax too.