so i am trying to change my current design for an IoT porject i am experimenting with.
currently i am using "submit" as my button type but i don't like how the page refreshes.
so i did some digging online and found that ajax was my solution using the "button" type.
however i am very unfamiliar with jquery or ajax so im trying to do this.
currently this is my php function that captures the submit button.
if(isset($_POST['button']))
{
$id = $_POST['button'];
$sql = mysql_query("SELECT * FROM device WHERE Username = '".$_SESSION['Username']."' && DeviceID = '".$id."'");
$productCount = mysql_num_rows($sql);
if ($productCount > 0)
{
$row = mysql_fetch_array($sql);
$status = $row["Status"];
$et = "";
if($status == 1)
{
$et = "a";
$status = 0;
}
else
{
$status = 1;
}
exec("sudo python /var/www/html/light/script'".$id."''".$et."'.py");
mysql_query("UPDATE device SET Status = '$status' WHERE DeviceID = '$id'");
header( "refresh:0.01;" );
//ADD scripts here and also to capture data.
}
}
ignore the header(refresh) feature i was just trying to do a work around but nothing was satisfying my itch.
Any help or tips are greatly appreaciated
EDIT
also this is the button i have atm
<div class="col-md-2">
<button type="submit" name="button" id="button" value="'.$id.'" class="btn btn-default">Toggle '.$ddt.'</button>
</div>
you can use this post it may have what you are looking for and may help you solve your problem just check it out it seems to be talking about the same thing you are looking to do Post link
Related
Building a messaging system for my site and i have been stuck for days. I have this PHP link
<a href='user_msg.php?hash=$hash'>$name</a>
When you click on the link, it takes you to a page where you can send message to a user you've connected to (this connection is binded by the $hash)
in the page for sending the message, i hid the $hash in and hidden input value="$hash" and it sends the message to row in database with the $hash with the following scripts (They have no issue and work fine)
var msg_area = $('.msg_area');
msg_area.scrollTop(msg_area.prop("scrollHeight"));
$('#send_rep').submit(function (e) {
e.preventDefault();
var $form = $(this), url = $form.attr('action');
var posting = $.post(url, {rep_msg: $('#rep_msg').val(), hash: $('#hash').val()});
posting.done(function (data) {
alert('success');
});
});
PHP script to send
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['rep_msg']) && !empty($_POST['rep_msg']) || isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_GET['hash'];
$my_id = $_SESSION['log_id'];
$rep_msg = $_POST['rep_msg'];
$hash = $_POST['hash'];
$rsql = <<<EOF
INSERT INTO messager (message, group_hash, from_id) VALUES('$rep_msg', '$hash', '$my_id');
EOF;
$rret = $db->exec($rsql);
$ursql = <<<EOF
SELECT * FROM User WHERE ID = '$my_id';
EOF;
$urret = $db->query($ursql);
while ($urrow = $urret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urrow['fname'];
$from_img = $urrow['image'];
header('Location: user_msg.php?hash=' . $hash);
}
}
The above Ajax Request and php script work fone to sedn the messages to database.
The issue not is getting the messages from database
This is the script i am currently using (not working)
PHP script to get message
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_GET['hash']) && !empty($_GET['hash']))
{
$hash = (int)$_GET['hash'];
$us_id = $_SESSION['log_id'];
$mesql =<<<EOF
SELECT from_id, message FROM messager WHERE group_hash = '$hash';
EOF;
$meret = $db->query($mesql);
while ($merow = $meret->fetchArray(SQLITE3_ASSOC))
{
$from_id = $merow['from_id'];
$messages = $merow['message'];
$usql =<<<EOF
SELECT * FROM User WHERE ID = '$from_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urow['fname'];
$from_img = $urow['image'];
if ($from_id != $_SESSION['log_id']) {
echo "
<div class='from_bubble'><div class='from_img'><img src='$from_img'></div><div class='from_txt'><p>$messages</p></div></div>";
} else {
echo "
<div class='rep_bubble'><div class='rep_img'><img src='$from_img'></div><div class='rep_txt'><p>$messages</p></div></div>";
}
}
echo "<input style='display: none' type='text' class='hash' name='hash' value='$hash' id='hash'>";
}
}
Ajax Request
setInterval(function() {
$('.msg_area').load("get_msg.php");
}, 2000);
But the get is not working. I suspect fro some reason, its not getting the $hash. Please is there a solution to this or am i trying something impossible.
Any help would be appreciated. If more info is needed please ask. Thanks in advance
Maybe $hash = (int)$_GET['hash']; would be $hash = (int)$_POST['hash'];
And you have more than just one $_GET...
In your ajax request you are using POST so you will need to get the hash with the POST as well: if (isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_POST['hash'];
Using '' in PHP indicates the actual string you are writing.
If you want to use a PHP variable in a string you should use "", so try changing $name
Check this for more info:
http://php.net/manual/en/language.types.string.php
Then, how do you hide your hash in the input?
You could use <input value="$_GET['hash']" ... />
In the script to send , does it enter the if? Try adding statements to see if SQL returns any error.
Hope this helps.
Answer to the question was to create a PHP SESSION for the $hash($_SESSION['hash'] = $hash) and to use this session all over the site with session_start().
Hi guys so i have created a simple comment box for my site now. It works perfectly, however the problem i am having is that i have different pages which are going to require different comment box. I cant seem to figure out how to get the comment box to be unique for every page. So right now my database holds this :
Called comments:
id
comment
comment1
comment_date
Now my idea is that everything was stored into comment, so i added comment1 for other page to store the info. However i have no clue how to edit the php file to get it to work with comment1. Any help on this would be great.
HTML:
<div class="comment_container">
<div class="comments">
<?php
include_once("comments.php");
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
JS:
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
$.post("comments.php?action=post", {
comment: $('#comment_text').val()
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
PHP:
include_once("connect.php");
function convert ($date) {
$converteddate = date("F j, Y g:ia", strtotime($date." +1day"));
return $converteddate;
}
function getComments(){
$comments = "";
$sql = mysql_query("SELECT * FROM comments") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date ) VALUES ('".$comment."', now())");
return true;
}
if((isset($_GET['action'])) && ($_GET['action']== "post")){
postComments($_POST['comment']);
}
echo getComments();
Thanks again for the help
DISCLAIMER
For future visitors:
Don't copy this code, as it has several issues that go beyond answering the question.
What you need to add is an identifyer for the type of comment. (Type could be replaced with something more suitable to your case like 'product', 'user', ... whatever the difference is/what they are related to)
So in your database add that new column:
comments
--------
id
comment
type
comment_date
Now you need to pass around that type through all your calls, and it shall be specified in your 'HTML'-Page (which actually is php...).
<div class="comment_container">
<div class="comments">
<?php
// specify the type needed on that page
$type = 1;
include_once("comments.php");
echo getComments($type);
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
<script>
// specify the type in javascript
var type=1;
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
// add the type here:
$.post("comments.php", {
comment: $('#comment_text').val(),
type: type,
action: 'post'
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
</script>
and in comments.php:
//....some code left out here
function getComments($type){
$comments = "";
$sql = mysql_query("SELECT * FROM comments where type=$type") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment, $type){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date, type ) VALUES ('".$comment."', now(), ".$type.")");
return true;
}
if((isset($_POST['action'])) && ($_POST['action']== "post")){
postComments($_POST['comment'], $_POST['type']);
// send all the comments back to client
echo getComments($_POST['type']);
}
// moved to html-file: echo getComments($type);
NOTE
There are several issues with that code.
First don't use mysql functions. For real. Unsecure and deprecated/deleted as of php7. Use mysqli or pdo. Furthermore your sql can be hacked with sql injection. Read about prepared statements.
The general structure of that code is not very good.
Try to seperate output and formating from getting data.
For example it would be much better if a function called 'getComments' only would get the comments from the database, then let others decide what to do with that data. The less one function does the better.
Please read about coding styles, maybe start learning object oriented programming.
I hope this still helps you to get a clue of where to go!
I have a simple JavaScript function that will not allow a form to be submitted if all the fields are not filled out. On top of that I would like PHP to write out an error message next to just the fields that are empty. The problem is the function activates upon the $_POST and yet my JavaScript function will not allow for $_POST to occur as long as one of the fields are empty.
If I keep the action outside of the $_POST condition then the page will load with the error message already showing. I am fairly new to PHP and JavaScript and would like any insight on perhaps another available condition that I could use to trigger my error messages to appear in my form. I am also open to any other suggestions for error handling. I do prefer to keep my JavaScript present due to it's ability to keep the form from being submitted if it is not properly filled. Unless there is another way to take that action then I have to keep the JavaScript.
PHP:
function cleanCrew ($id, $pswrd) {
$id = stripslashes($id);
$pswrd = stripslashes($pswrd);
$id = strip_tags($id);
$pswrd = strip_tags($pswrd);
return array($id, $pswrd);
}
require_once 'dbServ.php';
$db_server = mysqli_connect($db_host,$db_user,$db_pass,$db_base);
if ($db_server) {
$error_1 = "";
} else{
$error_1 = "connection to database unsuccessful";
}
$error_2 = "";
$error_3 = "";
if ($_POST) {
$user_id = mysqli_real_escape_string($db_server, $_POST['userId']);
$user_pass = mysqli_real_escape_string($db_server, $_POST['pass']);
$id_and_pass = cleanCrew($user_id, $user_pass);
if ($user_id == "" || $user_id == null) {
$error_2 = "please fill in proper User Id";
} else{
$error_2 = " ";
}
if($user_pass == "" || $user_pass == null){
$error_3 = "please fill out password";
} else{
$error_3 = " ";
}
echo $id_and_pass[0];
echo $id_and_pass[1];
}
HTML:
<div id="intro">
<h1 id="the_blog" align="center">The <span id="blog_animate" style="position:relative;">Blog</span></h1>
<div id="log-in"><p id="log">Log In</p><br> <?php echo $error_1; ?>
<form action="blog.php" method="post" onsubmit="return checkForm(this)" name="form1">
<p id="log">User ID :</p> <input type="text" placeholder="johnnyApple175" name="userId"></input><?php echo $error_2 ?><br>
<p id="log">Password:</p> <input type="password" name="pass"></input><?php echo $error_3; ?><br>
<input type="submit" value="submit" class="button" ></input>
</form>
First:
It's always a very good idea to validate the data server side, like you're doing.
Reason is simple: Javascript is client-side and can easily be modified to e.g. bypass those checks. Also, good that you escaped the sent data prior using it in the Database query.
Your problem is, that you're checking for $_POST to exist - it always exists, it's a super global var. You actually want to check if it's empty:
if (!empty($_POST))...
You might want to think over it, if you really want to give detailed information what exactly was wrong. Giving more info is more user friendly, but it makes attacks easier, especially if you don't block the user after X retries.
I'm trying to create a validation for a form. When a user fills out the form, it is supposed to run a set of queries. The first is to check if a records already exists in the table. If it does exist, then it doesn't need to run the the next 2 queries, which are to INSERT and UPDATE.
I'm not sure what I am doing wrong, but the table already has an existing record. After checking the table, it still runs the INSERT and UPDATE queries. They should not fire. It should not do anything.
Here is my code: * I'm starting my code from the for loop, which is just taking an array of BOL numbers and CONTAINER numbers that the user manually selected. I exploded the array, but I will not show that code as I do not think it is necessary to show in this case *
<?php
for($i = 0; $i < $count; $i++)
{
$bolService = $bolArray[$i];
$conService = $conArray[$i];
$checkService = "SELECT * FROM import_service WHERE bol = '" . $bolService . "' AND container = '" . $conService . "'";
$checkSerRes = mysql_query($checkService);
$checkSerNum = mysql_num_rows($checkSerRes);
if($checkSerNum > 0)
{
$successService = false;
}
elseif($checkSerNum = 0)
{
$sql_query_string = mysql_query
("INSERT INTO import_service (bol, container) VALUES ('$bolService','$conService')");
$updateService = mysql_query ("UPDATE import_dispatch_details SET SERVICE = 'Y'
WHERE BOL_NUMBER = '$bolService' AND CONTAINER = '$conService')");
$successService = true;
}
}
// javascript fires an ALERT message in this next set of code
if($successService = true)
{
echo ("<script language='javascript'>
window.alert('Record has been saved')
window.location.href=''
</script>");
}
// if checkSerNum > 0, then it should skip the INSERT and UPDATE and fire the code below
elseif($successService = false)
{
echo ("<script language='javascript'>
window.alert('There was an error saving the record')
window.location.href=''
</script>");
}
?>
I'm not sure why this is not working correctly. I need this validation to work. I'm sure there is an alternative method, but this is what I got.
Please help me make this work.
Thank you in advance.
This elseif($checkSerNum = 0) needs to be elseif($checkSerNum == 0)
You're presently doing an assignment instead of a comparison.
Including if($successService = true) and elseif($successService = false) so add another = sign.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
http://www.php.net/manual/en/function.mysql-error.php
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
This isn't quite efficient (you are selecting * from your table, which you aren't using - waste of memory?). Why don't you do something like this:
for ($i = 0; $i < $count; $i++)
{
$bolService = $bolArray[$i];
$conService = $conArray[$i];
$recordExists = false;
$result = mysql_query("SELECT COUNT(*) AS recordCount FROM import_service WHERE bol = '" . $bolService . "' AND container = '" . $conService . "'");
if ($result) {
$row = mysql_fetch_assoc($result);
$recordExists = ($row['recordCount'] >= 1);
}
if ($recordExists)
{
$successService = false;
}
else
{
$sql_query_string = mysql_query
("INSERT INTO import_service (bol, container) VALUES ('$bolService','$conService')");
$updateService = mysql_query
("UPDATE import_dispatch_details SET SERVICE = 'Y'
WHERE BOL_NUMBER = '$bolService' AND CONTAINER = '$conService')");
$successService = true;
}
}
P.S. mysql_* is officially deprecated. Please use PDO or MySQLi. Also, your code is potentially open to SQL Injection.
Sorry for the constant question!! I have a table that displays records of data from my database. To make life easier, I have make it editable using jquery so that a user can click right an area an edit right away without redirecting to a different page.
A couple of questions.. how can i refine the below code so that when an area on the table with checkboxes and links is clicked, it will not respond/not editable?
Also, the editing function does not fully work at the moment and im having problems trying to figure out where the problem is. The table responds to everything defined in the jquery below but does not update my database.
There is my jquery code edit.js
$(function() {
$('tbody').on('click','td',function() {
displayForm( $(this) );
});
});
function displayForm( cell ) {
var column = cell.attr('class'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width'),
prevContent = cell.text()
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" value="'+prevContent+'" /><input type="hidden" name="id" value="'+id+'" />'+'<input type="hidden" name="column" value="'+column+'" /></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width',cellWidth);
cell.on('click', function(){return false});
cell.on('keydown',function(e) {
if (e.keyCode == 13) {//13 == enter
changeField(cell, prevContent);//update field
} else if (e.keyCode == 27) {//27 == escape
cell.text(prevContent);//revert to original value
cell.off('click'); //reactivate editing
}
});
}
function changeField( cell, prevContent ) {
cell.off('keydown');
var url = 'edit.php?edit&',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data) {
if (data.success)
cell.html(data.value);
else {
alert("There was a problem updating the data. Please try again.");
cell.html(prevContent);
}
});
cell.off('click');
}
And in my edit.php I have the following:
<?php
include ("common.php");
if (isset($_GET['edit'])){
$column = $_GET['column'];
$id = $_GET['id'];
$newValue = $_GET["newValue"];
$sql = 'UPDATE compliance_requirement SET $column = :value WHERE ComplianceID = :id';
$stmt = $dbh ->prepare($sql);
$stmt->bindParam(':value', $newValue);
$stmt->bindParam(':id', $id);
$response['success'] = $stmt->execute();
$response['value']=$newValue;
echo json_encode($response);
}?>
and finally my html..
<div class="compTable">
<table>
<thead><tr><th>Compliance Name</th><th>Compliance Goal</th><th>Compliance Description</th><th>Opions</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM compliance_requirement';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ComplianceID'].'">';
echo '<td class="crsDesc">'.$row['ComplianceName'].'</td>
<td >'.$row['ComplianceGoal'].'</td>
<td >'.$row['ComplianceDescription'].'</td>
<td ><a href =inviteObstacle.php?action=invite&id=name1> InviteObstacle </a></td>
<td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="query_myTextEditBox">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
Your help is much appreciated. thanks in advance
Simplest solution for identifying editable cells would be give those cells a class editable in your php output, then change your selector for td click handler to
$('tbody').on('click','td.ditable',function() {
As for updating database...need to determine if the ajax request from $.getJSON is being made. You can inspect this within browser console network tab. Also look for errors in console. Request ( if made) will show status, what is sent, what is returned etc
Need to use that as start point to help determine if preoblem lies in server code ( would get a 500 status) or in browser code.
If you provide live html sample ( not php ) from browser source view can create test demos to see what your javascript code is doing . Putting the html and javascript into jsfiddle.net and saving creates a demo that anyone can test out