I want to get the latest post_id in the table without refreshing it, but the problem is whenever a user inserts a value to the database, It echoes infinitely the last post_id. I want it to echo only once. But I still want to get the latest post_id from the table.
Here is my main php:
<div id = "this_div">
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id ASC LIMIT 20";
$execute_query = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($execute_query))
{
$get_this_id = $row['post_id'];
echo $get_this_id."<br>";
}
$_SESSION['get_this_id'] = $get_this_id;
?>
</div>
here is my jQuery ajax:
<script>
var refreshId = setInterval(function(){
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
$.ajax({
url: 'another_file.php',
data: {},
success: function(data)
{
if(compare_session != data)
{
$('#this_div').text($('#this_div').text()+data);
}
}
});
},400);
</script>
here is the php code of another_file.php
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id DESC LIMIT 1";
$execute_query = mysqli_query($con,$query);
if($row = mysqli_fetch_assoc($execute_query))
{
echo $get_this_id = $row['post_id'];
}
?>
You are not updating the compare_session variable , it holds always the initial value . So update it inside success callback function
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
var refreshId = setInterval(function () {
$.ajax({
url: 'another_file.php',
data: {},
success: function (data) {
if (compare_session != data) {
$('#this_div').text($('#this_div').text() + data);
}
compare_session = data;
}
});
}, 400);
Related
I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks
mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}
Below is a jQuery function that retrieves 2 textbox values and posts them to another file ("Student Search Results.php"), where a live search is run using the values.
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = Team_Name + '?????' + Teacher;
$.ajax({
type: "POST",
url: "Student Search Results.php",
data: {
query: Search_Data
},
cache: false,
success: function() {
alert('The values were sent');
}
});
});
</script>
Below is the PHP script on the search page ("Student Search Results.php") that makes use of these values.
<?php
include "Connection.php";
if(isset($_POST['query'])){
$searchData = explode('?????', $_POST['query']);
$teamName = $searchData[0];
$teacher = $searchData[1];
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
echo $query;
?>
How would I be able to take variables from the PHP script (such as $result) to the first page, so I can create a result table? Simply including the PHP file does not work, as the file is only included once.
Thank you for your time.
Best option is to serialize to JSON using json_encode
I think best you can do is,
success: function(result) {
alert(result);
}
and Student Search Results.php print result in tabular format.
P.S. : Please follow proper file naming convention
use a proper URL, and send the data (and stop using camelcase for everything) :
$(".search").on('keyup', function() {
var data = {
team_name : $('#TeamName').val(),
teacher : $('#Teacher').val()
}
$.ajax({
type: "POST",
url: "student_search_results.php",
data: data,
cache: false
}).done(function(result) {
console.log(result);
});
});
And in PHP, you have to actually get the result into an array and json_encode it :
<?php
include "Connection.php";
$team_name = !empty( $_POST['team_name'] ) ? $_POST['team_name'] : null;
$teacher = !empty( $_POST['teacher'] ) ? $_POST['teacher'] : null;
if ($team_name && $teacher) {
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
?>
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = "Team_Name="+'Team_Name'&Teacher='+Teacher;
$.ajax({
type: "POST",
url: "Student_Search_Results.php",
data: Search_Data,
cache: false,
success: function(result) {
$('$output').html(result);
}
});
});
</script>
Here is output div
<div id="output"></div>
On Student_Search_Results.php page get
$tname = $_POST['Team_Name'];
$teacher = $_POST['Teacher'];
//your search query & print data
If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...
<script type="text/javascript">
function dispMsg() {
$("#displayMessage").load('load.php');
var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
$("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage"></div>
and here is the load.php:
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$id = $result['id'];
$from = $result['user_01'];
$to = $result['to_usr'];
$message = $result['message_01'];
$date = $result['date_send'];
echo "<span class='from'> $from </span>"
. "<span class='message'> $message </span> <br/>";
}
use the parameters and call back of $.load()
$.load(url, {param1:value, param2:value}, function(result){
if(result >5){
//do something
}
)
Example:
<?php
if($_REQUEST['action'] == 'check'){
if($_REQUEST['lastId'] < 5 ){
echo $_REQUEST['lastId']+1;
die;
}
}
if($_REQUEST['action'] == 'load'){
echo 'some conntent!';
die;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var lastId = 0;
function dispMsg() {
$.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
if(responce !== 0){
alert(responce);
$('#displayMessage').load('tmp.php', {action:'load'});
}
});
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage">1</div>
You can send the last message id with each request. If the last message of your query is greater than the id sent, send the response. Otherwise send nothing.
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "load.php",
type: "POST",
data: {
last: last
},
cache: false,
success: function(html){
//insert message
}
});
}
You can send the id as the id attribute in your HTML. Each message in the chat window is sent as a paragraph with some message id such as id="133".
Expanding on #Pé de Leão's solution, here's something more simple:
<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
$msg = $result->fetch_assoc();
if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
}
}
And on the client side:
function dispMsg() {
var last = $('#displayMessages span.from').attr('id');
$.get(baseUrl + '/load.php', { last: last }, function(result) {
if (result) {
$('#displayMessages').html(result);
}
});
}
Note that this replaces everything in displayMessages.
I am currently trying to update a textarea when a user clicks elsewhere. I'm not well-versed in AJAX and Jquery. However, the script doesn't seem to be updating the row in the DB.
Jquery/Text area:
<textarea id="<?php echo $item_id; ?>_textarea"><?php echo $notes; ?></textarea>
<script type="text/javascript">
$('<?php echo $item_id; ?>_textarea').on('blur',function () {
var notesVal = $(this).val(), id = $(this).data('id');
var itemVal = <?php echo $item_id; ?>;
$.ajax({
type: "POST",
url: "updateNotes.php",
data: {notes:notesVal , id:id, itemId:itemVal},
success: function(msg) {
$('#'+id).html(msg);
}
})
});
</script>
updateNotes.php:
<?php
include('db_connect.php');
include('order_functions.php');
$email = $_SESSION['username'];
$cartId = getcartid($mysqli, $email);
$notes = $_POST['notes'];
$itemID = $_POST['itemId'];
$query = "UPDATE `rel` SET `notes` = '$notes' WHERE `cart_id` = '$cartId' && `id_item` = '$itemID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if(result) {
return "Notes Updated";
}
?>
You forgot the $ in your last if-statement in your php-code and you should use "echo" (or likewise) instead of "return" as you are not in a function.
<?php
include('db_connect.php');
include('order_functions.php');
$email = $_SESSION['username'];
$cartId = getcartid($mysqli, $email);
$notes = $_POST['notes'];
$itemID = $_POST['itemId'];
$query = "UPDATE `rel` SET `notes` = '$notes' WHERE `cart_id` = '$cartId' && `id_item` = '$itemID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result) {
echo "Notes Updated";
}
?>
Your html/javascript-code is a bit wrong. This is how i guess you wanted it to work:
<div id="<?php echo $item_id; ?>_div">
<textarea id="<?php echo $item_id; ?>_textarea" data-id="<?php echo $item_id; ?>"><?php echo htmlentities($notes); ?></textarea>
</div>
$('#<?php echo $item_id; ?>_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "updateNotes.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
success: function (msg) {
$('#' + id + '_div').html(msg); //Changes the textarea to the text sent by the server
}
});
});
Good luck
I have a two jquery function to bring ratings and comments separately from two files which is working fine.
Now i want to do it in a single ajax call, i am trying to merge two function together this way but its not working.
jquery
function get_review(){
$.ajax({
type: "POST",
url: '../review.php',
data: {value1:value1, value2:value2, value3:value3},
dataType: 'json',
cache: false,
success: function(data)
{
var x = data[0];
var rating = (x-0.5)*2
var y = (20 * rating)+40;
$('#urating').css("backgroundPosition","0%" +(y)+ "px");
$('#comments').html(data);
}
});
};
PHP
$find_data = "SELECT * FROM $tablename WHERE table_name='$table' AND product_id='$id' ORDER by id DESC";
$query = mysqli_query($connection, $find_data);
$find_data2 = "SELECT * FROM $tablename2 WHERE id='$id'";
$query2 = mysqli_query($connection, $find_data2);
$row2 = mysqli_fetch_assoc($query2);
header('Content-type: application/json');
echo json_encode($row2);
?>
<?php while($row = mysqli_fetch_assoc($query)):?>
<div class="comment-container">
<div class="user-info"><?php echo $row['user_name']; ?></div>
<div class="comment"><p><?php echo $row['quick_comment']; ?></p></div>
</div>
<?php endwhile;?>
Please see and suggest any possible way to do it.
Thanks.
Try to encode whole response to JSON object!
Something like:
$response = array(
'success' => true,
'object' => $yourobject_or_array,
'html' => '<b>Bla bla</b>'
);
echo json_encode($response);
die();
JS:
function(response) {
var res = false;
try {
res = jQuery.parseJSON(response);
} catch(e) {}
if (res && res.success) {
// Use res.object and res.html here
}
}