PDA

View Full Version : Ajax Return Array



jdadwilson
03-11-2016, 06:27 AM
I have a problem with the Javascript processing of an Ajax returned array.

This is the code for the Ajax call:


var request;
var aaData;
// Initialize jQuery
$(document).ready(function() {
'use strict';

$('#table_FamilyPages').on('click', 'tbody tr', function() {
console.info( 'fam_ID: ' + oTable.row(this).cell(this, 1).data());
var famID = oTable.row(this).cell(this, 1).data();

request = $.ajax({
url: "files_ajax/ajax_FamilyPage_Single.php?fam_ID=" + famID,
dataType: "json"
});

// callback handler that will be called on success
request.done(function () {
$('#pages_remote').hide();
$('#pages_local').hide();

// Code here to display page info
var aaData = JSON.parse(request);
document.getElementById('idLongName').innerHTML = aaData.name_long;

$('#pages_family').show();
});

// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Inform user of the error and log to console for debugging
var errMessage = "The following error occured: " + textStatus + ' - # ' + errorThrown;
alert(errMessage);
console.error(errMessage);
});

// callback handler that will be called regardless if failed or succeeded
request.always(function () {
// reenable the inputs
});
});

});


The question is... What variables do I use in the JSON.parse(???) [see bold] function and then what do I use in the innerHTML line [see bold]?

Testing the code I receive an error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

Here is a sample of the encoded JSON array returned from the Ajax call.



{"sEcho":1,"iTotalRecords":100,"iTotalDisplayRecords":100,"aaData":[{"name_short":"SHORT NAME","name_long"
:"LONG NAME","submitter":"SUBMITTER","photo":"PHOTO","caption":"CAPTION","text":"TEXT"}]}


This is a link to my test page: http://www.txfannin.org/new-site/familypages.php

TIA for your assistance
jdadwilson

jscheuer1
03-11-2016, 07:04 PM
I don't see any bold. The error I'm getting is on this line:


var aaData = JSON.parse(request);

I don't think you want to be parsing the request object, that's the entire request. It looks like you're in luck though. The console gives up a request.responseJSON object that you should be able to have better luck working with in your code, by making the above code block:


var aaData = JSON.parse(request.responseJSON);

There may still be other errors, but at least you should be working with a valid JSON object. BTW, jQuery has its own JSON parsing function. In modern browsers, the native one you are using is probably fine, but if backward compatibility is of interest, you may want to use the jQuery one.