Home > Software design >  how to get data realtime with ajax?
how to get data realtime with ajax?

Time:12-04

what if I want to send data to the getDataDashboard function using ajax type post, so that the data can be returned realtime without using button clicks. in function getDataDashboard I want to put data that has been passed using ajax in variable $filter

this is sample code in function getDataDashboard :

code image

public function getDataDashboard(Request $request){
    
        $filter = 3;

        $priode = Lowongan::select('id_lowongan',\DB::raw("DATE_FORMAT(start_priode, '%d %M %Y') as tgl"))->latest()->take($filter)->pluck('tgl');

        $low = Lowongan::latest()->take($filter)->get();

    return view('r-admin.dashboard.IndexDashboard', compact('priode','low');
}

code in blade page :

<form action="">
   <select name="selectPriode" id="selectPriode" >
      <option value="3">3 Priode Terakhir</option>
      <option value="6">6 Priode Terakhir</option>
      <option value="10">10 Priode Terakhir</option>
    </select>
</form>

please help me to write the ajax code so that the function can run

CodePudding user response:

@Mas Raff You can use websockets which is a real time technology. Using Ajax as @Kokodoko said, you need to write a javascript fetch for request to a PHP file.

Here something for reference.

Javascript Function :

function getSomeData(){
    var data_to_send = "123";

    var action='actionNameX';
    $.ajax({
        url:    'ajax_file.php',
        type:   "POST",
        async:  true,
        data: {action:action,data_name:data_to_send},
        success: function (response) {
            var data_rcv = $.parseJSON(response);
            // do something $('#element').val(data_rcv);
        }
    });
  
    setTimeout( getSomeData, 2000 ); //ms, for automatic updating function
}

PHP Server side, ajax_file.php:

if ($_POST['action'] == 'actionNameX'){
    $data_name_rcv = $_POST['data_name'];
    // doing something with $data_name_rcv
    // update some data *** -> $specific_data

    if ($everything_ok > 0){
        // response to AJAX
        echo json_encode($specific_data,JSON_UNESCAPED_UNICODE);
        exit;
    }
    echo 0; // error 
    exit;
}
  • Related