Here is a solution I'm using - The issue is explained below.
I don't understand why .getJSON()
is failing. I am compensating by using .post()
which comes back as a String instead of the JSON.
$.post('test.php', { action: 'test' }, function(data, status){
console.log(jQuery.parseJSON(data)); //form the JSON from a string after the POST
});
It works fine for now but puts more stress on the browser and end-user. It might actually be better this way for large-scale deployment to save a little bit of server CPU? Anyways. Strange little bug.
I used this previous answer to get started with what I'm doing: using jquery $.ajax to call a PHP function
and double checked my basic usage against: http://api.jquery.com/jQuery.getJSON/ and http://api.jquery.com/jQuery.post/
I have complete success with $.post but when using $.getJSON there isn't even a status returned ..
For clarification: I'm editing these functions to ask the question. I'm testing with usable json data that I've already been handling I'm just adding the ability to call php functions through ajax requests. Don't be thrown off with my strange php echo json_encode. My working data is validated.
Anyways, here is the .js:
$.post('test.php', { action:'test' }, function(data, status){
console.log(data); //{"test_result":"success"}
console.log(status); //success
});
$.getJSON('test.php', { action:'test' }, function(data, status){
console.log(data); //nothing
console.log(status); //nothing
}).fail(function( jqxhr, textStatus, error ) {
console.log(textStatus); //parsererror
console.log(error); //SyntaxError: Unexpected end of input
});
and my .php:
<?php
try {
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test':
echo json_encode(array('test_result' => 'success'));
break;
}
}
} catch(Exception $e) {
echo "ERROR: " . $e->getMessage();
}
?>
This successfully executes as a $.post but when I switch to $.getJSON it no longer functions. Is there a simple reason why?