Hi,
I’m doing a jQuery Ajax request on a MODx table.
The purpose is to build a JSON array and later use its components to fill an HTML combo box (<select>)
{["id":1,"first_word":"Hello","second_word":"World"]
["id":2,"first_word":"Hi","second_word":"developers"]}
The request is like this:
$.ajax({
async: false,
url:'index.php?id=123',
type: 'POST',
dataType: 'json',
data: {company:'SomeCompany'},
timeout: 2000,
cache: false,
error: function(){
alert('Error.');
},
success: function(answer){
alert(answer);
}
});
The called document includes a snippet that does the database extraction.
I observed that if I’m using the ’json’ dataType, I must json_encode() the curly bracketed string before returning it, which is of course not necessary if using dataType:’text’.
As making a ’json’ request, I was expecting the alert box to display "[Object]".
But it displays the bracketed string.
I’m also unable to access individual array elements.
I expected being able to do something like: "alert(answer[0]);" and reach the first array element, but I observe that it extracts individual string bytes.
Does someone know the correct way to build a true JSON object with such Ajax request?
Thanks.
N.B. I’m obliged to use this rather complex technique as Opera is unable to handle <optgroup> returned by Ajax as html. For this reason, I have to get all data as JSON and programmatically build the <optgroup> using the data returned by the Ajax call.