Call Controller function from jQuery - javascript

I'm working on some codes. Here's my code
jQuery
duration = 30;
var countdown = setInterval(timer,1000);
var url = window.location.origin + '/pro/index.php/Test';
function timer(){
duration = duration - 1;
if(duration<=0){
clearInterval(countdown);
window.location(url+'/next');
}
}
I want to redirect and run function in Test/next. In next() method, it will rule where the link should go. url helper also has been added automatically in Loader
Controller
public $num;
public $val;
public function index(){
// get the value from GET method
$this->num = $this->input->get('num');
$this->val = $this->input->get('val');
}
public function next(){
$x = $this->num;
$x = $x + 1;
if($x < 4){
redirect(site_url('index.php/Test?x='.$x/.'&num='.$this->num));
}
else{
// it will redirect to another page
// redirect(site_url('index.php/Home'));
echo 'x = '.$x.', num = '.$this->num;
}
(The codes above have been simplified).
The method has been run, but the url was localhost/pro/index.php/Test/next and echo-ing :
x = , num =
It seems like the global property doesn't work for the function called from JS/jQuery. Any explanation or solution for this?

You need ajax calling.
In your View file
<button class="call_ajax" name="submit">Call Ajax</button>
<script type="text/javascript">
$('.call_ajax').click(function(){
var value1 = 'some data';
var value2 = 'some data';
$.ajax({
url: '<?php echo site_url('your_controller/your_function'); ?>',
type: 'POST',
data: {
key1: value1,
key2: value2
},
dataType: 'json',
success: function(url) {
window.location.href = url;
}
});
});</script>
in your Controller
your_function(){
$data1 = $this->input->post('key1');
$data2 = $this->input->post('key2');
// do Data Processing
// For return some data ;
echo "https://some-webiste-url/";
// FOR Array
echo json_encode($any_data_array);
}
NOTE : controller Function called from ajax will not do redirection . If you want to direct to some other url , you have to do that in the Javascript Section Using

Related

Laravel - Java script - Unable to load a page from web route url in ajax call

I'm passing a parameter in side the $ajax call to link with controller function.
abc.blade.php
inside onClick listener---
$.ajax({
url: "{{route('getFordHedGpsLocationForSelectedRep')}}",
type: "GET",
dataType:"json",
data: {repc:repCode.trim()},
success: function (data)
{
alert("OK");
}
});
web.php
Route::get('getFordHedGpsLocationForSelectedRep', 'MapController#getFordHedGpsLocationForSelectedRep')->name('getFordHedGpsLocationForSelectedRep');
MapController.php
public function getFordHedGpsLocationForSelectedRep(Request $request)
{
$repCode = $request->get("repc");
$result = DB::select('select query to get data');
$temp = array();
$output = array();
$output1 = array();
foreach ($result as $key => $value)
{
if (trim($value->RepCode) == $repCode)
{
$temp['lat'] = $value->Latitude;
$temp['lng'] = $value->Longitude;
$temp['ref'] = $value->RefNo;
$temp['sTime'] = $value->startTimeSO;
$temp['eTime'] = $value->endTimeSO;
$temp['repCode'] = $value->RepCode;
$temp['debCode'] = $value->DebCode;
$temp['tAmt'] = $value->TotalAmt;
$temp['outDis'] = $value->OutDisVal;
$temp['debName'] = $value->DebName;
$temp['repName'] = $value->RepName;
$temp['qty'] = $value->Qty;
$temp['tDate'] = $value->TxnDate;
}
$output = isset($temp)?$temp:'';
}
$output1 = isset($output)?$output:'';
return view('selectedRepMap')->with(['repOrders'=> $output1]);
}
That controller function returns a view (selectedRepMap.balde.php) with view loading data. Unfortunately page not loading automatically after the click event on abc.blade, but inspect network status got '200' for 'getFordHedGpsLocationForSelectedRep' function ($ajax call url) and double click on that function in inspect network area page loading successfully.
Updated code
public function getFordHedGpsLocationForSelectedRep(Request $request)
{
$repCode = $request->get("repc");
$result = DB::select('select query for data');
$output1 = isset($result)?$result:'';
return $output1;
}
abc.blade.php
$.ajax({
url: "{{route('getFordHedGpsLocationForSelectedRep')}}",
type: "GET",
dataType:"json",
data: {repc:repCode.trim()},
success: function (data)
{
var repOrders = {data};
var a = JSON.stringify(data);
console.log(a);
window.location = '/selectedRepMap?repOrders='+ a;
}
});
newPage.blade.php
var url_string = window.location.href;
var url = new URL(url_string);
var repOrders = url.searchParams.get("repOrders");
var orders = JSON.parse(repOrders);
console.log(orders['value']);

CodeIgniter - getting data from database automatically using setInterval

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?
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>
You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.

Automatic run a JavaScript when there is a new data get by Ajax

Now I have two javascript, one is I called auto_refresh.js which I use ajax to continuously get new data from mysql database (This part is done).
auto_refresh.js
var mainDisplayCacheData;
var mainDisplayData = $('.aside').html();
var auto_refresh = setInterval(
function()
{
$.ajax({
url: 'main_display.php',
type: 'POST',
data: mainDisplayData,
dataType: 'html',
success: function(mainDisplayData){
if(mainDisplayData !== mainDisplayCacheData){
mainDisplayCacheData = mainDisplayData;
$('.aside').html(mainDisplayData);
}
}
})
}, 1000);
display.php
<div class="aside">
<?php
$tm = TicketManager::getInstance();
$tm->displayMainTicket();
$ticket = $tm->mainTicketSound();
?>
</div>
ticketmanaget.inc
public function mainTicketSound()
{
$conn = DBManager::getConnection();
$query = "SELECT queue_id, ticket_name FROM queue
WHERE DATE(response_time) = DATE(NOW())
ORDER BY response_time DESC
LIMIT 1
";
$results = #$conn->query($query);
if ($results === FALSE or $results === NULL)
throw new DatabaseErrorException($conn->error);
if ($results->num_rows < 1)
{
$results->close();
}
else
{
while($rows = #$results->fetch_array())
{
$ticketname = $rows['ticket_name'];
return $ticketname;
}
}
}
audio function
var input = "<?php echo $ticket; ?>";
var files = ["0.mp3", "1.mp3",
"2.mp3", "3.mp3",
"4.mp3", "5.mp3",
"6.mp3", "7.mp3",
"8.mp3", "9.mp3"];
var audio = document.createElement("audio");
var audioIdx = 0;
var playById = function (id) {
audio.src = files[input[id]];
audio.play();
};
audio.addEventListener('ended', function () {
audioIdx++;
if (audioIdx >= files.length) audioIdx = 0;
playById(audioIdx);
});
audio.src = files[input[audioIdx]];
audio.play();
Then I have another script which is used to play audio files. Exactly which files to play is based on the new data get by ajax from database. In my case, I want my second script run the files based on the variable $ticket.
The audio script is done and run perfectly. However, it only play the sound when I refresh the page. I need it to run automatically when the auto_refresh.js get new data. Please help, thanks.
This might help "big picture".
Note that the code in display.php only runs one time - when page initially loads. You need that code to run each time new data is received.
Therefore, you must create a new php file that accepts via POST the new data, and returns (via echo not return) the desired $ticket value. Call this page as an AJAX call inside the success function of the first AJAX call. Something like this:
auto_refresh.js
var mainDisplayCacheData;
var mainDisplayData = $('.aside').html();
var auto_refresh = setInterval(
function(){
$.ajax({
url: 'main_display.php',
type: 'POST',
data: mainDisplayData,
dataType: 'html',
success: function(mainDisplayData){
if(mainDisplayData !== mainDisplayCacheData){
mainDisplayCacheData = mainDisplayData;
$('.aside').html(mainDisplayData);
$.ajax({
url: 'new_php_file.php',
type: 'post',
data: mainDisplayData,
success: function(axData){
var files = ["0.mp3", "1.mp3",
"2.mp3", "3.mp3",
"4.mp3", "5.mp3",
"6.mp3", "7.mp3",
"8.mp3", "9.mp3"];
//below element already exists. You should update it rather than creating another
var audio = document.createElement("audio");
var audioIdx = 0;
var playById = function (id) {
audio.src = files[axData[id]]; //axData returned by AJAX
audio.play();
};
audio.addEventListener('ended', function () {
audioIdx++;
if (audioIdx >= files.length) audioIdx = 0;
playById(audioIdx);
});
audio.src = files[input[audioIdx]];
audio.play();
}
});
}
}
});
}, 1000);
new_php_file.php
<?php
$new_data = $_POST['mainDisplayData'];
//insert code required to run lines that follow, and/or modify as required
$tm = TicketManager::getInstance();
$tm->displayMainTicket();
$ticket = $tm->mainTicketSound();
echo $ticket;
Call the sound playing function in the other script in this block:
if(mainDisplayData !== mainDisplayCacheData){
// e.g. otherScriptFunction();
}
On the Server-side: You should echo the "$ticket" variable.
On the Client-side: Call your sound playing function inside the 'success' ajax callback:
if(mainDisplayData !== mainDisplayCacheData){
PLAY_SOUND(mainDisplayData);
}

How to do the ajax + json using zf2?

i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)

How do you input javascript variable into php script?

I'm trying to get a function called that calls a php function with an input.
javascript function (picNum is an integer):
function hello(picNum) {
var pictureNumber = picNum;
var phpFunc = "<?php
include 'otherfile.php';
otherFileFunc(" + pictureNumber + ") //This is where the problem is, the input(pictureNumber) wont go through
?>";
echo phpFunc;
}
otherfile.php
<?php
function otherFileFunc($i) {
$final = $i + 1;
echo $final;
}
?>
this code pretty much says if you do onclick="hello(1)" then the output or phpFunc should be 2 because you add one in the otherfile.php, but no matter the input the output is always 1 so I'm guessing the input at where I marked just isn't going through.
DONT TELL ME IT DOESNT WORK BECAUSE IT DOES.
if i put an integer instead of " + pictureNumber + " it works perfectly!
any help is appreciated :)
Unfortunately you won't be able to call php from javascript.
Php is run from the server and javascript is run on a client (usually, the exception being node.js. However even in the instance of node.js, php is not used as javascript has replaced its functionality)
If you need to have javascript "call" a server function you will need to look into ajax requests so that the server can then run a function and return it to the client.
You have to use Ajax bro:
Javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
PictureNumber = output_string['picturenumber'];
alert(PictureNumber);
}
});
}
PHP otherfile.php:
$picNum = $_POST['picNum'];
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = function($picNum);
$array = ('picturenumber' => $outputnumber);
echo json_encode($array);
Note: Untested
EDIT, tested:
javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
pictureNumber = output_string['picturenumber'];
alert(pictureNumber);
}
});
}
hello(1); //sample
PHP otherfile.php:
$picNum = $_POST['picNum'];
$picNum = 1;
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = otherFileFunc($picNum);
$array = array('picturenumber' => $outputnumber);
echo json_encode($array);

Categories

Resources