Cross Cross - 2 months ago 8
Javascript Question

What is the proper way of using a javascript, jquery, ajax ? I am getting CPU reach limit on my site

Maybe i think this script (code snippet) below is causing me High server load make my site down as well as CPU reach limit. Is there a proper way to code the variables and arragement of this script?

One point here also, I am using here a SetTimeout(); because i REALLY NEED to get data from a JSON file from Codeigniter PHP and MYSQL every 2 seconds any other way to set this in proper way?, What can i do minimize my server load and avoid reaching the limit of the cpu of my web host?

<script>

var data1;
var data2;
var id = "1";
var url = '<?php echo base_url();?>index.php/site/get_products/';

products();

function products() {
$(document).ready(function () {
$.get(url + id, function (data) {
var obj = JSON.parse(data)
data1 = obj.product[0].data1;
data2 = obj.product[0].data2;
if (obj.product[0].data2 == "") {
document.getElementById("datap").innerHTML = "No data found";
} else {
document.getElementById("datap").innerHTML = data1 + data2;
}
});
});
setTimeout(products, 2000);
};


server side: (mycontroller.php)

public function get_product($id){
$this->db->select('*');
$this->db->from('product');
$this->db->where('id', $id);
$query = $this->db->get();
if($query->num_rows() > 0){
$data['product'] = $query->result();
}
echo json_encode($data);
}

Answer

There is no use of $(document).ready(function () {...} inside the locate function

Also you have place the setTimeout outside the function locate

function locate() {
  $.get(get_loc + v_id, function(data) {
    var obj = JSON.parse(data)
    longtitude = obj.vehicle[0].longtitude;
    latitude = obj.vehicle[0].latitude;
    if (obj.vehicle[0].longtitude == "") {
      document.getElementById("coordinates").innerHTML = "No coordinates found in the database";
    } else {
      document.getElementById("coordinates").innerHTML = "Longtitude: " + longtitude + "<br>Latitude: " + latitude + " ";
    }
  });
};
setTimeout(locate, 2000);
Comments