refresh a SQL query to display changes - php

I have the following query:
if (!isset($profile_id) || !is_numeric($profile_id))
return false;
if ( isset(self::$newMessageCountCache[$profile_id]) )
{
return self::$newMessageCountCache[$profile_id];
$filter_cond = SK_Config::section('mailbox')->section('spam_filter')->mailbox_message_filter ? " AND `m`.`status`='a'" : '';
$query = "SELECT COUNT(DISTINCT `c`.`conversation_id`)
FROM `".TBL_MAILBOX_CONVERSATION."` AS `c`
LEFT JOIN `".TBL_MAILBOX_MESSAGE."` AS `m` ON (`c`.`conversation_id` = `m`.`conversation_id`)
WHERE (`initiator_id`=$profile_id OR `interlocutor_id`=$profile_id)
AND (`bm_deleted` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_deleted` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
AND (`bm_read` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_read` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
$filter_cond AND `m`.`recipient_id`=$profile_id
";
self::$newMessageCountCache[$profile_id] = SK_MySQL::query($query)->fetch_cell();
return self::$newMessageCountCache[$profile_id];
This will return a number for any new mailbox messages, I have found an ajax code for checking if there is a change.
Code:
var previousValue = null;
function checkForChange() {
$.ajax({
url: '',
...
success: function(data) {
if (data != previousValue) { // Something have changed!
//Call function to update div
previousValue = data;
}
}
});
}
setInterval("checkForChange();", 1000);
But I really need to figure out how to update the query without refreshing the entire page? I figured maybe something with ajax can help but I am totally new to ajax and I don't have an no idea where to start.
Update: ok so I wrote a php script for the queries but not sure how to get ajax script to use my "emails" var.
here is the script.
<?php
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
die();
}
include("..\internals\config.php");
$host = DB_HOST;
$user = DB_USER;
$password = DB_PASS;
$dbname = DB_NAME;
$prefix = DB_TBL_PREFIX;
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db($dbname, $cxn);
function get_user_id()
{
$userid = NULL;
if (!empty($_COOKIE['PHPSESSID']))
{
$result = $cxn->execute("
SELECT profile_id
FROM " . TABLE_PREFIX . "profile_online
WHERE hash = '" . $cxn->escape_string($_COOKIE['PHPSESSID']) . "'
");
if ($row = $cxn->fetch_array($result))
{
$userid = $row[0];
}
}
return $userid;
}
$profile_id = get_user_id();
public static function newMessages( $profile_id )
{
if (!isset($profile_id) || !is_numeric($profile_id))
return false;
if ( isset(self::$newMessageCountCache[$profile_id]) )
{
return self::$newMessageCountCache[$profile_id];
}
// check config for filter condition
$filter_cond = SK_Config::section('mailbox')->section('spam_filter')->mailbox_message_filter ? " AND `m`.`status`='a'" : '';
$query = "SELECT COUNT(DISTINCT `c`.`conversation_id`)
FROM `".TBL_MAILBOX_CONVERSATION."` AS `c`
LEFT JOIN `".TBL_MAILBOX_MESSAGE."` AS `m` ON (`c`.`conversation_id` = `m`.`conversation_id`)
WHERE (`initiator_id`=$profile_id OR `interlocutor_id`=$profile_id)
AND (`bm_deleted` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_deleted` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
AND (`bm_read` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_read` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
$filter_cond AND `m`.`recipient_id`=$profile_id
";
self::$newMessageCountCache[$profile_id] = SK_MySQL::query($query)->fetch_cell();
return self::$newMessageCountCache[$profile_id];
}
mysql_close($cxn);
$emails = newMessages();
?>

Ajax is correct - with Ajax you can send a request to the webserver which will execute your query and receive a request.
Its like visiting a page with the browser except that it happens in the background and not reloading the browsertab/page.
Lets say this is your file query.php and you can access it via my-domain.tld/query.php
query.php:
//First make this file only executeable for AJAX-Requests but no regular visit via browser:
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
die(); //User tried to enter query.php with a browser or similar...
}
//call function where query is stored or put your query here and save result
//Its important to echo what you want to be returned in the ajax-request.
echo self::$newMessageCountCache[$profile_id];
die(); //Best is die after last echo to make sure there are no extra outputs!
Now in your template or atleast where your HTML code is:
function checkForChange() {
$.ajax({
url: 'my-domain.tld/query.php', //See, here is the URL to your file on server
data: {}, //You need this only if you want to mpass any variables to your script. On PHP Server-side this data are available via $_POST array!
success: function(data) { //data contains all echo'ed content from query.php
$(".mailbox_messages").html(data); //The best is make your container to be updated to a class or ID to access. Its content can be overridden with .html() function. Simply echo all contents in query.php that you want to be displayed in your element and override the content with .html(data);
}
});
}
Now you just need to call checkForChange() when something special happens like a button click for example:
<input type="button" id="refresh-mailbox" value="Refresh my Mailbox" />
<script type="text/javascript">
$("#refresh-mailbox").on("click", function() {
checkForChange(); //Execute your function on button click and done!
});
</script>
I hope this helps. :)

Related

PHP - AJAX - is it possible to generate HTML using PHP and return that to AJAX to replace the contents of a <div>

I am working on a web application where it allows you to post a simple comment to the database on a form submit, what I want to do is generate a new list of all comments written and use AJAX to replace a div where comments are to be stored, this to show the newest written comment after submitting it.
$(document).ready(function() {
$('#postCommentForm').submit(function (e)
{
e.preventDefault();
console.log("JS Submitted");
function addCommentAJAX_call(commentTitleBox,commentBox,source_name,place_id,city_id)
{
$.ajax(
{
url : "funcsAJAX.php",
type : "post",
dataType : "json",
data : {
'commentTitleBox' : commentTitleBox,
'commentBox' : commentBox ,
'source_name' : source_name ,
'place_id' : place_id ,
'city_id' : city_id
},
success : function(response)
{
console.log(response);
$('#g').html(response);
},
});
}
var commentTitleBox = $('#commentTitleBox').val();
var commentBox = $('#commentBox').val();
var source_name = $('#source_name').val();
var place_id = $('#place_id').val();
var city_id = $('#city_id').val();
addCommentAJAX_call(commentTitleBox,commentBox,source_name,place_id,city_id);
});
});
This is the jQuery code I use to pull data from the form and post it to the webserver, note that the success part is unfinished as it never fired for me, #g is the div which contents I want to replace.
Next is the handler for the AJAX call
extract($_POST);
#addCommentAJAX_call handler
$user = 'user';
$pass = 'pass';
try
{
$db = new PDO('mysql:host=localhost;dbname=twincities;charset=utf8',$user,$pass);
}
catch(PDOException $e)
{
die("<h3>connection to be failed, not surprising really heres why ".$e->getMessage());
}
addComment($db,$city_id,$place_id,$commentTitleBox,$commentBox,$source_name);
$allComments = showCommentsForAJAX($db,$city_id,$place_id);
$db->connection = null;
echo json_encode($allComments);
This will create PDO object and then addComment() will add the comment to the database, it works fine with no issues.
showCommentsForAJAX() is the function I want to use that returns the comments from the database
function showCommentsForAJAX($db,$cityID,$placeID)
{
try
{
if($cityID && $placeID)
{
$query = "select * from comment where place_place_id = :place_place_id and city_city_woeid = :city_city_woeid";
$queryVars = ['place_place_id' => $placeID,'city_city_woeid' => $cityID];
}
else if($cityID)
{
$query = "select * from comment where city_city_woeid = :city_city_woeid";
$queryVars = ['city_city_woeid' => $cityID];
}
$query = $query." ORDER BY `timestamp` desc";
$stmt = $db->prepare($query);
$stmt->execute($queryVars);
$returnHTML = "";
$returnHTML = $returnHTML . '<div id=comments>';
while($comment = $stmt->fetch())
{
$returnHTML = $returnHTML . '<div id=commentIDis'.$comment['comment_id'].'>
<h3>'.$comment['title'].'</h3>
<br>
<p>'.$comment['content'].'</p>
<br>
<p>-'.$comment['source_name'].'</p>
<br>
';
$returnHTML = $returnHTML . '</div>';
}
$returnHTML = $returnHTML . '</div>';
return $returnHTML;
}
catch(PDOException $e)
{
die("<h3> ROLLBACK something broke, not surprising really heres why ".$e->getMessage());
}
}
I want to based off the entries in the database, to build the comments' HTML and return that to AJAX, I am not sure how to encode the result for AJAX to understand it, and I believe that the logic for $returnHTML is incorrect and there is a better method of doing what I want but I am not sure how to achieve that, I have done a similar thing using Flask before where I used jinja templating to generate the HTML and successfully replace the contents of a div, but due to this university project I need to use PHP.
Suggestions to code layout are also very appreciated

Returning a variable from PHP to AJAX

how can I return a variable from a PHP query to AJAXA. I want the user to be redirected to the user panel using javascript after successfully entering the login and password. The query in PHP was successfully written but Ajax does not return any results.
Code Javascript:
$(document).ready(function() {
$("#btn-login").click(function() {
const loginAuth = $("#login-auth").val();
const passAuth = $("#pass-auth").val();
$.ajax({
type: "POST", //Request type
url: "http://localhost/game/login.php",
data: {
loginAuth: loginAuth,
passAuth: passAuth
},
cache: false,
success: function(data) {
console.log(data);
}
});
});
});
Code PHP:
<?php
require ('connect.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['loginAuth'])) {
// removes backslashes
$username = stripslashes($_REQUEST['loginAuth']);
// escapes special characters in a string
$username = mysqli_real_escape_string($con, $username);
$password = stripslashes($_REQUEST['passAuth']);
$password = mysqli_real_escape_string($con, $password);
// Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE login='$username'
and password='" . md5($password) . "'";
$result = mysqli_query($con, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if ($rows == 1) {
$_SESSION['username'] = $username;
// Redirect user to index.php
$arr = 'udało się';
header("Location: panel.php");
}
else {
$arr = false;
header("Location: panelLogin.php");
}
}
else {
}
echo json_encode($arr);
?>
Thank you very much for every help.
you cannot redirect the user from the php script that is being called from ajax call.
because it will redirect but not on your browser instance but the ajax one.
you need to redirect it from javascript.
so you can do
echo "true";
instead of
header("Location: panel.php");
and echo "false"; // in case login failed
as an example but you can print some json text and use more informative messages
and you can check these values from ajax success function then you can do
window.location.href = "the url you want to redirect to";

PHP/MySQL/AJAX - Refresh query values with AJAX

I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.

Why isn't my pdo mysqli query working correctly from browser, but has correct behavior from Postman?

I'm currently working on a project where a user can subscribe on a class event. They have the event displayed in a calendar and when they click on it, there is a mysqli query executed:
INSERT INTO conduct_user
(user_id, conduct_id)
VALUES
(?, ?)
which subscribes the user for a class event. This works properly with no deviations.
However... When the user clicks a second time on the event, a second query is executed, which should unsubscribe the user from the event:
public function unsubscribe_from_class_event($userId, $eventId)
{
return "
DELETE FROM conduct_user
WHERE user_id = " . $userId . " AND conduct_id = " . $eventId . "
";
}
The above function returns and assigns a variable $sql:
$sql = unsubscribe_from_class_event($userId, $eventId);
It ($sql) in its turn is executed from the connection object $conn:
$result = $conn->query($sql);
if($result){
return true;
} else {
return false;
}
The strange thing is that whenever I execute this from Postman of Chrome, it works properly without any deviations.
However, when I execute it from the browser, it doesn't execute, even though in both cases "true" is returned.
Here is the repo of the project:
https://github.com/mirchev1977-practical-projects/unity-yoga
and below are the files with annotations to understand how the queries are executed. The steps are enumerated and described. Please follow the links and look for notes which will guide you into the flow of the request process. [UPDATE!!!] Here are the notes on github starting from 0.1, 0.2 ...
which will guide you through the code:
https://github.com/mirchev1977-practical-projects/unity-yoga/commit/153fa9c4d9907fd1e38f6a2d7d34649b14e3c457#diff-ca9644a4bcedb12a5bbbf1fbf744e496
Here is the relevant code:
file: src/angular/calendar/calendar.js
Here I call the function unsubscribeEvent(userId, eventId):
if (indexEvent == -1) {
eventsSubscribedOn.push(eventId);
event.attendees.length++;
} else {
unsubscribeEvent(userId, eventId);
event.attendees.length--;
var inx = eventsSubscribedOn.indexOf(eventId);
eventsSubscribedOn.splice(inx, 1);
}
In the same file is the function inself.
file: src/angular/calendar/calendar.js
function unsubscribeEvent(userId, eventId) {
var request = DbRequester.unsubscribeEvent(userId, eventId,
CONFIG.SERVER.CALENDAR_CONTROLLER_PATH,
Helpers.getSessionId(),
Helpers.getUserRole());
request
.done(function(data) {
console.log('success');
console.log(data);
if (data === 'exited') {
Helpers.logout();
return;
}
// Helpers.setLocalStorage(data);
})
.fail(function(data) {
console.log("error");
console.log(data);
// Helpers.logout();
});
}
It calls the method
$dbRequester.unsubscribeEvent = function(userId, eventId, serverPath, sessionId, userRole) {
return $.ajax({
url: serverPath,
type: 'POST',
dataType: 'json',
data: {submit_type: 'unsubscribe_event',
user_id: userId,
event_id: eventId,
session_id: sessionId,
user_role: userRole
}
});
}
from the file src/angular/db_requester.js .
This method $dbRequester.unsubscribeEvent
sends an ajax request to the php backend file:
src/server_files/controllers/calendar_controller.php
and its method:
if ( isset($_POST['submit_type'])
&& $_POST['submit_type'] == 'unsubscribe_event'
&& isset($_POST['user_role'])
&& ($_POST['user_role'] == 'admin'
|| $_POST['user_role'] == 'instructor'
|| $_POST['user_role'] == 'user') ) {
//set session
// $post_session = $_POST['session_id'];
// $sessionIsActive = sessionIsActive($post_session, 'not_as_array');
$sessionIsActive = true;
//set session
if ($sessionIsActive != false) {
$calendar = new CalendarObj(Db::getDb(), new Config());
$calendar->unsubscribeEvent($_POST['user_id'], $_POST['event_id']);
} else {
echo 'exited';
}
}
.
In it is created a CalendarObj
src/server_files/models/calendar/calendar_obj.php and its method
public function unsubscribeEvent($userId, $eventId)
{
$req = new RequesterCalendar();
//Into the class_conduction
$conn = $this->db;
$sql = $req->unsubscribe_from_class_event($userId, $eventId);
$result = $conn->query($sql);
if($result) {
echo 'true';
}
return null;
}
is called.
In it the object
$req = new RequesterCalendar();
is created and assigned to the $req variable.
Then
$req->unsubscribe_from_class_event($userId, $eventId)
is called:
its code is the following:
public function unsubscribe_from_class_event($userId, $eventId)
{
return "
DELETE FROM conduct_user
WHERE user_id = " . $userId . " AND conduct_id = " . $eventId . "
";
}
The $sql variable is assigned and the mysqli query executed on the next row:
$sql = $req->unsubscribe_from_class_event($userId, $eventId);
$result = $conn->query($sql);
Whenever I make this request from Postman
there is no problem.
If I make the request from the browser itself - it does not work.

Having an Ajax Save button and save in database

I'm currently doing a form whereby customers will have to do the survey form, I'll have a AJAX "Save" button to allow me to save the data into database when the customers did not managed to finish the form itself and then when the customers login again, the form which they did halfway will pop out again and ask them to continue finish the survey form.
Is it possible where AJAX/javascript/jQuery can work with php codes in it (because of the insert query)?
Not very sure with AJAX and all so Thanks for helping!
This is for the "Save" button.
<input type="button" onClick="save();" value="Save">
This is the insert query whereby it will be inserted in database.
<?php
include("dbFunctions.php");
$idQuery = "SELECT id,question,input FROM db_ExtApp1.scFormLayout WHERE surveyID ='$lastID'";
$idResult = sqlsrv_query($conn, $idQuery);
while ($row = sqlsrv_fetch_array($idResult)) {
$fcID = $row['id'];
$question = $row['question'];
$surveyTitle = $_SESSION['surveyTitle'];
$input = $row['input'];
if (isset($_POST['qns' . $fcID])) {
$answer = implode(",", $_POST['qns' . $fcID]);
$newAns = str_replace($singleQuote,$changeQuote,$answer);
} else {
$newAns = '';
}
if (isset($_POST['others'.$fcID])) {
$others = $_POST['others' . $fcID];
$newOthers = str_replace($singleQuote,$changeQuote,$others);
}else {
$newOthers = 'N.A.';
}
$connectionInfo['ConnectionPooling']=0; // this creates a new connection on the next line...
$newconn = sqlsrv_connect($serverName, $connectionInfo);
if ($input != 'Normal text line, no input required*') {
$query = "INSERT INTO db_ExtApp1.scFormResult(surveyID, answer, others, title, question, name)
VALUES ('$lastID','$newAns','$newOthers', '$surveyTitle','$question', '$name')";
$status = sqlsrv_query($newconn, $query);
} }
if ($status === false) {
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
You can use jquery $.ajax() to send data from client side to PHP. (eg)
$.ajax({
url : 'path/to/php/page',
data : { id : '1', name : 'name' },
dataType : 'JSON',
type : 'POST',
cache: false,
success : function(succ) {
alert(succ);
},
error : function(err) {
alert(err);
}
});
Then in PHP page, use $_POST[] to capture data and insert it into database.
$id = $_POST['id'];
$name = $_POST['name'];
Make sure you escape the values and make it safe for sql insert.

Categories