Gabrielle-M
Gabrielle-M

Reputation: 1077

How to execute a join query by an AJAX request

I have a drop-down list, from this list I have to send an ajax request to the database and I have run a join query over the request. However, when I check my response using alert() it only shows [object][Object].

Here is my AJAX request.

$(document).ready(function(){
    $('#client_id').on('change',function(){
        var id=$(this).val();
  //alert(id);
        $.ajax({
            url:"{{route('getcheque')}}",
            method:'post',
            data:{
              id: id,
              '_token':"{{csrf_token()}}"
            },
            success:function(response)
            {
                //console.log(response);
                alert(response);
            }
        });

    });
    //end client part

});

and here is my ajax request method.

public function get_cheque(Request $request)
{
    $id=$request->id;
    $cdata=DB::table('directcheques')
            ->join('clients', 'directcheques.client_id', '=', 'clients.id')
            ->join('banks', 'directcheques.bank_id', '=', 'banks.id')
            ->select('directcheques.*', 'clients.*', 'banks.*')
            ->where('directcheques.id',$id)
            ->get();

    return $cdata;
}

Upvotes: 1

Views: 1872

Answers (2)

nithinTa
nithinTa

Reputation: 1642

Your response is an array calling response[0].branch_name might work. If you are having multiple records then you need to iterate using for each

If it is laravel and your expected response contain only one record , instead of get() use following, then you can call response.branch_name

$cdata=DB::table('directcheques')
        ->join('clients', 'directcheques.client_id', '=', 'clients.id')
        ->join('banks', 'directcheques.bank_id', '=', 'banks.id')
        ->select('directcheques.*', 'clients.*', 'banks.*')
        ->where('directcheques.id',$id)
        ->first(); //change to first only if you need one record.

Upvotes: 1

Casper
Casper

Reputation: 1539

This is the expected behavior, return only works if you are using the returned value with another php function.

When using Ajax you should use echo/print instead of return.

like below,

public function get_cheque(Request $request)
{
    $id=$request->id;
    $cdata=DB::table('directcheques')
            ->join('clients', 'directcheques.client_id', '=', 'clients.id')
            ->join('banks', 'directcheques.bank_id', '=', 'banks.id')
            ->select('directcheques.*', 'clients.*', 'banks.*')
            ->where('directcheques.id',$id)
            ->get();

    echo json_encode($cdata);
}

In your Ajax parse JSON,

var data = JSON.parse(response);

Upvotes: 0

Related Questions