calling a php function using ajax after interval o

2019-03-01 06:25发布

问题:

hi i am working on a codeigniter project. I want to execute a php function after an interval of 10seconds. When a user visits that specific page after 10 seconds i want that php function to be executed. In that php function i have set a counter which adds 1 to the specific table into the database. I have tried using AJAX but didnt get the desired result. Kindly explain me with examples as i am new in ajax. Thanks in advance...

回答1:

@Majid Golshadi s answer is the right answer.

Working version is here

Please in view that is loaded all the time (like header_view.php)

add this few lines

<script type="text/javascript">
        var _baseUrl = "<?= base_url() ?>";
</script>

This makes that your base_url is usable in JavaScript anywhere in page (but make sure to have it somewhere on "TOP" of page)

and literraly use @Majid Golshadi s answer in this way

$(document).ready(function() {
    setTimeout(function() {
        $.ajax({
        url: _baseUrl + "/your/controller/param",    
        type: 'post',    
        data: {"token": "your_token"}, });   
    }, 10000);
});


回答2:

using jquery this will be the easiest and fastest way to do that

`//setting timeout to 3 seconds = 3 thousand milli seconds

 setInterval(function(){
     //ajax call
      $.ajax({
         url: _baseUrl + "/controller_name/function_name/",   //the url where you want to fetch the data 
         type: 'post', //type of request POST or GET    
         data: {"data": "value"}, }); //data passed to controller
 },3000);`

in your controller you may use

function function_name(){
    $var = $this->input->post();//getting data passed from ajax
    //process here...
    echo json_encode($var)//parses and returns the processed value
 }


回答3:

try this

setTimeout(function(){
    $.ajax({
    url: "<?php echo base_url('your/controller/address');?>",
   type: 'post',
   data: {"token": "your_token"},
});

}, 10000);

Example

in your view

$(document).ready(function(){

setTimeout(function(){
    $.ajax({
    url: "<?php echo base_url('MyController/Mymethod');?>",
   type: 'post',
   data: {"token": "12majid18"},
 });

 }, 10000);

});

and in Your Controller write method like this

public function Mymethod()
{
   $token = $this->input->post('token');

   if ( $token == '12majid18' )
     {
        /*call your model and insert your data in Table*/
     }
 }


回答4:

you can try this:

window.jQuery(function(){
var y=setInterval(function() {
        window.jQuery.post(url,{"token": "your_token"},function(res){
        alert(res);
   });   
 }, 10000);
});