0

I am trying to get the currency from selected country name but ajax returns the value as undefined.

Ajax Code

$(document).on('change', '#country' ,function () {
        var prod_id=$(this).val();
        console.log(prod_id);
        var a=$(this).parent();
        var op="";
        $.ajax({
            type:'get',
            url:'{!!URL::to('searchCurrency')!!}',
            data:{'id':prod_id},
            dataType:'json',//return data will be json
            success:function(data){
                console.log(data.currency);
                    // here price is column name in products table data.coln name
                a.find('#currency').val(data.currency);
            },
            error:function(){}
        });
    });
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });

Code in controller

$currency=Currency::select('currency')->where('country','=',$request->id)->pluck('currency')->first();
return response()->json($currency);
Jaydeep Rajgor
  • 137
  • 1
  • 2
  • 12
  • you're passing `id` parameter in data segment of your `get` request, change the request data body to : `url: '{!!URL::to("searchCurrency")!!)?id='+prod_id`. I think this will fix your problem. – Arash Khajelou Jul 01 '19 at 13:35
  • for more about passing data in `get` request in jquery ajax visit this [question](https://stackoverflow.com/questions/15576548/how-to-pass-parameters-in-get-requests-with-jquery). – Arash Khajelou Jul 01 '19 at 13:37

1 Answers1

1

You should take a look at the request output in your development tools. The result of your query is a single string, so this is also what will be returned from your ajax request. There are no properties.

To get the currency, just use the data variable in your JavaScript:

success: function (data) {
    a.find('#currency').val(data);
},

The reason you get undefined as result is because String has no property currency.

Jerodev
  • 32,252
  • 11
  • 87
  • 108