Reload only a <DIV> and php code with in that div - javascript

I have below code in a page called home.php.
<div class="Wrapper-notify" id="Wrapper-notify">
<?php echo rand(10,100); ?>
</div>
How can I reload only this div and the php code on regular time interval. (I'm using codeigniter framework) please help

PHP is evaluated on the server-side, so you will need to make a call to the server in order to re-evaluate the PHP expression. Considering that the only thing your PHP seems to be doing is generating a random number, and depending on what you're trying to accomplish overall, you might consider using Javascript to "refresh" the div, instead. You could do something like this:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function refreshDiv() {
var divObj = document.getElementById("Wrapper-notify");
var randNum = getRandomInt( 10 , 100 );
divObj.innerHTML = String( randNum );
}
setInterval( "refreshDiv()" , 2000 );
The above Javascript will change the number inside the div every 2 seconds.

You should first create a .php page, let's say test.php printing data like this :
<?php
echo rand(10,100);
?>
An you can use this code to load data from your page, this one is pure javascript
function getValue()
{
if (window.XMLHttpRequest)
AJAX=new XMLHttpRequest();
else
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX)
{
AJAX.open("GET", "test.php", false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send();
return AJAX.responseText;
}
else
return null;
}
window.onload=function()
{
setInterval(function(){
document.getElementById("Wrapper-notify").innerHTML = getValue();
},1000);
};
However, if you are using jQuery you can the use .get method to load data from server
$(document).ready( function()
{
setInterval(function(){ changeDiv(); },1000);
});
function changeDiv()
{
$.ajax({
url: "test.php",
success: function(result)
{
$("#Wrapper-notify").html(result);
}
});
}

You can use AJAX for this,
You define a function that will talk with your server to get data.
$('div #Wrapper-notify').load('http://yoursite.com #newContent');
Set time interval using function and call that in a regular time period like below.
setInterval( function() {
$('div #Wrapper-notify').load('http://yoursite.com #newContent');
}, 6000); // every 6000 milliseconds

I suppose you could do it with AJAX. Do a setInterval in Javascript that executes a function every x seconds. That function should call your PHP file via AJAX and pass the response to your DIV. The PHP file should just contain
<?php echo rand(10,100); ?>
This method is probably overkill for what you're probably aiming to achieve though.

I only see one simple solution, ajax call to a php in a time interval and just push the response into a container:
This is an example using jQuery:
setTimeout(function() {
$.get('/my/page', function(data) {
$('#my_container').html(data);
})
}, 3000);

If you just need random number between 10 and 100 , no need for php ... you need just some javascript : jsFiddle
window.onload=function()
{
setInterval(function(){
document.getElementById("Wrapper-notify").innerHTML = parseInt((Math.random()*100)+10);
},1000);
};
and if you're using some jQuery you can use this : jsFiddle
$(document).ready( function()
{
setInterval(function(){$("#Wrapper-notify").html(parseInt((Math.random()*100)+10))},1000);
});

You need to create new action, that will output only rand number from 10 to 100. Lets call it for example get_rand_num_action:
public function get_rand_num_action(){
return mr_rand(10,100);
}
In your view (where you have Wrapper-notify div), in the end of the or in tag create new ajax request to your get_rand_num_action
Gather data from get_rand_num_action response and update your Wrapper-notify div using native JS or jQuery:
function changeWrapperDiv(){
$.ajax('/controller/get_rand_num_action', {
success: function(response){
$("#Wrapper-notify").text(response);
}
});
}
// Change div every 5 seconds
setInterval(5000, changeWrapperDiv)
Hope this will help you.

Related

How to refresh specific div using Javascript/Jquery with the variables on it

