on click make a server request to change php variable - php

I thought I solved the issue in a preceding question but it is sill not working. I want to change the php variables ($start and $end called by var b1 and var b2) if the admin clicks on button. After this the new code should be availble for every visitor, so it should make a server request. Here is my updated code:
<?php
if(date('w') == 4){ // day 2 = Tuesday
$start = strtotime('9:30');
$end = strtotime('12:30');
$timenow = date('U');
if ($timenow >= $start && $timenow <= $end) {
echo'<div id="iar_eu">';
echo quick_chat(200, 'default', 1, 'left', 0, 0, 1, 1, 1);
echo'</div>';
} }
?>
</div>
<?php if ( is_user_logged_in() ) { ?>
<input type="submit" value="Start Chat" id="start_chat" style="position: absolute; top: 30px; left: 10px;" />
<?php
} ?>
<script type="text/javascript">
if(jQuery('#start_chat').data('clicked')) {
// change var b1 and b2
$.ajax({
type: "POST",
url: "/web/htdocs/www.fattorefamiglia.com/home/wp-content/themes/child_care_creative/chat.php",
dataType: 'json',
data: { b1: "1:00", b2: "23:00" }
}).done(function(data) {
b1 = data.b1;
b2 = data.b2;
});}
else {
$.ajax({
type: "POST",
url: "/web/htdocs/www.fattorefamiglia.com/home/wp-content/themes/child_care_creative/chat.php",
dataType: 'json',
data: { b1: "9:00", b2: "18:00" }
}).done(function(data) {
b1 = data.b1;
b2 = data.b2;
});}
jQuery('#start_chat').click(function(){
$(this).data('clicked', true);
var b1 = '<?php echo $start; ?>';
var b2 = '<?php echo $end; ?>';
});
</script>
chat.php:
<?php
// variables
if (!empty($_POST)) {
$data['b1'] = $_POST['b1'];
$data['b2'] = $_POST['b2'];
}
// to not lose them
$_SESSION['chat'] = $data;
// to keep it compatible with your old code
$start = $data['b1'];
$end = $data['b2'];
// send the JSON formatted output
echo json_encode($data);
?>
Nothing happens when I click the button. What am I doing wrong?

There is a problem with the way jQuery is being used. All jQuery references should be made in functions that are only called after the page is ready, or in a wrapper that makes sure the page is ready.
For example, this code needs to be wrapped:
jQuery('#start_chat').click(function(){
$(this).data('clicked', true);
var b1 = '<?php echo $start; ?>';
var b2 = '<?php echo $end; ?>';
});
Like this:
jQuery(function(){
jQuery('#start_chat').click(function(){
$(this).data('clicked', true);
var b1 = '<?php echo $start; ?>'
var b2 = '<?php echo $end; ?>';
});
});
Setting the .data() isn't going to do you any good here. You're setting some info to the actual var instead of the element because of the way that method works.
But there's another problem with the way you're deciding to make AJAX requests, simply putting an if statement there won't make it happen. You would need a listener to make an action actually happen. But rather than get into that why don't you just simplify and do it like this?
<script type="text/javascript">
var b1 = '<?= $start ?>', b2 = '<?= $end ?>';
$(function(){
$('#start_chat').click(function(){
$.post('/web/htdocs/www.fattorefamiglia.com/home/wp-content/themes/child_care_creative/chat.php', { b1: '1:00', b2: '23:00' },
function(data) {
b1 = data.b1;
b2 = data.b2;
}, 'json');
});
});
</script>

