ajax callings to functions in the controller codeigniter - javascript

I am using codeigniter 3 and I am having a strange issue using ajax. I'm trying to call two ajax simultaneously and I thought I have problem with my ajax code and I asked this question here and nothing worked with me.
I kept making the code more simple and narrow it down until I discover that the problem seems to be with the codeigniter
Here is my js code:
do_download();
get_operation_status();
function get_operation_status() {
//var url_process_info = "http://www.example.com/public/sleep_status.php";// this url works as expected
var url_process_info = "<?php echo site_url(); ?>download/sleep_status";
$.ajax({
url: url_process_info,
dataType: 'json',
async: true,
method: "GET",
success: function (data) {
},
complete: function (){
get_operation_status();
}
});
}
function do_download(){
//var download_url = "http://www.example.com/public/sleep_download.php"; // this url works as expected
var download_url = "<?php echo site_url(); ?>download/sleep_download";
$.ajax({
url: download_url,
method: "POST",
async: true
});
}
My php code, inside the Download controller, I have these two functions just for testing :
public function sleep_status () {
sleep(1);
}
public function sleep_download(){
sleep (7);
}
Calling the ajax to the controller download, it showing the issue which keeps the second call pending until the first one is executed.
I created two php files and put them in /public/sleep_download.php and /public/sleep_status.php
and within the two files just the sleep line of code, and it works as I want, while the first call is running, the second ajax call has been excuted several times .
Edited: I could make it work by making the class not extending from CI_Controller, I created a new class named Action and I commented this part:
class Action /*extends CI_Controller*/ {
Although I could make it work, I still wonder why was it happening ? and is there a better solution ?

Related

Run php script inside JavaScript at regular intervals using ajax or any method

I have a index.php with a javascript function Loaddata()
function loaddata(){
<?php
$data = //connects to database and gives new data
?>
var data = <?php echo json_encode($data); ?>;
}
setInterval(loaddata,3000);
I understand the fact that php scripts can only be run once when the page is loaded and it cannot be run again using set interval method. Can someone please guide me how to run the php script at regular intervals inside my index.php using ajax or some other method. My javascript variable "data" depends upon the php script to gets its value. Thanks a lot
Generally, using ajax to get data from a PHP page on the front page is a good way. The way you write this code is fine, too. I suggest writing like this,
var data = <?php echo json_encode($data);?>;
function loaddata(){
// use data
}
setInterval(loaddata,3000);
I think it is more clear
You could use an ajax call to retrive data from php and call that function in setInterval function something like this.
function demofunc()
{
$.ajax({
url: '<?php echo base_url();?>',
type: 'POST',
data: formdata,
dataType: 'json',
success: function(data) {
// do your thing
}
});
}
setInterval(demofunc,3000);
If anyone wondering how to do it.
Echo the PHP value that you want ajax to get for you.
Do an ajax request to the php page to get the data.
$.ajax({
method: 'get',
url: 'time.php',
data: {
'ajax': true
},
success: function(data) {
console.log(data)
}
});
// Second Method
$.get('time.php',function(data){
console.log(data);
});
PHP file
if ($_GET['ajax']) {
echo "HELOOO";
}
//if using the 2nd method just echo
echo "hi second method";

Parsing Javascript variable to AS3

I'm trying to write a simple 2 way chat but got a problem. I'm sure it's very basic but couldn't figure out since I'm new to this.
Below is my JS code to pass a streamID to AS3:
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: 'action=sd_chat_code&chat_code='+chat_code,
success: function(data){
object.streamCompanion(data);
},
error: function(data) {
console.log(data);
}
});
and in AS file, I got the streamID passed through as below:
public function streamCompanion(data):void {
var netStreamObj:NetStream = new NetStream(_nc);
netStreamObj.play(data);
_client.attachNetStream(netStreamObj);
}
Here's my code so you can check https://codepen.io/adamboy_1802/pen/MpqyML
The variable data above returns "12345" correctly. I tried to output is via JS and there's nothing wrong:
ExternalInterface.call("function() { console.log("+data+") }")
Any advice would be greatly appreciated.
(Solved)
So after trying to create a text box and output the variable data in Flash instead of alert it out via jQuery, the problem relied in my ajax call, where I use echo json_encode(my_var), simply change it to echo my_var fixed the problem.