I have a variable $salary which is dynamic. How can I refresh specific div every 5seconds.
index.html
<html>
<body>
<img src="<?php echo $filename.'.jpg'; ?>" />
<p id="salary"><?php echo $salary; ?></p>
</body>
</html>
Is there any javascript/jquery way to refresh #salary only. Please help..
You can execute an ajax call:
function ajaxCall() {
$.ajax({
method: 'POST',
url: 'path/to/asyncHalndler.php',
data: { ... },
success: function (data) {
if (data) {
$('#salary').html(data);
}
}
});
}
// Execute ajax call every 5 seconds
setInterval(function() {
ajaxCall();
},5000);
var salary = document.getElementById('salary');
Now, the value of your variable salary will be the DOM node where you would like to change the value. When you get new data, you can refresh text inside your p tag with salary id by adding salary.innerText = yourNewValue;
This is pure JavaScript way of updating that element with id.
It's better to use ajax way. But if u are looking for a very simple solution then jQuery .load will be the best
setInterval($("#salary").load("<url to get the value>"), 1000);
You will need an jquery ajax call for that.
first you should create php file get_salary.php where you send id from jquery ajax if you want to update the salary for unique id:
in get_salary.php you need to get salary from database so the code in this php file will be like that
$id = $_POST['ID']
$query = mysql_query("SELECT * FROM sallaries WHERE id='$id'") or die("Can't connect");
$fetch = mysql_fetch_array($query)
$salary = $fetch['salary']
echo $salary
after that you will need javascript file(e.g script.js) from where you will send the request and id to the get_salary.php and grab the data from it, after that you will be able to update salary in html, so code in javascript file will be like that:
function updateSalary(){}
var id=25;
$.ajax({
url: "get_salary.php",
type: 'POST',
//sending id
data:'id='+id,
success: function(result){
//updating html
$("#salary").html(result);
}
});
}
//setting interval to update in every second
setInterval(updateSalary, 1000)
so it will update your salary in the div

Show ajax process 1 by 1 when something is done

I have a code and it works, and it shows all notifications at the same time.
I have question..
How to get notifications when one of the functions is done? (Notifications appear one by one)
There are several functions in the indexing.php file.
$preproses = $_POST["preproses"];
if($preproses == "preproses"){
//mulai proses
set_time_limit(0);
buatindex();
hitungbobot();
panjangvektor();
}
function buatindex() {
code
}
function hitungbobot() {
code
}
function panjangvektor() {
code
}
In index.php there is a code to call that function
<script type="text/javascript">
function preproses(){
var preprosesx = "preproses";
$.ajax({
type : "POST",
url : "indexing.php",
data: {preproses:preprosesx},
error: function(){
$("#notif").prepend("fail");
},
success: function(html){
$("#notif").prepend("Process done <br/>"+html);
},
});
return false;
}
</script>
click to precess
If all processes are completed, a notification will appear
<span id="notif"></span>
$preproses = $_POST["preproses"];
if($preproses == "preproses"){
//mulai proses
set_time_limit(0);
setTimeout(function(){ buatindex() }, 3000);
setTimeout(function(){ hitungbobot() }, 3000);
setTimeout(function(){ panjangvektor() }, 3000);
console.log("Completed all");
}
function buatindex() {
code
}
function hitungbobot() {
code
}
function panjangvektor() {
code
}
Also you can console.log in ajax success response.
Something Like this : JsFiddle Example
count your post parameter ($_POST["preproses"]) and keep into an javascript variable like var count = ""; . you can also take an hidden text variable which will be increase by 1 after every notification send. after all notification values send this hidden variable will be equal to the count variable. then you can be sure that all the notifications have been sent. Hope this will work for you..:)
Haven't you tried async: false yet? This will stop further processing until one ajax request is complete.

Is it possible to call a function using Ajax?

I'm noob, and i recently knew about Ajax, so dont worry if my question seems idiot.
I tried to do that, but i had no success, but i will explain what i tried to do:
I have one draggble box with some words, and everytime that i drag some elements to a certain place, i want to record this transition into my database.
So, i did that in Ajax:
UPDATE
$(document).ready(function() {
$(".event").draggable();
$(".drop").droppable({
drop: function(event, ui) {
var id = ui.draggable.attr("id");
var targetid = event.target.id ;
$.ajax( {
type: 'post',
url: "new.php",
data : { 'day' : '3' },
success: function( response ) {
alert( response );
}
});
}
});
});
New file:
function eventTransition($day){
$day = $_POST['day'];
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
}
eventTransition($day);
I tried to automatically put a value to the day variable.
Please try this in php file and reply if this helps you
function eventTransition($day){
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
}
$day = $_POST['day'];
eventTransition($day);
You cannot call a PHP function directly using Ajax. A(n over-)simplified new.php file may look like the following:
$day = $_REQUEST['day'];
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
In your ajax call you must specify:
dataType: 'json'
As #baxri advises, add an error handler.

How to return json value from php page to html page by ajax and how to show result on html page

