Reputation: 37
I am tryng to get AJAX to post to a seperate php file and then have that data put into a div. The ultimate goal will be to set up a long poll for auto updating, but baby steps.
So nothing shows up in the div when the page is loaded. I checked the console and the ajax does send the 'initiate' POST but it doesn't seem to receive anything back except headers.
FIXED whole time i was missing curly brackets. Thanks for all the syntax help guys.
here is the code
Php file that ajax calls
<?php
require "dbc.php";
$function = $_POST['function'];
switch($function)
case('initiate'):
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$mostrecent= mysql_fetch_array($request);
$mostrecentid = $mostrecent['id'];
header("Content-type: application/json");
echo json_encode($mostrecentid);
break;
case('update'):
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
header("Content-type: application/json");
echo json_encode($updateid);
break;
?>
The page where the call is made
<div id="datacheck"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: 'initiate'},
dataType: "json",
success: function(msg) {
$('#datacheck').html(msg);
}
});
}); // document ready
</script>
Upvotes: 0
Views: 103
Reputation: 572
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
you were missed ,
data: {function: 'initiate'},
datatype: "json",
Upvotes: 0
Reputation: 30488
You forgot ,
here
data: {function: 'initiate'}, // here
datatype: "json",
also
'function': 'initiate'
should be
function: 'initiate'
function is reserved word in javascript, so you need to change that to other name as well.
Upvotes: 4