calling a php function using ajax after interval of time - php

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...

#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);
});

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
}

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*/
}
}

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

Related

Get mysql table data one by one

I want to retrive mysql table data one by one.
data1
// wait 5 sec
data2
// wait 5 sec
Like this is there any way I can do That in php ?
Add sleep() to your loop to wait and pass seconds like sleep(5) how many seconds to wait.
Please use this code.
<script type="application/javascript">
function getData()
{
$.ajax({
method: "POST",
url: "getData.php",
data: { testParam: "1"}
}).done(function( msg ) {
$("#data").append(msg);
});
}
var myVar = setInterval(function(){ getData() }, 5000);
</script>
this code added in getData.php
function myfunction(){ echo "Hello, Nice to meet You";}
echo myfunction();
In this case you can use jQuery Ajax and create a function which call each 5 seconds:
<script>
function getData()
{
$.ajax({
method: "POST",
url: "getData.php",
data: { testParam: "1"}
}).done(function( msg ) {
$("#data").append(msg);
});
}
setInterval(getData(), 5000);
</script>
and you need an div which show data
<div id="data"></div>
and a php file which we named getData.php which provide data
<?php
echo '<div>Data</div>';
?>

How to use ajax to pass a variable to a php file using POST method?

I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});

jQuery Ajax load data from database but doesn't display it

I have two files. One PHP-file, which contains a SQL-Select statement and returns the output as html. The second file is my index file which contains a div with the class "loadMembers" and some jquery code:
$(document).ready(function () {
function startInterval() {
var refreshId = setInterval(function () {
$.ajax({
url: 'sidebars/members.php',
type: 'html',
success: function (resp) {
$("div.loadMembers").html(resp);
}
});
}, 5000);
}
startInterval();
});
I want to refresh the div with database data in a 5 seconds interval. I tried it also with .load()...
The request contains some data but nothing from my database...
Where's the problem?
Thanks for any help :)
your request type can be get or post, not html, it should be dataType
url : 'sidebars/members.php',
type: 'POST', // or GET
dataType : 'html',

jscrollPane disappear when continuously Ajax GET

