Magento 2 Knockout JS – Bind Data from AJAX Response

knockoutjsmagento2

I want to bind image source to following div.

<div class="head_label"><img class="bank_photo" data-bind="attr:{src: bankImage}"></div>

Following is my ajax call and their is my variable which I want to bind to image src.

define(
[
    'jquery',
    'ko',
    'Magento_Checkout/js/view/payment/default',
    'Magento_Payment/js/view/payment/cc-form',     
    'Magento_Payment/js/model/credit-card-validation/validator',
    'mage/validation'           
],
function ($, ko, Component) {
    'use strict';

    var bankImage = '';

    return Component.extend({
        defaults: {
            template: 'Nitesh_Payment/payment/form',
            transactionResult: ''
        },
        ajaxCall: function(){
                $('#input-cc-number').blur(function(){
                    var cc = $(this).val();
                    var cc_length = cc.length;
                    if(cc_length>=6){
                        var data= {cc:cc}
                        $.ajax({
                            dataType: 'json',
                            url: url,
                            data: data,
                            type: 'post',
                            success: function(result)
                            {
                                var myObj = result;
                                this.bankImage = myObj.image;
                            },
                            error: function(){
                                alert("You Failed!");
                            }
                        });

                    }

                }); 
        },  

    });
}
);

Also I am unable to access bankImage variable inside Ajax call.
Please tell me how to access that variable in ajax function.

Best Answer

At first, add your variable to defaults object, and you will be able to set default value for field.

defaults: {
    bankImage : null
}

Define your variable as observable

/**
 * Initialize observable properties
 */
initObservable: function () {
    this._super()
        .observe('bankImage');

    return this;
},

And you need to define correct success handler with component context:

success: (function(result) {
    this.bankImage(result.image);
}).bind(this),
Related Topic