I have two .php files. The first one ajax_testing.php looks like this:
<!DOCTYPE html>
<html>
<?php
$index_local=1;
$_SESSION['global_index'] = $index_local;
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="main">Who is batman? click count=<?echo $_SESSION['global_index'] ?>
<button id="detailed">LINK</button>
</div>
</body>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait till page is loaded
$("button").click(function(){
<?php
$_SESSION['global_index']+=1;
?>
$('#main').load('property-detailed.php?global_index='
+ <?php echo $_SESSION['global_index']; ?>
+ ' #main', function() {});
});
}); //// End of Wait till page is loaded
</script>
</html>
Document number two is called property-detailed.php and looks like this:
<!DOCTYPE html>
<html>
<?php
$_SESSION['global_index'] = $_GET['global_index'];
?>
<head>
<script></script>
</head>
<body>
<div id="main">Who is batman? click count=<?php echo $_SESSION['global_index']; ?>
<button id="detailed">LINK</button>
</div>
</body>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait til page is loaded
$("button").click(function(){
<?php
$_SESSION['global_index']+=1;
?>
$('#main').load('property-detailed.php?global_index='
+ <?echo $_SESSION['global_index'] ?>
+ ' #main', function() {});
});
}); //// End of Wait till page is loaded
</script>
</html>
I load the first page, and it has a variable, $global_index, that is set to 1 and a button with an ajax command to reload the div with the new information found on the second page.
My goal is to have the variable $global_index carry over and increment each time I press the button. Is this possible with only ajax being implemented? If so, is there a way to make it happen with only the first page? Otherwise would it just be easier to have my database keep track of this number and increment that?
In your ajax_testing.php:
<?php session_start(); ?>
<script type="text/javascript" src="jquery.js"></script>
<?php
$_SESSION['counter'] = 1;
$count = $_SESSION['counter'];
?>
<div id="main">Batman<?php echo $count; ?></div>
<button id="detailed">Link</button>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#detailed',function(){
var count = "<?php echo $count; ?>",
dataString = "counter=" + count;
$.ajax({
type: "POST",
url: "property-detaild.php",
data:dataString,
success:function(data){
$('#main').html(data);
console.log(data);
}
});
})
});
</script>
And in your property-detailed.php:
<?php
session_start();
$_SESSION['counter'] = $_SESSION['counter']+1;
echo $_SESSION['counter'];
?>
Related
I am trying to print some code from PHP after clicking button in JavaScript, however the code is not running and I can't see any errors.
<script type="text/javascript src="https://code.jquery.com/jquery-
3.4.1.min.js" >
$( document ).ready(function() {
<?php echo '$("button[data-id='. $transport[0]['request']['vehicleType']
. ']" ).click();'; ?>
});
</script>
...
<script type="text/JavaScript src=" https:="" code.jquery.com="" jquery
3.4.1.min.js"="">
$( document ).ready(function() {
$("button[data-id=seated]" ).click();});
</script>
Running the code in console works just fine and the button is clicked,however echoing from php the code is present without errors but not executed and the button is not clicked.
the code is not working even like this
php
<script src="https://code.jquery.com/jquery-3.4.1.min.js" > </script>
<script type="text/javascript">
$( document ).ready(function() {
<?php echo '$("button[data-id='. $transport[0]['request']['vehicleType'] . ']" ).click();'; ?>
});
</script>
js output
<script src="https://code.jquery.com/jquery-3.4.1.min.js"> </script>
<script type="text/javascript">
$( document ).ready(function() {
$("button[data-id=seated]" ).click();});
</script>
those missing quotes and slashes came from formatting my question, im new to the forum so i wasn't sure how to format the code.
<script src="https://code.jquery.com/jquery-3.4.1.min.js" > </script>
<script type="text/javascript">
$( document ).ready(function() {
setTimeout(function(){ <?php echo '$("button[data-id='. $transport[0]['request']['vehicleType'] . ']" )[0].click()' ?> }, 100)
setTimeout(function(){ <?php echo '$("input[value='. $transport[0]['request']['vehicleSpecification'] . ']")[0].click();'; ?> }, 100)
});
</script>
A small time out and ref to element 0 was enough to make it work
I'm building a chat website and i want to add a sound alert whenever a new message is sent so i can alert other users for new unread messages(i use MySQL for storing messages etc.). I use ajax to get the messages from the database and put them on my chatbox. I tryied every way but it doesn't seen to work idividually on every NEW message. Please help!
That's my index.php
<?php
session_start ();
define('DB_HOST', 'localhost');
define('DB_NAME', '*******');
define('DB_USER','*****');
define('DB_PASSWORD','********');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<META HTTP-EQUIV="content-type" CONTENT= "text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Chat2Chat!</title>
</head>
<body id="body-color">
<?php
if (! isset ( $_SESSION ['user'] )) {
header ( "Location: sign-in.html" ); // Redirect the user
} else {
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">
Καλωσήρθες, <b><?php echo $_SESSION['user']; ?></b>
</p>
<p class="logout">
<b class="submitmsg" id="exit" href="#">Logout</b>
</p>
<div style="clear: both"></div>
</div>
<div id="chatbox" class="chatbox">
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" autofocus/>
<input class="submitmsg" name="submitmsg" type="submit" id="submitmsg" value="Αποστολή"/>
</form>
</div>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
setInterval ( "get()", 2000 );
});
//jQuery Document
$(document).ready(function(){
//If user wants to end session
$("#exit").click(function(){
var exit = confirm("Είσαι σίγουρος πως θέλεις να αποσυνδεθείς;");
if(exit==true){window.location = 'index.php?logout=true';}
});
});
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
loadLog;
return false;
});
setInterval (loadLog, 2500);
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatbox").html(data);
var scroll = document.getElementById('chatbox');
scroll.scrollTop = scroll.scrollHeight;
}
});
}
</script>
<?php
}
?>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
The chat.php
<!DOCTYPE HTML>
<head>
<title>Chat</title>
<META HTTP-EQUIV="content-type" CONTENT= "text/html; charset=UTF-8">
</head>
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'db_57218');
define('DB_USER','u57218');
define('DB_PASSWORD','27222528');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Failed to connect to MySQL: " . mysqli_error());
$query = "SELECT * FROM Messages";
if($result = mysqli_query ($con, $query)){
while ($row = mysqli_fetch_row($result))
{if($row['4']==0){
echo '('.$row['5'].') <b>'.$row['1'].'</b>: '.$row['2'].'<br>';
}
else{echo 'Ο χρήστης <b>'.$row['1'].'</b> '.$row['2'].'<br>';}
}
mysqli_free_result($result);
}
mysqli_close($con);
?>
You can store the last message id which you played sound for, and at every refresh action, you can check if the last message id is equals to id you stored before. If not, you play sound.
To be more clear:
$lastMessageId=5;
$lastMessageIdWePlayedSoundFor=4;
if($lastMessageId!=$lastMessageIdWePlayedSoundFor)
{
////play sound here
$lastMessageIdWePlayedSoundFor=$lastMessageId;
}
So whenever there is a new message we haven't played a sound for it's existance, we play sound. You can use this algorithm.
I have php code and jQuery/javascript. I want to make visitor counter using jQuery and php code.
Here is the php code :
<?php
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "could not open the file" ;
} else {
$counter = (int ) fread($handle,20);
fclose ($handle);
$counter++;
//echo $counter;
$handle = fopen("counter.txt", "w" );
fwrite($handle,$counter) ;
fclose ($handle) ;
}
?>
and this is jQuery/javascript code :
<html>
<head>
<title>jQuery Hello World</title>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/jquery.counter.js"></script>
<link href="js/jquery.counter-analog.css" rel="stylesheet">
</head>
<body>
<span id="custom"></span>
<script>
$('#custom').addClass('counter-analog').counter({
//direction: 'up',
interval: '1',
format: '99999'
//stop: '2012'
});
</script>
</body>
</html>
How can I combine the jQuery/javascript code into php code? This is my first time for using jQuery, and I still don't understand to use jQuery. So I need your help. :D Thank you.
This is the result:
I want to add "50" into the jQuery "00000", so the result is "00050"
You simply need to echo the counter value in the span element.
So assuming your PHP code is at the top of the file, it should look like this.
<?php
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "could not open the file" ;
} else {
$counter = (int ) fread($handle,20);
fclose ($handle);
$counter++;
//echo $counter;
$handle = fopen("counter.txt", "w" );
fwrite($handle,$counter) ;
fclose ($handle) ;
}
?>
<html>
<head>
<title>jQuery Hello World</title>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/jquery.counter.js"></script>
<link href="js/jquery.counter-analog.css" rel="stylesheet">
</head>
<body>
<span id="custom"><?php echo $counter; ?></span>
<script>
$('#custom').addClass('counter-analog').counter({
//direction: 'up',
interval: '1',
format: '99999'
//stop: '2012'
});
</script>
</body>
</html>
I Have been going through a tutorial on infinite scrolling and have everything exactly the same except my alert is not being triggered and I cannot work out why. Any possible variations of obtaining the scroll positioning in the IF statement would also be helpful.
<?php
require_once("connect.php");
$results = $connect->query("SELECT * FROM images ORDER BY image_name DESC LIMIT 0,2");
$count = $connect->query("SELECT * FROM images");
$nbr = $count->rowCount();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class='images'>
<?php
while($row = $results->fetch())
{
?>
<p><img src="images/<?php echo $row['image_name'];?>" height="500" width="500"></p>
<?php
}
?>
</div>
<script src='js/jquery.js'></script>
<script>
$(document).ready(function(){
var load = 0;
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height())
{
alert("test");
}
});
});
</script>
</body>
</html>
Found the solution. The correct library needs to be called which many sites do not stipulate. Here is the code that needs to be posted just before the scroll script.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
I'm doing a small project where I'm trying to create a continual gallery for a user; whereby, they upload a file, and it immediately appears on the same page. The one thing I can't manage to accomplish is to keep the files there on the page even if the page is refreshed. In other words, I want the user to return and see all of their uploaded files as if they never left, until they close the browser. I've tried using cookies and session variables but I'm confused on how to implement this. Here is my Code. I APOLOGIZE IN ADVANCE FOR BAD INDENTATION.
My index.php:
<?php
// Process image
$uploadName = 'uploaded/pic.jpg';
if (count($_FILES))
move_uploaded_file($_FILES['image']['tmp_name'], $uploadName);
?>
<!DOCTYPE html>
<html>
<head>
<style>
li { display: inline-block; padding: 200px; width: 200px;}
img { width: 100%; height:100%;}
</style>
<script type="text/javascript">
function iframeSubmit(formElem, action, callback) {
// name a callback that will be called from inside the iframe
var callbackName = 'iframe' + Math.ceil(Math.random() * 10000);
action = action + (action.indexOf('?') == -1 ? '?' : '&') + 'callback='+
callbackName;
// create an iframe and use the callback as its name
var iframe = document.createElement('iframe');
iframe.setAttribute('name', callbackName);
iframe.style.display = 'none';
// add the target and edit the action of the form
formElem.setAttribute('target', callbackName);
formElem.setAttribute('action', action);
// add the hidden iframe after the form
formElem.parentNode.appendChild(iframe);
window[callbackName] = callback;
}
;
</script>
</head>
<body onload="onload()">
Home
Schedule
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>
<ul>
<?php if (count($_FILES)): ?>
<li><img src="<?php echo $uploadName ?>"/></li>
<?php endif; ?>
</ul>
<script type="text/javascript">
function onload() {
}
</script>
<script type="text/javascript">
function processResponse(response) {
if (!response.success) {
alert('woopsie');
return;
}
var newListItem = document.createElement('li');
newListItem.innerHTML = '<img src="' + response.path + '"/>';
document.getElementsByTagName('ul')[0].appendChild(newListItem);
}
function onload() {
iframeSubmit(document.getElementsByTagName('form')[0], 'upload.php',
processResponse);
}
</script>
</body>
</html>
Here is my upload.php:
<?php
enter code here
$imagePath = 'uploaded/pic.jpg';
setcookie("cookie", "stuff", time() + 3600, $uploadName);
move_uploaded_file($_FILES['image']['tmp_name'], $imagePath);
?>
<!DOCTYPE html>
<html>
<head>Iframe content</head>
<body>
<script type="text/javascript">
<?php
echo 'window.parent[\'' . $_GET['callback'] . '\']('
. json_encode(array('success' => true, 'path' => $imagePath)) . ')';
?>
</script>
</body>
</html>