For each li menu, send attributes by post - javascript

So i have this database:
And then i have a php script to create a simple menu, with the 'local' column.
$query = "SELECT * FROM credenciais_sensores where ambiente = '1'";
$results = mysqli_query($conn, $query);
<ul class="treeview-menu">
<?php
foreach ($results as $result){
$local = $result['local'];
$local = substr($local,0,7);
echo "<li><a class='post' href='#'>".$local."</a></li>";
}
?>
</ul>
On the query i select all info, but i only display the 'local'. Now, when i click on one of the items from the menu, i want to somehow send the info of that row by post to another page, without triggering a reload on the page. I know i can do this with GET, but i dont want to show the info on the URL.
I want to send the 'oxi_sensorid' and 'oxi_apikey' by post to another page. Ive tried using jquery post, but i cant get the items to display on the other page...
This is the menu i get printed:
Now, for example, when i click "Pipo 01" i want to send the Pipo 01 oxi_apikey and oxi_apikey by post with javascript to another file, for example getData.php. Ive tried using ajax to post all data to the getdata.php file but the getdata.php is not receiving them...

First, you need to modify your php script:
echo "<li><a class='clsPostData' data-sensorid='".$result['oxi_sensorid']."' data-apikey='".$result['oxi_apikey']."' href='#'>".$local."</a></li>";
And your Jquery code:
$(function(){
$('.clsPostData').click(function(e){
e.preventDefault();
var objPost = {};
objPost.api = $(this).data('apikey');
objPost.sensor = $(this).data('sensorid');
$.ajax({
url: 'getData.php',
type: 'post',
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});
});
});
Your getData.php script:
<?php
$apikey = $_POST["api"];
$sensorid = $_POST["sensor"];
$response["message"] = "Grettings from php, we receive your sensorid: ".$sensorid;
echo json_encode($response);
?>

Related

Update MYSQL Table On Div Click using Ajax - No Page Refresh?

I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as 'Online' or 'Offline' and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here's my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = #$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there's a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
From what i see, the reason why no alert pops up nor nothing gets updated is because of the onclick() on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as $profile['online_status']; is a string.
If you had debugged your code, you should see an error pointing towards the onclick() line
Change this
onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
To
onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements
pass data to PHP file
data: { id: id },
add a database connection to your PHP file
<?php
$var = $_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
If you still see any errors then press F12 and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file's response, hope it helps

Ajax And PHP : Handling Multiple Posts in A Single Page