This line
if(jQuery('#start_chat').data('clicked')) {
will never be true since .data('clicked') is not set until #start_chat is clicked which always will happen after the check has been made.
You need to rethink your process of what you want to accomplish.

Related

PHP and Ajax updating values

I'm trying to dynamically update text on a PHP page via AJAX. But, instead of the text coming through at different intervals, it all comes at once. Maybe this is the wrong approach.
index.html
<html>
<head>
<title>Please Update!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.post("hello.php", function(data){
var success = $("#update");
success.css("color", "green");
success.html("> \r " + data + ".");
});
});
</script>
</head>
<body>
<div id="update"></div>
</body>
</html>
hello.php
<?php
echo "Hello World\n";
sleep(1);
echo "\rFoobar\n";
sleep(1);
echo "\rBazboo\n";
?>
I'd like the text to overwrite itself after one second but it comes barreling down the pipe all at once. ;_;
Not sure about this, but it might help you to do...
in PHP
<?php
$result[] = "Hello World\n";
$result[] = "\rFoobar\n";
$result[] = "\rBazboo\n";
print_r($result);
?>
in Ajax result
$.post("hello.php", function(data){
for(let i = 0; i < data.length; i++) {
setTimeout(() => {
// your stuff to do is here by 1 second interval...
var success = $("#update");
success.css("color", "green");
success.html("> \r " + data[i] + ".");
}, 1000*i);
}
});
Simple Representation
var data = ["Hello World\n","\rFoobar\n","\rBazboo\n"];
for(let i = 0; i < data.length; i++) {
setTimeout(() => {
console.log(data[i]);
}, 1000*i);
}
Like Antony suggested. You could create an array in php and encode it as Json
and then create a settimeout().
php
$data = array("Hello World","Foobar","BazBoo");
echo json_encode($data);
jQuery ~ JavaScript
$.ajax({
method: "GET",
url: "hello.php",
success: (res) => {
for (let i = 0; i < res.length; i++) {
setTimeout(() => {
// or use .html(res[i])
$("#update").text(res[i] + "<br>");
}, 1000 * i);
}
}
})

Browsing inside Ajax response

I'm new to jquery & Ajax.
I have a php file with jquery inside it, which loads content from another php file on selection of a date
$("#datepicker3").change(function(){
$.ajax({
type: "POST",
url: "ptreport1.php",
data: 'ptdate=' + $(this).val(),
success: function(resultt){
$('#searchr').html(resultt);
$("#searchr").show();
}
});
});
The issue I'm facing is contents in ptreport1.php has links (pagination) contained to browsing scope of that php file. When the user clicks on those links he is directed out of the original page ajax content is loaded from.
Is there anyway to prevent that and load content in original page.
Update # 2.
After ediding the codes with preventDefault, following is my jquery
<script>
$(document).ready(function() {
$("#searchr").hide();
$(function() {
$('#datepicker3' ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd M yy'
});
});
$("#datepicker3").change(function(){
var myValue = $(this).val();
$.ajax({
type: "POST",
url: "ptreport1.php",
data: 'ptdate=' + $(this).val(),
success: function(resultt){
$('#searchr').html(resultt);
console.log('html.resultt');
$("#searchr").show();
$('.pagination-link').click(function(e) {
e.preventDefault();
//Another AJAX call to load the content here.
var page = $("#pagediv").html();
var timestamp =$("#timediv").html();
var dataString = 'page='+ page + '&timestamp='+ timestamp;
$.ajax({
type: "GET",
url: "ptreport1.php",
data: dataString,
success: function(resultt){
$('#searchr').html(resultt);
console.log('html.resultt');
$("#searchr").show();
}
});
});
}
});
});
});
</script>
and ptreport1.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
include "core.php";
connectdb();
$page = $_GET['page'];
$timestamp = $_GET['timestamp'];
$ptdate = $_POST['ptdate'];
if(isset($timestamp)){
$ptdate = date('d M Y', $_GET['timestamp']);
}else{
$timestamp = strtotime($ptdate);
}
if(!isset($page)){
$page=1;
}
if($page=="" || $page<=0)$page=1;
$numresults = mysqli_query($connect, "SELECT patient.firstname, patient.lastname, appointment.charge FROM patient INNER JOIN appointment ON patient.id = appointment.patientid WHERE DATE_FORMAT(appointment.date, '%d %b %Y')='".$ptdate."'")or die("error querying");
$numrows = mysqli_num_rows($numresults);
$num_items = $numrows; //changable
$items_per_page= 5;
$num_pages = ceil($num_items/$items_per_page);
if($page>$num_pages)$page= $num_pages;
$limit_start = ($page-1)*$items_per_page;
$npage = $page+1;
$numresults = mysqli_query($connect, "SELECT patient.firstname, patient.lastname, appointment.charge FROM patient INNER JOIN appointment ON patient.id = appointment.patientid WHERE DATE_FORMAT(appointment.date, '%d %b %Y')='".$ptdate."' LIMIT $limit_start, $items_per_page")or die("error querying");
$numrows = mysqli_num_rows($numresults);
if($numrows==0){
echo "Sorry, No results for $ptdate.";
exit();
}
echo "<p><table>";
while($msdrow = mysqli_fetch_assoc($numresults)){
$charge= $msdrow['charge'];
$fname= $msdrow['firstname'];
$lname= $msdrow['lastname'];
// $fullname = $fname." ".$lname;
echo "<tr><td>$fname</td><td>$lname</td><td>$charge</td></tr>";
$totalcharge = $totalcharge+$charge;
}
echo "<b><tr><td colspan=\"2\">Total Charge</td><td>$totalcharge</td></tr></b></table></p>";
echo "<div id='pagediv' >";
echo "$page</div>";
echo "<div id='timediv' >";
echo "$timestamp</div>";
echo "<p align=\"center\">";
if($page>1)
{
$ppage = $page-1;
echo "«PREV ";
}
if($page<$num_pages)
{
$npage = $page+1;
echo "Next»";
}
echo "<br/>$page/$num_pages<br/>";
echo "</p>";
What am i doing wrong here, since it after second click it jumps out of ajax directs to original php page.
Thanx
You would need to set onclick event handlers on the pagination links after loading the content in ptreport1.php. You'll need to change .pagination-link to match the links in the content you are loading.
success: function(resultt){
$('#searchr').html(resultt);
$("#searchr").show();
$('.pagination-link').click(function(e) {
e.preventDefault();
//Another AJAX call to load the content here.
});
}