I m validating email id in php and ajax, and want to return value from php page to html in JSON format.
I want to keep that return value in php variable for the further use.
I'm doing these all in codeigniter, and I want to show .gif image while my AJAX is processing. (Pre loader image)
AJAX/Javascript/jQuery:
function checkEmail(value_email_mobile) {
if (value_email_mobile !== '') {
//alert('te');
$.ajax({
type: "POST",
url: url_check_user_avail_status,
data: "value_email_mobile=" + value_email_mobile,
success: function(msg) {
alert(msg);
//$('#psid').html("<img src='images/spacer.gif'>");
// $('#stat').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
}
PHP/Controller:
<?php
function check_email_or_mobile($param)
{
$ci = CI();
$value = $param['email_or_mobile'];
$query = "SELECT user_email , mobile FROM tb_users WHERE user_email = '$value' or mobile = '$value'";
$query = $ci->db->query($query);
if ($query->num_rows() > 0)
{
if (is_numeric($value))
{
return $res = "This mobile number is not registerd";
}
else
{
return $res = "This Email id is not registerd";
}
}
}
This is just to give you an example on how it will work.
First off, (obviously) there must the a preloader image ready inside the document. This must be hidden initially.
Second, before triggering the AJAX request, show the loading animated GIF.
Third, after the request if successful. Hide the image again inside your success: block inside the $.ajax().
Consider this example: Sample Output
PHP:
function check_email_or_mobile($param) {
// your functions, processes, blah blah
// lets say your processes and functions takes time
// lets emulate the processing by using sleep :)
sleep(3); // THIS IS JUST AN EXAMPLE! If your processing really takes time
$data['message'] = 'Process finished!';
// with regarding to storing, use sessions $_SESSION for further use
$_SESSION['your_data'] = $data_that_you_got;
echo json_encode($data); // use this function
exit;
}
// just a simple trigger for that post request (only used in this example)
// you really dont need this since you will access it thru your url
// domain/controller/method
if(isset($_POST['request'])) {
check_email_or_mobile(1);
}
HTML/jQuery/AJAX:
<!-- your animated loading image -->
<img src="http://i600.photobucket.com/albums/tt82/ugmhemhe/preloader.gif" id="loader" style="display: none;" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- <script type="text/javascript" src="jquery.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
// before the request, show the GIF
$('#loader').show();
$.ajax({
url: document.URL, // JUST A SAMPLE (url_check_user_avail_status)
type: 'POST',
data: {request: true},
dataType: 'JSON',
// data: "value_email_mobile=" + value_email_mobile,
success: function(response) {
// After a succesful response, hide the GIF
$('#loader').fadeOut();
alert(response.message);
}
});
});
</script>
My assumption is, since this is just a simple email checking, this wont really take a chunk of time. The other way is to fake the loading process.
success: function(response) {
// After a succesful response, hide the GIF
// Fake the loading time, lets say 3 seconds
setInterval(function(){
$('#loader').fadeOut();
alert(response.message);
}, 3000);
}
Let us know what part of your code is not working?
1) Check if the request flow is hitting the function checkEmail? PHP has inbuilt JSON converting utility json_encode. You could start using that.
2) If you want to store this on the server for further use, you could think about usage like
a) Storing it in Database (If really needed based on your requirements. Note: This is always expensive)
b) Session - If you would want this info to be available for all the other users too.
c) Or keep it in the memory like any of the caching mechanisms like memcache etc
3) For displaying the busy display,
// Before the below ajax call, show the busy display
$.ajax({
});
// After the ajax call, hide the busy display.
You could do this using JavaScript / JQuery on your choice.
I remember using
JSON.parse(data)
to convert JSON ino a javascript object.
Jquery has its own JSON parser btw. Something like $.JSONParse(data)

AJAX and PHP making like button

I have this like button code I want the like number to go up after click but there a need to refresh the page how can I do this:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('body').on( 'click' , '.votebutton' , function(){
var span = $(this).children('span');
var no = parseInt($(this).text(), 10);
$(span).text(++no);
var _id = $(this).data('vote');
$.ajax({
type: 'POST',
url: 'vote.php',
data: {
id: _id
}
});
});
});
</script>
<?php
$q = mysql_query("SELECT * FROM vote");while($row = mysql_fetch_array($q)){
$item[] = $row;
foreach($item as $i){}
echo "<button class='votebutton' data-vote='".$row[0]."'>Up vote</button><span>".$row[1]."</span>";
}
?>
It seems like you have two options. You could either A) make the post request return the new like count; or B) increment it manually with jQuery, which would be faster but not necessarily as accurate.
For the first option, you'd change your AJAX request to something like
$.ajax({
...
}).done(update_count)
where update_count is a function that takes the request as an argument and updates the count for a button. This method is is slower, but it would show an accurate like count at every instance, since the shown value is always the most current value in the database.
For the second option, you could select the span for the button and update its value with jQuery. This would be slightly faster, since it wouldn't have to wait for the AJAX query to complete, but it would only increment once, even if somebody else hit the "like" button.
Use location.reload(); to refresh the page.

Categories