I would like to refresh a div every second with a PHP variable using Jquery.
I have a simple PHP file with a variable date:
<?php
$date = date('d/m/Y H:i:s');
?>
I have a HTML file with the following code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
function request() {
$.ajax({
url: "date.php",
dataType: "text",
cache: false,
success: function(data) {
var json = $.parseJSON(data);
$('#result').html(json.date);
}
});
}
setTimeout(request, 1000);
});
</script>
</head>
<body>
<div id="result">
</div>
</body>
</html>
But the result is a blank page. I can not make it work. I would like your help.
I would like to refresh every second a PHP variable using Jquery.
You need to print date variable:
<?php
$date = date('d/m/Y H:i:s');
echo $date;
?>
Related
I've one page called test.php that display 2 types of products, first type is Odd second type is Even, the page have one HTML Switch/Toggle
Note( the code work OK and it display results according to switch/toggle value )
I've 1 issue
Code run's ok but it duplicate the switch/toggle (See Images Bellow)
.
test.php
<?php
require ('../../common.php');
echo "
<html>
<head>
<link rel='stylesheet' href='css/toggleOddEven.css'>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
to load default odd products on page load
<script type='text/javascript'>
$(window).load(function() {
$.ajax({
type:'POST',
url:'test.php',
data:{
product_type:'odd'
},
success: function(data){
$('#view').html(data);
}
});
});
</script>
Switch/Toggle value
<script type='text/javascript'>
$(function(){
$('#myonoffswitch').click(function() {
if ($('#myonoffswitch').prop('checked')) {
$.ajax({
type:'POST',
url:'test.php',
data:{
product_type:'even'
},
success: function(data){
$('#view').html(data);
}
});
}else{
$.ajax({
type:'POST',
url:'test.php',
data:{
product_type:'odd'
},
success: function(data){
$('#view').html(data);
}
});
}
});
});
</script>
Rest of page code
</head>
<body>
<div class='onoffswitch'>
<input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch'>
<label class='onoffswitch-label' for='myonoffswitch'>
<span class='onoffswitch-inner'></span>
<span class='onoffswitch-switch'></span>
</label>
</div>
<div id='view'></div>
</body>
</html>
";
if (isset($_POST['product_type'])) {
$product_type = $_POST['product_type'];
$allProducts="SELECT * FROM products_tbl
WHERE product_type = :product_type ";
$stmt = $db->prepare($allProducts);
$query_params = array(
':product_type' => $product_type
);
$stmt->execute($query_params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $value):
echo "
<strong># </strong> <a href='prod?id=".$value['product_name']."'>".$value['product_name']."</a> </br>
";
endforeach;
}
?>
why it duplicate the tag ? see bellow image
odd product (default value)
even product
It's because you load the whole page in test.php, not only the result data. This should help:
if (isset($_POST['product_type'])) {
--> keep existing code
} else {
--> Put your large echo into here
echo "
<html>
<head>
<link rel='stylesheet' href='css/toggleOddEven.css'>
...
";
}
A cleaner solution might be to split the data and the UI into seperate PHP files and only request the data PHP.
i am taking a value from the dropdown using jquery on change , i am using ajax to post to self, but i am not able to echo the posted variable.
<form>
<label>Select Doctor:</label>
<select class="docdrop">
<option value="">Choose</option>
<option value = "123">doca</option>
<option value = "456" >docb</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.docdrop").change(function(){
var d_Id = $(this).val();
if(d_Id!="")
{
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'];?>",
data: {d_id1 : d_Id}, //using 'd_id1' did not make a change
success: function(){
alert(d_Id]);
}
});
}
});
});
</script>
//php code in same page
<?php
if(isset($_POST['d_id1']))
$d_Id = $_POST['d_id1'];
?>
<p><?php echo $d_Id; ?></p>
i get the alert on success but , i am unable to echo the posted variable. i dont want to use serialize() or post the entire form. just d_Id whic i obtain in jquery
If you want you can do this without using jQuery in this way :
<?php
$d_id1 ="";
if(isset($_POST['d_id1'])){
$d_Id = $_POST['d_id1'];
echo $d_Id;
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head>
<body>
<form>
<label>Select Doctor:</label>
<select class="docdrop" >
<option value="">Choose</option>
<option value = "123">doca</option>
<option value = "456" >docb</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.docdrop").change(function(){
var d_Id = $(this).val();
if(d_Id!="")
{
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'];?>",
data: {d_id1 : d_Id},
success: function(data){
d_id1 = data;
document.getElementById('name').innerHTML = d_id1;
console.log(data);
}
});
}
});
});
</script>
<p id ="name"><?php echo $d_id1;?></p>
</body>
</html>
php code execute one time on page load, so that time your variables $d_Id and $d_Id1 are not created, so it is not display any value.
also ajax execute without page refresh and all code in side success executed without any error.
success: function(data){
alert(data);
}
You will alert the data send from backend i.e. echoed by your php part, which in your case will be the result of <p><?php echo $d_Id; ?></p>, if you just need your $d_id selected without the paragraph tags change your code to <?php echo $d_Id; ?>. Of course you may prefer to use JSON as output of your backend and then parse it in the success callback with $.parseJSON(data) per instance or use data type 'json' in your AJAX reques.
I created simple code, that should pass JS variable to PHP on the same page. This is code that i have written so far:
<body>
<h3>Client side IP geolocation using ipinfo.io</h3>
<p><a onclick="" href="xyz.pdf" download id="xyz" value="x">test pdf</a></p>
<p><?php print_r($_SERVER['SERVER_NAME'] . '/' . $_SERVER['REQUEST_URI']); ?></p>
<p><?php
if(isset($_POST['city']))
{
$uid = $_POST['city'];
print_r("elo");
}
?></p>
</body>
<script>
$.get("http://ipinfo.io", function (response) {
if(response.city == 'BiaĆystok') {
$("a").click(function() {
var city = response.city;
$.ajax({
type: "POST",
url: 'index.php',
data: { city : city },
success: function(data)
{
alert(city);
}
});
});
}
}, "jsonp");
</script>
So as u can see, im trying to pass city of the user, who downloaded specific file. When i test it locally, after clicking on download link
i get alert from success, so i guess I'm doing it correctly. But my PHP above doesn't print anything. There is no $_POST['city'] on the website.
Do you have any advice what I'm doing wrong?
If all you want is to print city name after clicking on the link then you don't need php for it.
<html>
<body>
<h3>Client side IP geolocation using ipinfo.io</h3>
<p><a onclick="" href="xyz.pdf" download id="xyz" value="x">test pdf</a></p>
<p><?php print_r($_SERVER['SERVER_NAME'] . '/' . $_SERVER['REQUEST_URI']); ?></p>
<p id="result">
<!-- Result will be printed here -->
</p>
</body>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
$.get("http://ipinfo.io", function (response) {
$("a").click(function() {
var city = response.city;
$('p#result').html("City Name: "+city);
});
}, "jsonp");
</script>
</html>
If you want something from php side then...
Write this condition in the starting of the file
<?php
if(isset($_POST['city'])) {
die("...Return something to the call from jquery");
}
?>
and this code should be followed by your remaining code.
Note: If you are expecting JSON data from php then use correct headers and output the json string from php. using die() won't solve the issue.
I'm attempting to post some data back to the same page through ajax. In the example below the $name variable is not being updated in my page once the button is clicked. However, if I look at the console log of the response from ajax (using firebug) it shows the correct html, with the name inserted (i.e. <div>Matthew</div>) - the page just isn't being updated with this response. Any ideas for how to fix this would be greatly appreciated.
The code I have is:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
$name = "A name";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name = "No name!";
}
else{
$name = $_POST["name"];
}
}
?>
<script>
$(document).ready(function(){
$("button").click(function(){
var mydata = {name: "Matthew"};
$.ajax({
type: 'POST',
data: mydata,
success: function(data){
console.log(data);
}
});
});
});
</script>
<button>Send an HTTP POST request to a page and get the result back</button>
<div id="name">
<?php echo $name;?>
</div>
</body>
</html>
It is because <?php echo $name;?> does not run again when doing the ajax call. You have to replace the content of the div in the success function like this:
success: function(data){
$("div").html(data);
}
I have got 2 files, one named index.php and one named api.php. I am trying to retrieve some data from my DB and I've done this simple example before trying to put the code into my project. In the api.php file I ve got the following:
$connessione=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
$scelta_db=mysql_select_db(DB_NAME) or die(mysql_error());
$idM=67;
$result = mysql_query("SELECT * FROM map_comment WHERE idMap ='$idM'");
$array = array();
while ( $row = mysql_fetch_row($result) )
{
$array[] = $row;
}
echo json_encode($array);
While in the index.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<h3>Output: </h3>
<div id="output">Attacco qua sotto</div>
<button onclick ='show_comments'>Carica commenti </button>
<script id="source" language="javascript" type="text/javascript">
function show_comments()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var idU = row[1];
var text_map = row[3];
$('#output').append("<b> idU: </b>"+idU+"<b>text </b>"+text_map)
.append("<hr />");
}
}
});
};
</script>
</body>
</html>
The problem is that it does not seems to "append" nothing and I dunno what I am doing wrong. I KNOW I should use mysqli, I'll fix that. Plus: HOW can I "send" a $idM to the api.php from the index.php (for example an $id already defined in the index.php)?
Your function is not called when you click the button, in an onclick attribute you're not setting a function but rather writing code to execute. See example below
<button onclick ='show_comments()'>...
To send the id, you can use the data parameter
data: {id: 67},
Since this is a GET request you can use the php super global $_GET to retrieve the value $_GET['id'].