Php variable not getting incremented in jquery

I want to increment $j in $.each function of jquery. But $j is not getting incremented. What may be the reason. My code is as follows:
$.ajax
({
url : "test.php",
type : "post",
data : {
"categoryIds" : categoryIds
},
dataType : "json",
success : function(resp){
var html = "";
var i = 1;
<?php $j = 1; ?>
$.each(resp,function(key,questions ){
<?php
$j = 1;
$testdataIndex = "answer_".$j;
?>
var test = "<?php echo $testdataIndex?>";
alert(test);
var res = "<?php echo $_SESSION['testdata'][$testdataIndex]; ?> ";
var index = "<?php echo $j++;?>";
alert(index);
});
});
Each time test prints 'answer_1' and index as 1
Fixed session issue :
$.ajax
({
url : "test.php",
type : "post",
data : {
"categoryIds" : categoryIds
},
dataType : "json",
success : function(resp){
var html = "";
var i = 1;
<?php $j = 1; ?>
$.each(resp,function(key,questions ){
var testdataIndex = "answer_" + i ;
var filename = "getsession.php?sessionName="+testdataIndex;
$.get(filename, function (data)
{
sessionValues = data;
$("#"+testdataIndex).text(sessionValues);
});//get
html += '<textarea class="form-control answer" rows = "5" style="width:127%;" id="answer_'+i+'" name="answer_'+i+'" required="required"></textarea>';
i++;
});//each
});//ajax
getsession.php
<?php
session_start();
$sessionName = $_GET['sessionName'];
print ($_SESSION['testdata'][$sessionName]);
?>
I have answered my question for other who face same problem.

How to update information by the click of a button?

I currently have two php files (index.php and update.php) In index.php, there is some javascript code and a button that sends a variable, called $sid, to update.php, where it is processed based on $sid. Here is the code for both index.php and update.php. I am not pasting it directly into StackOverflow, simply because of how you have to add code to your text on StackOverflow, and how JavaScript works with it's spacing hierarchy.
http://pastebin.com/fq87vvgz
Currently, when you press the button, an alert box does not pop up. If you put the PHP code in a PHP code checker, no errors appear.
Here is my code:
This is what is in index.php
<?php
$sid = 11;
?>
<script type="text/javascript">
$(document).ready(function(){
$('#vote').click(function(){
$.ajax({
url : 'update.php', // Notice how this sends to update.php
type : 'POST',
data : {
action : 'vote_server',
sid : $('#sid').data('sid')
},
dataType : 'JSON',
success : function(result) {
if (result.xhr == 'success') {
alert('You bumped your server!');
} else if (result.xhr == 'voted_already')
alert('You can only bump every 24 hours!')
}
});
});
})
</script>
<input type="button" class="btn btn-primary" id="vote" value="Vote up your server">
This is what is contained in update.php
<?php
define('action',$_POST['action']);
$result = array(
'xhr' => 'error'
);
if (action == 'vote_server')
{
$sid = (int)$_POST['sid'];
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$dbTime = #mysql_result(mysql_query("SELECT `id`, `last_updated` FROM `servers` WHERE `id` = '$sid'"), 0);
$timeDiff = $time - $dbTime;
if($timeDiff >= 86400){
mysql_query("UPDATE `servers` SET `last_updated` = '$time' WHERE `id` = '$sid'");
$result['xhr'] = 'success';
} else { $result['xhr'] = 'voted_already'; }
}
echo json_encode($result);
?>
Use query and ajax
in your index page...
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$( ".button" ).click(function() {
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
$.ajax({
type: "POST",
url: 'update.php',
data: {postedVar:var1, postedVar2:var2},
success: function(data)
{
alert(data);
}
});
});
});
</script>
<html>
<button class="button" data-var1="<?php echo "this is var1"; ?>" data-var2="<?php echo "this is var2"; ?>">Button</button>
</html>
On you update page...
access your vars like this
<?php
var1 = $_POST['postedVar1'];
var2 = $_POST['postedVar2'];
echo var1;
?>
...NOT TESTED