returning value from js method with ajax call to REST service

What I am trying to do is call a js method that uses ajax to call a REST service and then return that response to the original call. Sounds simple enough, but I haven’t been able to find a sufficient answer here on SO to get it to work.
If async is true, I get undefined. If I set async to false, it works, but it is holding up the loading of the page. I have tried several attempts with different examples of using promises and callbacks, but just haven’t been able to figure it out. I know that there is something very basic I am missing, or concept I am failing to grasp.
In this example, I am wanting to check if an item is on a persons watch list for an auction. If it is, then it will set the icon class to active so it will change the icon color and they can see that it is on their watch list. If it is not, it remains greyed out.
Each page will have a few things like this example.
Page1.php
jQuery(document).ready(function($){
var w = mgapp.checkWatchlist($id, localStorage.u_pcjid);
if(!w.error){
$("#watchlist").removeClass('watchlist').addClass('watchlist-active');
}
});
The method is on the script.js page. The data returned from the ajax call is a JSON object.
NOTE: async is currently set to false just to get it to work.
script.js
var mgapp = {
checkWatchlist: function($iid, $uid) {
var $msg;
$.ajax({
url: 'https://somedomain/api/v1/watchlist/item/' + $iid + '/' + $uid,
type: "GET",
headers: {"Authorization": localStorage.u_apikey},
contentType: 'application/json',
async: false
})
.done(function(data){
$msg = data;
})
.fail(function(data){
$msg = data;
});
return $msg;
}
}
I am sure I will need to have a callback function or something, but none of the attempts I have made with those have worked.
Just to clarify. All the code is working as is, it is just not working asynchronously. What I am wanting is to have async set to true so that i am making an actual asynchronous call so that this is not holding up the loading of the page. I need the value returned from the ajax call available to the var on Page1.php.
Thanks in advance.
If figured it out.
var w = mgapp.checkWatchlist($id, localStorage.u_pcjid).done(function() {
if(!w.responseJSON.error){
$("#watchlist").removeClass('watchlist').addClass('watchlist-active');
}
})
checkWatchlist: function($iid, $uid) {
return $.ajax({
url: 'https://somedomain.c9.io/api/v1/watchlist/item/' + $iid + '/' + $uid,
type: "GET",
headers: {"Authorization": localStorage.u_apikey},
contentType: 'application/json'
})
},

Read Data from text file on server using $.ajax to call a php script

This is my first time posting on this site. I have looked over several of the previous postings related to this topic, but did not find anything that works for me. I am trying to use javascript and jquery $.ajax to call a php script on the server and return the contents of the file. Thus far I am not getting any data back. I am able to update the .txt file on the server using the $.ajax, but could use some help in finding out what I am doing wrong to retrieve it. I do not see any errors being generated from the php script and the events.txt file is not blank. vb.net and c# are my native languages so this is a bit foreign to me.
My js is:
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'get',
dataType: 'text',
success: function (data) {
result = data;
alert(result);
},
async: false
});
}
and my readdata.php script is:
<?
$file=fopen("events.txt","r");
$read=fread($file,filesize("events.txt"));
fclose($file);
echo $read;
?>
Any advise is welcome. Thanks!
The type in $.ajax should be in capitals
type: 'GET'
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'GET',
dataType: 'text',
success: function (data) {
result = data;
console.info(result);
},
async: false
});
}
After adding the error: function(){} to the ajax call, I was able to work through this issue.
It turned out that part of the issue was permissions on the server (not able to read from file in the file permissions on the server).
Also I was trying to run locally and I did not have php installed on my local machine.

Loading XML into JS variable with jQuery without JS alert

I know questions about loading XML into a JS variable have been posted here many times, but I didn't find a solution that would work. In my script I declare a variable before an ajax request, and then add the result to the variable. This works only if I add alert to the script:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
myDB = xml;
}
});
alert(myDB); //returns: undefined
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
alert(question);
});
The above code works only with the alert. When I delete the alert, the code doesn't work. How can I make this work without the alert?
You need to add your code to success handler for doing that:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
});
}
});
An ajax request is asynchronous. That means, the function you gave in the success option is excuted somwhen later.
After you've started the request, you're variable is still empty. Only if you wait long enough to confirm the blocking alert, the variable will have been loaded.
You will need to add the iteration to the success function, where the xml data is certainly available.

Categories