I am developing a webpage where multiple posts from the Database is shown one by one in a single page much like twitter or facebook.
I need to use Ajax for comments and likes. The comment system should be nested as well.
The problem I am having is each post is having a unique post_id and I need to transfer it through Ajax for inserting the comments into the DB.
The below HTML is inside a PHP for loop for getting the posts from Database. So I have given post_id as every comment element's id to get the unique post comment.
<script>
function addcomment(abc) {
var temp1 = abc;
var post_id = temp1.value; // POST ID
var comment = document.getElementById(post_id).value;
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
post_id:post_id,
comment:comment
},
success: function(response) {
document.getElementsByClassName(post_id).innerHTML = response;
}
});
}
</script>
<div class="comment_section" id="comment_section">
<textarea type="text" id="<?php echo($post_id); ?>" placeholder="comment Here..." value=""></textarea>
<button id="comment_button" value="<?php echo ($post_id); ?>" onclick="return addcomment(this);">Comment</button>
<br>
<span class="<?php echo($post_id); ?>"></span>
</div>
And the addcomment.php looks like this:
<?php
include("connect.php");
$postid = $_POST['post_id'];
$comment = $_POST['comment'];
$sql1 = "INSERT INTO comments (name,comment) VALUES ('$postid','$comment')";
$result = $db->query($sql1);
$sql = "SELECT * FROM comments ORDER BY id DESC LIMIT 0,1";
$result1 = $db->query($sql);
while($row = $result1->fetch_assoc()) {
$post = $row['name'];
$comment_op = $row['comment'];
?>
<?php echo $comment_op; ?>
<br>
<?php echo $post; ?>
<?php } ?>
How can I get the comment when the Comment button clicked and store it in the DB and return the Comment below the comment area using AJAX ?
For display comments on specific post first you create comment section and use
<section id="comments-post_id"></section>
when you successfully add comment via above ajax request code get the response and create comment html and append in your comment section.
$("#comments-post_id").html($response);
make sure you have already create your comment HTML in controller or in ajax file where you get the response.
and for the rendering all post data user inside loop or recursive function to get all comments of your specific post
Need more help feel free and ask :)

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
index.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<div id="container">
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
</div>
<button id="loadMore">Загрузить ещё...</button>
<script src="/jquery-1.11.3.min.js"></script>
<script src="/script.js"></script>
item.php
<?php
class Item
{
public $id;
public $text;
function __construct($id = null, $text = null)
{
$this->id = $id;
$this->text = $text;
}
public function show()
{
return $this->text;
}
}
loadmore.php
<?php
$offset = 0;
$limit = 10;
$statement = $pdo->prepare('SELECT * FROM credit LIMIT ?, ?');
$statement->bindValue(1, $offset, PDO::PARAM_INT);
$statement->bindValue(2, $limit, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
$items = [];
foreach ($data as $item)
{
$items[] = new Item($item['id'], $item['tel']);
}
pdo.php
<?php
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
script.js
function getMoreItems() {
var url = "/loadMore.php";
var data = {
//
};
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
//
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
}
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
I think 2 hours and I can not understand.
Help.(
I understand your confusion, I believe you're wondering why your php code in index.php doesn't work properly after you call loadMore.php using ajax.
There's one distinction you need to understand to be capable of developing for the web. The difference between server-side and client-side code.
PHP is a server-side programming language, which means that it only executes on the server. Your server returns html, or json, or text, or anything to the browser and once the response arrives at the browser, you can forget about php code.
Javascript on the other hand is a client side programming language (at least in your case) It executes on the browser.
You basically have two options:
To send back some json and loop over it using jQuery, which is the preferable choice, but I fear it requires more work.
Send back html and append it to your page, first create a file called async.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
in your js add to your success callback
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
$('#container').append(res);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
don't forget var url = "async.php";
First you need to attach the buttons onclick="" attribute with the ajax-method.
<button ... onclick="getMoreItems">...</button>
Second, your loadmore.php need to require_once the files it depends on:
require_once('pdo.php');
require_once('item.php');
Third, separate your logic for querying the database to a function in the pdo.php file you can call with the limits as parameters, i.e.
function getData($offset = 0, $limit = 10){
//logic
}
You should also always try to use require_once or include_once to be sure files aren't loaded several times.
Now you can call the function getData(...) from index.php before the container div to load up the initial data, remove the include to loadmore.php from index.php, and in loadmore.php write the logic to use the parameters sent from the webpage to get the next chunk of data.
The data:... in your ajax needs to pass along the "page" it wants to get, perhaps simply a counter as to how many times you have loaded more. In the loadmore.php script you then just multiply the page by the limit to get the offset.
Return the data as JSON to the ajax, parse the JSON so you can build a new div for each item, then add each div to the container-div using javascript.
Im not going in detail on all topics here, but you at least will know what tutorials to search for on google :)

Trying to print onto an html page via PHP

I'm making a custom WYSIWYG editor with a save function, and through the save function I have run some code to get everything within a certain div, save it into a data table or overwrite it. But right now, I'm trying to load the page back.
The process is as follows: you press the save button, and it runs a PHP script called save.php, which is seen below.
My issue is that I want it to load or echo the contents within a certain div on the original html page. How would I go about doing that? I need it to work like Javascript's innerHTML function, basically.
Below are the files I use, at least the relevant parts.
test.html:
<form method="post" name="blog-post" id="blog-post">
<input type="hidden" name="postID" value="1"><!--Get the post's id-->
<div class="blog-editor-bar">
<a href="#" data-command='save'
onclick="submitForm('save.php');">
<i class='fa fa-save'></i>
</a>
</div>
<div id="blog-textarea" contenteditable>
</div>
<textarea style="display:none;" id="blog-post-cont" name="post-content"></textarea>
</form>
test.js:
function submitForm(action){
var theForm = document.getElementById("blog-post");
theForm.elements("post-content").value = document.getElementById("blog-textarea").innerHTML;
theForm.action = action;
theForm.submit();
}
save.php:
$conn = mysqli_connect('localhost', 'root', '', '');
if (mysqli_connect_errno()){
echo "<p>Connection Failed:".mysqli_connect_error()."</p>\n";
}
//store stuff in database
//Get Variables
$postid = $_POST['postID'] ? $_POST['postID'] : null;
$post = $_POST['post-content'] ? $_POST['post-content'] : null;
//if exists, overwrite
if($postid != null || $postid != ""){
$sqlSave = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rSave = mysqli_query($conn, $sqlSave) or die(mysqli_error($conn));
if(mysqli_num_rows($rSave)){
$sqlOverwrite = "INSERT INTO wysiwyg.post(post) VALUES(?) WHERE idpost = ?";
$stmt = mysqli_prepare($conn, $sqlOverwrite);
mysqli_stmt_bind_param($stmt, "sd", $post, $postid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
newSave();
}
loadSave();
}
function newSave(){
$sqlNewSave = "INSERT INTO wysiwyg.post(post) VALUES(?)";
$stmt = mysqli_prepare($conn, $sqlNewSave);
mysqli_stmt_bind_param($stmt, "s", $post);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
function loadSave(){
$sqlLoad = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rLoad = mysqli_query($conn, $sqlLoad) or die(mysqli_error($conn));
//This is the part I'm stuck on
}
Thank you all in advance for helping me out! I've been stuck on it for at least a few hours!
EDIT: Before people comment on SQL Injections, I have taken it into consideration. This is me getting the code working on my localhost before I run it through a ton of anti-sql injection methods that I have already done in the past. The code i provide is only important to the functionality at this point.
EDIT #2: The anti-injection code already exists. I guess i seem to have forgotten to provide that information. I repeat, the code I have provided here is only code relating to functionality. I have escaped the strings, trimmed, etc. and more, but that code is not necessary to provide for people to get an understanding of what it is i am trying to do.
You can use an AJAX request to communicate with the server, send data and receive a response. There are many good tutorials out there, but since I first learned it in W3Schools website I am going to refer you there.
JavaScript tutorial.
jQuery tutorial.
You can use an AJAX request which is written like this:
<script>
$(document).ready(function(){
$.ajax({ //start an AJAX call
type: 'GET', //Action: GET or POST
data: {VariableName: 'GETvalue'}, //Separate each line with a comma
url: 'Destination.php', //save.php in your case
success: function(data)){ //if values send do this
//do whatever
}
}); //end ajax request
});
</script>
This allows you to send information to your php page without refreshing
So in my example you can do this on the PHP side
<?php
echo $_GET['VariableName'];
?>
Will echo out "GETvalue as specified in the data section of the Ajax call"
EDIT************
In the AJAX call you can add dataType if you want json
$.ajax({
type: 'GET',
data: {VariableName: 'GETvalue'},
dataType: 'json' // Allows Json values or you can change it to whatever you want
url: 'Destination.php',

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

Categories