jQuery AJAX call on mousemove

I have an image being created with gdimage, which has 40000 5x5 blocks linking to different user profiles and I want that when you hover over one of those blocks, AJAX will go and fetch that profile from the database by detecting the x and y co-ords when it is moved over the image.
Then when it is clicked, with the information it has obtained link to that users profile.
Here is what I have got so far:
Javascript/jQuery:
<script type="text/javascript">
jQuery.fn.elementlocation = function() {
var curleft = 0;
var curtop = 0;
var obj = this;
do {
curleft += obj.attr('offsetLeft');
curtop += obj.attr('offsetTop');
obj = obj.offsetParent();
} while ( obj.attr('tagName') != 'BODY' );
return ( {x:curleft, y:curtop} );
};
$(document).ready( function() {
$("#gdimage").mousemove( function( eventObj ) {
var location = $("#gdimage").elementlocation();
var x = eventObj.pageX - location.x;
var x_org = eventObj.pageX - location.x;
var y = eventObj.pageY - location.y;
var y_org = eventObj.pageY - location.y;
x = x / 5;
y = y / 5;
x = (Math.floor( x ) + 1);
y = (Math.floor( y ) + 1);
if (y > 1) {
block = (y * 200) - 200;
block = block + x;
} else {
block = x;
}
$("#block").text( block );
$("#x_coords").text( x );
$("#y_coords").text( y );
$.ajax({
type: "GET",
url: "fetch.php",
data: "x=" + x + "&y=" + y + "",
dataType: "json",
async: false,
success: function(data) {
$("#user_name_area").html(data.username);
}
});
});
});
</script>
PHP:
<?
require('connect.php');
$mouse_x = $_GET['x'];
$mouse_y = $_GET['y'];
$grid_search = mysql_query("SELECT * FROM project WHERE project_x_cood = '$mouse_x' AND project_y_cood = '$mouse_y'") or die(mysql_error());
$user_exists = mysql_num_rows($grid_search);
if ($user_exists == 1) {
$row_grid_search = mysql_fetch_array($grid_search);
$user_id = $row_grid_search['project_user_id'];
$get_user = mysql_query("SELECT * FROM users WHERE user_id = '$user_id'") or die(mysql_error());
$row_get_user = mysql_fetch_array($get_user);
$user_name = $row_get_user['user_name'];
$user_online = $row_get_user['user_online'];
$json['username'] = $user_name;
echo json_encode($json);
} else {
$json['username'] = $blank;
echo json_encode($json);
}
?>
HTML
<div class="tip_trigger" style="cursor: pointer;">
<img src="gd_image.php" width="1000" height="1000" id="gdimage" />
<div id="hover" class="tip" style="text-align: left;">
Block No. <span id="block"></span><br />
X Co-ords: <span id="x_coords"></span><br />
Y Co-ords: <span id="y_coords"></span><br />
User: <span id="user_name_area"> </span>
</div>
</div>
Now, the 'block', 'x_coords' and 'y_coords' variables from the mousemove location works fine and shows in the span tags, but it's not getting the PHP variables from the AJAX function and I can't understand why.
I also don't know how to make it so when the mouse is clicked it takes the variables taken from fetch.php and directs the user to a page such as "/user/view/?id=VAR_ID_NUMBER"
Am I approaching this the wrong way, or doing it wrong? Can anyone help? :)
Please see the comments about not doing a fetch with every mousemove. Bad bad bad idea. Use some throttling.
That said, the problem is, you're not using the result in any way in the success function.
Your PHP function doesn't return anything to the browser. PHP variables do not magically become available to your client-side JavaScript. PHP simply runs, produces an HTML page as output, and sends it to the browser. The browser then parses the information that was sent to it as appropriate.
You need to modify your fetch.php to produce some properly formatted JSON string with the data you need. It would look something like { userid: 2837 }. For example, try:
echo "{ userid: $user_id, username: $user_name }";
In your success callback, the first argument jQuery will pass to that function will be the result of parsing the (hopefully properly formatted) JSON result so that it becomes a proper JavaScript object. Then, in the success callback, you can use the result, in a way such as:
//data will contain a JavaScript object that was generate from the JSON
//string the fetch.php produce, *iff* it generated a properly formatted
//JSON string.
function(data) {
$("#user_id_area").html(data.user_id);
}
Modify your HTML example as follows:
User ID: <span id="user_id_area"> </span>
Where showHover is a helper function that actually shows the hover.
Here is a pattern for throttling the mousemove function:
jQuery.fn.elementlocation = function() {
var curleft = 0;
var curtop = 0;
var obj = this;
do {
curleft += obj.attr('offsetLeft');
curtop += obj.attr('offsetTop');
obj = obj.offsetParent();
} while ( obj.attr('tagName') != 'BODY' );
return ( {x:curleft, y:curtop} );
};
$(document).ready( function() {
var updatetimer = null;
$("#gdimage").mousemove( function( eventObj ) {
clearTimer(updatetimer);
setTimeout(function() { update_hover(eventObj.pageX, eventObj.pageY); }, 500);
}
var update_hover = function(pageX, pageY) {
var location = $("#gdimage").elementlocation();
var x = pageX - location.x;
var y = pageY - location.y;
x = x / 5;
y = y / 5;
x = (Math.floor( x ) + 1);
y = (Math.floor( y ) + 1);
if (y > 1) {
block = (y * 200) - 200;
block = block + x;
} else {
block = x;
}
$("#block").text( block );
$("#x_coords").text( x );
$("#y_coords").text( y );
$.ajax({
type: "GET",
url: "fetch.php",
data: "x=" + x + "&y=" + y + "",
dataType: "json",
async: false,
success: function(data) {
//If you're using Chrome or Firefox+Firebug
//Uncomment the following line to get debugging info
//console.log("Name: "+data.username);
$("#user_name_area").html(data.username);
}
});
});
});
Can you show us the PHP code? Do you use json_encode on the return data?
An alternative would be to simply make the image a background to a <div> container and arrange <a> elements in the <div> where you need them then simply bind with jQuery to their click handler.
This also has benefits if the browser does not support jQuery or javascript as you can actually put the URL you need in the HREF attribute of the anchor. This way if jQuery is not enabled the link will be loaded normally.
A skeleton implementation would look like this:
Example CSS
#imagecontainer {
background-image: url('gd_image.php');
width: 1000px;
height: 1000px;
position: relative;
}
#imagecontainer a {
height: 100px;
width: 100px;
position: absolute;
}
#block1 {
left: 0px;
top: 0px;
}
#block2 {
left: 100px;
top: 0px;
}
Example HTML
<div id="imagecontainer">
</div>
Example jQuery
$(document).ready(function(){
$("#block1").click(function(){ /* do what you need here */ });
});

Categories