1

In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1.

VIEW:

<h4 class="qr-title" id="status"></h4> <script> var username = <?php echo(json_encode($username)); ?>; function checkAuthStatus() { setInterval(getStatus, 1000); } function getStatus() { var isAuth = <?php echo(json_encode($isAuth)); ?>; $.ajax({ url: '<?php echo base_url('auth/listen_auth'); ?>', type: 'post', data: {username:username}, success: function(data){ console.log(data); } }); document.getElementById("status").innerHTML = isAuth; } </script> 

here's the listen_auth() function in my CONTROLLER:

public function listen_auth(){ $username = $this->input->post('username'); $isApproved = $this->adminmodel->get_auth($username); if($isApproved == 1){ return 1; } else{ return 0; } } 

The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? Or is there any better way to do this?

1
  • what do you get in console.log(data) Commented Apr 24, 2017 at 10:54

2 Answers 2

1

The function from server 'listen_auth()' should print text not return.

public function listen_auth(){ $username = $this->input->post('username'); $isApproved = $this->adminmodel->get_auth($username); if($isApproved == 1){ echo 1; } else{ echo 0; } } 

And then get the answer from server in AJAX request:

<script> var username = <?php echo(json_encode($username)); ?>; function checkAuthStatus() { setInterval(getStatus, 1000); } function getStatus() { var isAuth = <?php echo(json_encode($isAuth)); ?>; $.ajax({ url: '<?php echo base_url('auth/listen_auth'); ?>', type: 'post', data: {username:username}, success: function(data){ document.getElementById("status").innerHTML = data; } }); } </script> 
Sign up to request clarification or add additional context in comments.

Comments

1

You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.