PROBLEM SOLVED
updated the jscrollpane to the latest version which support jquery 1.8 !
https://github.com/vitch/jScrollPane/blob/master/script/jquery.jscrollpane.min.js
I'm trying to refresh a div with content for a certain period. It will fire an Ajax GET call to a php script which render the content. For the first time ajax GET called, the ScrollPane is there, but for the second time Ajax GET(refresh) JScrollPane disappeared. Any how to reinitialize the jscrollpane?
function getActivity(callback)
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
var api = $('#activityLineHolder').jScrollPane(
{
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
}
).data('jsp');
api.getContentPane().html(data);
api.reinitialise();
}
});
setTimeout(callback,10000);
}
$(document).ready(function(){
(function getActivitysTimeoutFunction(){
getActivity(getActivitysTimeoutFunction);
})();
});
Right now, my scrollpane is there after every Ajax call, but it shows buggy, the jscrollpane will keep moving left after every Ajax Call and slowly, it will hide the content. How is this happened?
foreach ($list as $notification) {
echo "<div class='feeds' id='$notification->notification_id'>";
$userObj = $user->show($notification->added_by);
echo $userObj->first_name.":<span class='text'>".$notification->activity."</span>";
echo " <span class='time'>".$notification_obj->nicetime($notification->created_at)."</span>";
echo "</div>";
}
something like this , that is my activity.php
here is my screenshot , anyone pls do help me #_#
http://img31.imageshack.us/img31/6871/jscrollpane.png
change the order of your commands. make a global variable that caches the ID like this:
var $activity, $activity_pane; // outside the dom ready
function getActivity(callback){
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
success: function(data) {
$activity_pane.html(data);
}
});
setTimeout(callback,10000);
}
$(function(){
$activity = $('#activityLineHolder');
$activity.jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
autoReinitialise: true
});
$activity_pane = $activity.data('jsp').getContentPane();
(function getActivitysTimeoutFunction(){
getActivity(getActivitysTimeoutFunction);
})();
});
My understanding is that a callback should be executed when the code within your method completes. If you are then wanting to run the getActivity() method again, shouldn't that be used in setTimeout(). Something like this:
function getActivity(callback)
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
$('#activityLineHolder').html(data);
}
});
setTimeout(function(){getActivity(callback);},10000);
if($.isFunction(callback)) {
callback();
}
}
I just take a look at http://jscrollpane.kelvinluck.com/ajax.html
I had tried and works. i change setTimeout into setInterval (function from scrollpane).
you can try this (i had tested)
$(document).ready(function(){
var api = $('#activityLineHolder').jScrollPane(
{
showArrows:true,
maintainPosition: false,
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12,
autoReinitialise: true
}
).data('jsp');
setInterval(
function()
{
$.ajax({
url: '../../views/main/activity.php',
success: function(data) {
api.getContentPane().html(data);
}
});
},
10000
);
});
I've faced this problem before, here is a snippet so you can get the idea. Good luck!
attachScroll = function(){
return $('.scroll-pane').jScrollPane({
verticalDragMinHeight: 17,
verticalDragMaxHeight: 17,
showArrows: true,
maintainPosition: false
});
}; // in this var I store all settings related to jScrollPane
var api = attachScroll().data('jsp');
$ajaxObj = $.ajax({
type: "GET", //set get or post
url: YOUR_URL,
data: null,
cache: false, //make sure you get fresh data
async: false, //very important!
beforeSend: function(){
},
success: function(){
},
complete: function(){
}
}).responseText; //$ajaxObj get the data from Ajax and store it
api.getContentPane().html($ajaxObj); //insert $ajaxObj data into "api" pane previously defined.
api.reinitialise(); //redraw jScrollPane
You can define the ajax call as a function and put it into a setInterval.
An example from official docs can be found here
Hope it helps!
Well I suppose that your HTML content coming from AJAX is long and you have problem with decreasing area size because it takes some time to render content by .html():
api.getContentPane().html(data);
And when it goes to the next line api.reinitialise() - HTML rendering isn't complete yet, but jScrollPane already catches current DIV width / height, initializes by those width / height, and then remaining html content is being inserted - and it appears outside of jScrollPane boundaries.
Read similar question: Wait for jquery .html method to finish rendering
So my adice:
1) Add a DIV at the end of your PHP code which will mark end of HTML coming from Ajax:
foreach ($list as $notification) {
...
}
echo '<div id="end-of-ajax"></div>';
2) Add periodical (200ms) check for "end-of-ajax" in your JS code - when it finds the end is reached, it calls for api.reinitialise():
var timer = setInterval(function(){
if ($("#activityLineHolder").find('#end-of-ajax').length) {
api.reinitialise();
clearInterval(timer);
}
}, 200);
EDIT
This is full JavaScript code:
function getActivity()
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
var api = $('#activityLineHolder').jScrollPane(
{verticalDragMinHeight: 12,verticalDragMaxHeight: 12}
).data('jsp');
api.getContentPane().html(data);
var timer = setInterval(function(){
if ($("#activityLineHolder").find('#end-of-ajax').length) {
api.reinitialise();
clearInterval(timer);
}
}, 200);
}
});
}
$(document).ready(function(){
setInterval(getActivity,10000);
});
Im not sure about what your content is but just make sure that you reset the widths and heights accordingly before reinitlizing. as i had the same issue, and that was the problem
var origHeight =$('#GnattChartContainerClip').height();
var GanttChart = $('#EntireGnattWrapper').get(0).GanttChart;
$('#GnattChartContainerClip').find('#PaddingGnatt').remove();
$('#HeadersCol').find('#PaddingHeaders').remove();
var pane = $('#GnattChartContainerClip');
$('#GnattChartContainerClip').height(origHeight+height);
$('#GnattChartContainerClip').append('<div id="PaddingGnatt" style="width:'+GanttChart.TotalWidth+'px;height:25px"></div>');
$('#HeadersCol').append('<div id="PaddingHeaders" class="header" style="height:25px"></div>');
var paned = pane.data('jsp');
paned.reinitialise();

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories