In my display page I have a script that updates a div from another php page.
How do I re-write the below script to:
Be a function I can call with updateadiv(divid,content) in my display page (in php) where content is a php variable. (the script will then not call the php page but take the input variable).
<!DOCTYPE html>
<html>
<body>
function updatediv(divId, content)
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
(function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#content').hide();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
$('#content').show();
},
success: function() {
$('#loading').hide();
$('#content').show();
}
});
var $container = $("#content");
$container.load("http://192.168.1.90/json_output.php");
var refreshId = setInterval(function()
{
$container.load('http://192.168.1.90/json_output.php');
}, 9000);
});
})(jQuery);
</script>
<?php
function createarray() {
global $reindexed_devices_a ;
$feed_url = "http://192.168.1.90/JSON?request=getstatus&ref=all&location1=all&location2=all";
//$feed_url = "demoxml.xml";
$json = file_get_contents($feed_url);
$devices_a = json_decode($json, true);
//echo $devices_a[Devices][2][name] ;
//echo "<BR> ReIndexed:";
$reindexed_devices_a = array(Devices => array());
foreach ($devices_a[Devices] as $value) {
$reindexed_devices_a[Devices][$value[ref]] = $value;
}
//echo $reindexed_devices_a[Devices][59][name] ;
//need to do some conditional formatting before updating to DIV's
if ($reindexed_devices_a[Devices][59][name] == 'Coffee maker') {
$reindexed_devices_a[Devices][59][name] = "overwritten";
}
echo time();
//echo $reindexed_devices_a[Devices][59][name] ;
}
createarray();
$name59=$reindexed_devices_a[Devices][59][name];
//check if $name59 has changed - if yes update div
updatediv('59');
echo "This is a test <div id = 'name59'>.....</div>";
?>
</body>
</html>
function updateadiv(DivID , Url){
$('#loading').hide();
$('#' + DivID ).html('');
$.ajax({
url:url,
success:function(rData){
$('#' + DivID ).html(rData);
}
});
}
Related
Is it possible to make script tag in to the database print area? I need to add some JavaScript in to table. How can I add this?
Here is the sample of script
$results = $mysqli->query($query);
if($results) {
print ' here the Script '
<script>
$(document).ready(function() {
$('#b1').click(function(){
var data = $('#f1').serialize();
$.post( "post.php", data,function(return_data,status){
$("#display").html(return_data.msg);
setTimeout(function() { $("#display").fadeOut('slow'); }, 4000);
},"json");
})
});
</script>
<?php
$html = ' <script>
$(document).ready(function() {
$("#b1").click(function(){
var data = $("#f1").serialize();
$.post( "post.php", data,function(return_data,status){
$("#display").html(return_data.msg);
setTimeout(function() { $("#display").fadeOut("slow"); }, 4000);
},"json");
})
});
</script>';
echo $html;
?>
Is there a way to get updates from a PHP process while it's not finished and it has been called by ajax? By updates i mean flushed output from the PHP script.
var proc;
$('#start').click(function () {
proc = $.ajax({
type: 'POST',
url: 'execute.php',
// getData function that will get me updated data
getData: function (update){
alert(update);
}
});
});
UPDATE:
Lets say we want to get that echo before this ends.
execute.php
<?php
$progress = 0;
while(1){
$progress++;
echo $progress;
flush();
sleep(5);
if($progress == 100){
break;
}
}
?>
FINAL:
myScript.js
var strongcalcs;
var source;
$('#start').click(function () {
strongcalcs = $.ajax({
type: 'POST',
url: 'execute.php',
beforeSend: function () {
rpm_percent();
},
success: function(result){
source.close();
},
complete: function () {
source.close();
},
error: function () {
source.close();
}
});
});
function rpm_percent() {
source = new EventSource("execute.php");
if(typeof(EventSource) !== "undefined") {
source.onmessage = function(event) {
console.log(event.data);
};
} else {
alert("nono");
}
}
execute.php
<?php
$coco = 0;
function sendMsg($msg, &$coco) {
echo "id: " . $coco . "\n";
echo "data: " . $msg;
echo "\n";
echo "\n";
ob_flush();
flush();
$coco++;
}
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$progress = 0;
while(1){
sendMsg($progress++, $coco);
ob_flush();
flush();
sleep(5);
if($progress == 100){
break;
}
}
?>
I've in the past used Server Sent Events for this (https://www.w3schools.com/html/html5_serversentevents.asp). Internet Explorer is not supported out of the box, but there are polyfills that can solve the issue.
I think Websockets do something similar but don't have experience with those myself.
you can use Ajax callback when success load file from server..
$('#start').click(function () {
proc = $.ajax({
type: 'POST',
url: 'execute.php',
success: function (respon){
//do what u want to do here.
if(respon.status == 0){
alert("failed");
}
else{
alert("ok");
}
},
error: function(xhr, error){
//for error handling
}
});
});
and in your php you can echo what u want to show
<?php
$var["status"] = 0;
//if(your condition){ $var["status"] = 1;}
return json_encode($var);
?>
for more information you can see on here and here
Below is my code to convert time to a fancy style for eg. 1 min ago, 9 hours ago etc using moment.js.
<script>
$(document).ready(function() {
var out = "";
var diffDays = moment.utc("<?php echo $row["created_date"]; ?>", "YYYY-MM-DD hh:mm").fromNow();
out += "<span class='glyphicon glyphicon-time hours'></span> "+ diffDays;
$("#divContent<?php echo $row["postid_userid"]; ?>").html(out);
});
</script>
The code is working fine.
I have an ajax load more option on the same page to load more posts when scrolling.
My main problem is that, the moment js I am using stopped working after ajax call. Is this the problem because the code is not getting moment.js on my ajax page get_results.php ?
This is my ajax function (which is on the same page and calls the other page to load more posts)
<script type="text/javascript">
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
var val = document.getElementById("id").value;
document.getElementById("id").value = Number(val)+5;
$.ajax({
type: 'post',
url: 'get_results.php',
data: {
getresult:val
},
success: function (response) {
loading = false;
if(response.trim().length == 0){
//notify user if nothing to load
$('.loading-info').html("No more posts!");
document.getElementById("loading-info").style.display = "block";
return;
}
else
{
var content = document.getElementById("all_rows");
content.innerHTML = content.innerHTML+response;
}
$('.loading-info').hide(); //hide loading animation once data is received
}
});
}
});
And this is the get_results.php page:
<?php session_start();
$user_id=$_SESSION['user_id'];
include "mydbfile.php";
if(isset($_POST['getresult']))
{
$no = $_POST['getresult'];
?>
<?php
$select =$conn->prepare("select * from ----- ");
$select->execute();
while($row =$select->fetch())
{
?>
//design to display more posts
<?php
}
} exit(); ?>
I have a table that shows userid, name, internetstatus, button
If internet status is 0, when I click on the button it will update the database as 1 and vice versa.
Also row['internet'] == 0 //Red button and row['internet'] == 1 //Green button. When I click on Red Button internet's value will be changed to 1 and and vice versa.
Everything works as intended. The only problem is, when I click on User #2's button (according to image), it will also affect User #3 and both will be updated. If they all have the same status, then all will be updated instead of only clicked one.
What part should I fix to code work as intended?
Main Page:
...table code...
//If internet == 0, Red Button will display
if($row['internet'] == 0) {
echo "<td><button type='submit' style='width:100%' class='btn btn-danger' value='ariza' id='".$row['id']."'>Problem</button></td>
<script src='https://code.jquery.com/jquery-2.2.2.min.js'></script>
<script>
$(document).ready(function() {
$('.btn-danger').click(function() {
var clickBtnValue = $(this).val();
var kullanici = ".$row['id'].";
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue,
'kullanici': kullanici
};
$.post(ajaxurl, data, function(response) {
// Changes
$('#ariza').removeClass('btn-danger');
$('#ariza').addClass('btn-success');
$('#ariza').html('Düzeltildi');
$('#var').html('Arızalı');
$('#var').css('color', 'red');
alert(response);
setTimeout(function() {
location.reload();
}, 2000);
});
});
});
</script>";
// If internet == 1, Green Button will display
} else {
echo "<td><button type='submit' style='width:100%' class='btn btn-success' value='duzelt' id='".$row['id']."'>OK</button></td>
<script src='https://code.jquery.com/jquery-2.2.2.min.js'></script>
<script>
$(document).ready(function() {
$('.btn-success').click(function() {
var clickBtnValue = $(this).val();
var kullanici = ".$row['id'].";
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue,
'kullanici': kullanici
};
$.post(ajaxurl, data, function(response) {
// Changes
$('#duzelt').removeClass('btn-success');
$('#duzelt').addClass('btn-danger');
$('#duzelt').html('Arızalı');
$('#yok').html('Var');
$('#yok').css('color', 'green');
alert(response);
setTimeout(function() {
location.reload();
}, 2000);
});
});
});
</script>";
}
ajax.php:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'duzelt':
isaretle_arizali();
break;
case 'ariza':
isaretle_duzeltildi();
break;
}
}
Functions.php:
function isaretle_arizali()
{
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$content = $_POST['kullanici'];
$int = 0;
if ($stmt = $mysqli->prepare("UPDATE members SET internet=? WHERE id=?"))
{
$stmt->bind_param('ss', $int, $content);
$stmt->execute();
$stmt->close();
echo "Marked as Problem";
}
else
{
echo "Fail.";
}
}
function isaretle_duzeltildi()
{
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$content = $_POST['kullanici'];
$int = 1;
if ($stmt = $mysqli->prepare("UPDATE members SET internet=? WHERE id=?"))
{
$stmt->bind_param('ss', $int, $content);
$stmt->execute();
$stmt->close();
echo "Marked as Fixed";
}
else
{
echo "Fail.";
}
}
Here's an alternative solution which would also minimize code duplication. Put this JavaScript code only once.
Note again. Only put this JavaScript code in your page once. You don't need to put it in more times as it works depending on what is clicked.
Example PHP code
//...table code...
//If internet == 0, Red Button will display
if($row['internet'] == 0): ?>
<td>
<button type='submit' style='width:100%' class='btn btn-danger' value='ariza' id='<?=$row['id']?>'>Problem</button>
</td>
<?php else: ?>
<td>
<button type='submit' style='width:100%' class='btn btn-success' value='duzelt' id='<?=$row['id']?>'>OK</button>
</td>
<?php endif;
// Rest of PHP code?
?>
<script>
$(document).ready(function() {
$('.btn-success, .btn-danger').click(function() {
var clickBtnValue = $(this).val();
var kullanici = $(this).attr("id");
var ajaxurl = 'ajax.php',
var data = {
'action': clickBtnValue,
'kullanici': kullanici
};
var self = this;
$.post(ajaxurl, data, function(response) {
// Changes
if ($(self).is(".btn-success")) {
$(self).removeClass('btn-success');
$(self).addClass('btn-danger');
$(self).html('Arızalı');
$(self).parent().prev().html('Var');
$(self).parent().prev().css('color', 'green');
} else {
$(self).removeClass('btn-danger');
$(self).addClass('btn-success');
$(self).html('Düzeltildi');
$(self).parent().prev().html('Arızalı');
$(self).parent().prev().css('color', 'red');
}
alert(response);
setTimeout(function() {
location.reload();
}, 2000);
});
});
});
</script>
I am passing an array from javascript to PHP using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<head>
<script>
var parms = [];
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function () {
parms.push($(this).text());
});
function loadXMLDoc(parms) {
$.ajax({
type: "POST",
url: "update.php",
data: {
value: $(parms).serializeArray()
},
success: function (data) {
alert(data);
}
});
}
$("button").on('click', function () {
loadXMLDoc(parms);
});
alert(parms);
</script>
</head>
On click of button, I am trying to call the PHP script to edit the display of my web page. However, the ajax call to the below PHP statement alerts only the "Am I printed" line.
<?php
$uid = $_POST['value'];
echo "Am I printed";
echo $uid;
// Do whatever you want with the $uid
?>
Why is the $uid value not returned to my javascript? Is there something am doing wrong?