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
Related
Currently, I am developing a website, for my own purposes. I am a beginner at web developing so please understand me if I am not getting this correct. Please Help.
I have a code for javascript when clicking an html element button
for logging in. see code below:
$(document).ready(function(){
$("#login").click(function(){
var username = document.getElementById("username").value;
var pword = document.getElementById("password").value;
validateUser(username,pword);
});
});
function validateUser(user,pass){
var username =user;
var pword =pass;
var datasend = "username="+ username + "&password=" + pword;
$.ajax({
type:'POST',
url:'../bench/php/login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
alert("Hello World"); //Trying to pop up
$('#username').val('');
$('#pword').val('');
}
});
}
I successfully triggered the button for the second time I try to click it, and the hello world message will pop out, but it cannot redirect the page if it was successfully logged in using an account in MySQL in WAMP server. Here is the code in PHP below:
<?php
// require("php/config.php");
include("config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("Location: index.html");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");';
echo '}, 100);</script>';
}
}
?>
The problem is, the page does not redirect to the index.html even when the second click triggers the HELLO WORLD alert.
I don't know what I am doing wrong.
I don't why this is not working, I see the console, there is no error exist.
can someone help me with this? any help will much be appreciated. thanks and regards.
If you'd like to keep to using the AJAX setup you have at the moment (which is totally fine), what you'll need to do is to beef up the on-success function to read the returned results from your PHP.
A simple example
Instead of
header("Location: index.html");
write
echo "index.html";
exit;
and then add the following to your on-success function:
window.location.href = msg;
That will start to give you a flavour of how the relationship between an AJAX call and your PHP server should look like.
Next steps
Instead of having your AJAX return a string (index.html) have it
return an array of information, perhaps you want to welcome the user
with a personalised message?
You don't need to create a string (var datasend = "username="+ username + "&password=" + pword;) and feed that to your AJAX call, you can send an array.
Make sure your passwords are not stored in plain text on the server.
An ajax request will not follow the Location header of responses to redirect users.
You need to either redirect the user manually using JS in the success callback or change your form submission to use a classic HTML form
The first thing to make sure, PHP Redirect Header doesn't work when sending an Ajax Request.
So the solution to your problem is:
Change this part of your code in PHP file:
header("Location: index.html");
Into:
echo "Success";
exit();
And then in your Ajax Request Success Callback:
success:function(msg){
if (msg == 'Success') {
window.location = "/path/to/redirect";
}
}
Let me know if you have still confusion in this.
I have a list from the database and I want to implement edit functionality where in onclicking a table column, the column becomes editable and on clicking out of column, the value gets updated.
I have used AJAX for this purpose. My code is as under:
Page1.php
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
The column of my table is as under:
<td contenteditable="true" onBlur="saveToDB(this, 'exmid','<?php echo $p0; ?>')"
onClick="showEdit(this);"><?php echo $p3 ?>
Note: $p0 contains the serial no of row from mysql database table and $p3 contains the displayed text.
The code for page2.php is:
<?php
include_once 'includes/db_connect.php';
?>
<?php
$result = mysql_query("UPDATE examlist1 set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE sno=".$_POST["id"]);
?>
Problem:
When I click on the column it becomes editable. Using alert() inside saveToDB() I have checked that the function is called on clicking out of the column and also values of column and id are correct.
Then I tried the alert() function inside $.ajax and it was not called. I am not sure whether ajax is running or not. This is the first time I am trying to use ajax in a php code myself.
Please suggest what is the problem and what is the solution? The code is being implemented on a Linux based server hosted at Godaddy using PHP 5.4.
Also I would like to set the background color on fail. How to write it inside ajax block?
If you are getting the correct values when alerting.In your page2.php. Use mysqli instead of mysql and also use $connection object in mysqli_query().
<?php
include_once 'includes/db_connect.php';
$column=$_POST["column"];
$editval=$_POST["editval"];
$id=$_POST["id"];
$result = mysqli_query($connection,"UPDATE examlist1 SET $column='$editval' WHERE sno=$id");//$connection is database connection variable
if ($result)
{
echo json_encode(array('success'=>true));
}
else
{
echo json_encode(array('success'=>false));
}
?>
Here is Javascript: Try 100% works (Define what you want on if/else statement)
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
var res=eval(data);
//if success then
if (res.success)
{
//write JS code that you want after successful updation
$(editableObj).css("background","#FDFDFD"); //<- according to problem
}
//if fails then
else
{
//write JS code that you want after unsuccess
}
}
});
}
</script>
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);
?>
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',
So i am trying to make an asynchronous call of a PHP script but for some reason there is an error: Maximum call stack size exceeded that is making my site lagging a LOT. There must be a loop somewhere in my code but i can't really find it. I am looking for the past 3 days and still nothing. If someone could spot anything i would be really greatfull. Thanks in advance!
PHP code:
<?php
require_once 'li.php'; //File with the constants
$Username = $_POST['Username'];
$query = "SELECT Username
FROM user_info
WHERE Username = ?
LIMIT 1";
if($stmt = $conn->prepare($query)){ //Prepares the statement!
$stmt->bind_param('s', $Username);
$stmt->execute(); //Executes it!
if($stmt->fetch()){ //Checks if the query returns anything!
$stmt->close(); //If yes then closes the prepared statement!
$error = "Username taken";
echo $error;
}
}
?>
AJAX/JS code:
$(document).ready(function(){
$('#Username').on("keyup", function(){
$.ajax({
type: 'POST',
url: 'NameValidation.php', //Your required php page
data: { Username: Username }, //pass your required data here
async: true,
}).done(function(response){
if(response != ""){
$('#UsernameLabel').html("Username Taken!");
}
});
});
});
In case you didn't understand what i want to do with this code let me explain some more. I want every time the Username input changes to search if the username already exists in the database and alert the user by changing the Label text.
PS: Dont worry about SQL injection security i'll add that later when i fix this problem! ^-^
you are not closing connection if query returns nothing, try changing the code to :
if($stmt->fetch()){ //Checks if the query returns anything!
$error = "Username taken";
echo $error;
}
$stmt->close(); //close connection in any case