I have a HTML/JQuery frontend. I would like my HTML page to have a link, which when clicked posts data to a php file and decodes a JSON response which should be printed to the document window.
EDIT:
Here is my UPDATED HTML/JQuery Code based on @Kyle’s answer:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
a.test { font-weight: bold; }
</style>
</head>
<body>
<a href="">display message</a>
<script src="jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$(function(){
$("a").click(function(e){
e.preventDefault();
getmessage = "Yes";
getmessage = encodeURIComponent(getmessage);//url encodes data
$.ajax({
type: "POST",
url: "http://dev.speechlink.co.uk/David/test.php",
data: {'getmessage': getmessage},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
$("#message_ajax").html("<div class='successMessage'>" + json.message + "</div>");
}
});
});
});
});
</script>
<div id = "message_ajax"></div>
</body>
</html>
Here is test.php
<?php
if(isset($_POST['getmessage'])){
$dbh = connect();
$message = mysql_real_escape_string($_POST['message']);
$query = mysql_query("SELECT message FROM messages WHERE id = '46'") or die(json_encode(array('message' => "didn't query"));
if($query){
echo json_encode(array('message' => 'Successfully Submitted Data'));
}else{
echo json_encode(array('message' => 'Error Submitting Data'));
}
mysql_close();
}
?>
The back-end is setup fine…So I know the issue doesn’t lie there. I think it’s a syntax issue on my behalf but I cannot for the life of me get the div to display the response.I have tried for hours. I think one of the potential many problems is the fact that i’m not posting ‘getmessage’ correctly in my jQuery function…I’m a jQuery noob, which probably answers most of your questions…
EDIT:
With the above code, I manage to get the following written to the document window after the link is pressed:
[Object object]
My question is how do I get it to print the actual value within the JSON endoded PHP response..
Your dataString variable inside of your ajax request is empty. You never set it to anything inside of your code. Also, non-jQuery object don’t support the .serialize method. You should use the encodeURIComponent method for that.
Try this: