keewee279
keewee279

Reputation: 1654

jQuery / Ajax: How to access values from result array

I use the following Ajax call to fetch translations from a db.
The call itself works and returns the below result.

Can someone tell me how I can access the values from the array in the Ajax result so that I can assign them to my variables ? I either get an error or empty variables and couldn't find a way to make this work (I am new to arrays).

Note: The id in this case is a unique identifier so the Ajax call always returns only one row.

Ajax call:

$.ajax({
    type: 'POST',
    url: 'fetchTrans.php',
    data: {
        transId: transId
    },
    success: function(result){                  
        var transDE = ''; // should be result['de']
        var transEN = ''; // should be result['en']
        var transDA = ''; // should be result['da']
        var transES = ''; // should be result['es']
        var transFR = ''; // should be result['fr']
        var updateDate = ''; // should be result['updateDate']
        
        $('#transId').val(transId);
        $('#langDE').val(transDE);
        $('#langEN').val(transEN);
        $('#langDA').val(transDA);
        $('#langES').val(transES);
        $('#langFR').val(transFR);
        $('#updateDate').val(updateDate);
    }
});

Ajax result (example):

array (
  'de' => 'Ziffer',
  'en' => 'digit',
  'da' => 'cifret',
  'es' => 'dígito',
  'fr' => 'chiffre',
  'updateDate' => '2020-05-09 19:40:58',
)

Upvotes: 0

Views: 229

Answers (1)

Lelio Faieta
Lelio Faieta

Reputation: 6669

What I'd do if I where you:

First encode the array as json in PHP:

echo json_encode($array);

so that you will end up with a JSON returned in the ajax call.

Then I'd change the AJAX accordingly (note that I add a JSON type not to rely on the jquery dataType autodetection:

$.ajax({
    type: 'POST',
    url: 'fetchTrans.php',
    dataType: 'JSON',
    data: {
        transId: transId
    },
    success: function(result){
        $('#transId').val(transId);
        $('#langDE').val(result.de);
        $('#langEN').val(result.en);
        $('#langDA').val(result.da);
        $('#langES').val(result.es);
        $('#langFR').val(result.fr);
        $('#updateDate').val(result.updateDate);
    }
});

Also, as you note I skipped assigning the result to variables. Unless you don't need those variable for something else in the response it is completely useless

Upvotes: 1

Related Questions