can someone help me how to get rid the counts or number on notification after I read or open it... I hope you understand, sorry if its vague and to my bad English tho. Just here my sample codes..
/index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
$('#notification_count').html(msg);
}
function waitForMsg(){
$.ajax({
type: "GET",
url: "select.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function(){
waitForMsg();
});
</script>
</head>
<body>
<span id='notification_count'></span>
Notifications
<div id="HTMLnoti" style="textalign:center"></div>
<br>
<p style="font-weight: bold; font-size: 20px; font-family: Tahoma;">Admin panel</p>
<form action="index.php" method="post">
<input type="text" required name="notification" autofocus="on" autocomplete="off">
<br>
<br>
<input type="text" name="status" value="unread" style="display: none;">
<input type="submit" name="btnsub" value="Submit">
</form>
and then my /select.php where why my notification counts..
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "messageTest";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from messageTest where status = 'unread'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>
please! all I want is get rid of the counts on the notification after
the user open or read it. Thanks!
my database name = "messageTest" my database table =
"messagetest" inside my table =
id notification status
If you don't want to show the count if there are no unread values, you simply don't show it. Easy as that.
if ($count > 0) {
echo $count;
} else {
// Do nothing
}
You may also want to consider checking out some basic programming tutorials.
When you are displaying the notification count:
$count = $result->num_rows;
echo ($count > 0) ? $count : 0;
Now call the addmsg function only when the count is not == 0 meaning there actually are some unread notifications.
success: function(data){
if(data >0){ // unread notification
addmsg("new", data);
}
setTimeout(
waitForMsg,
1000
);
}
Now your notification link has a
onclick = "return getNotification()"
You would not need the return keyword. You can now have the ajax function as:
function getNotification(){
$.ajax({
type: "GET",
url: "notification.php",
success: function(data){
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
}
});
};
Now your notification.php should handle the update query by something like:
//Connection part
$sql = "UPDATE messageTest Set status = 'unread'";
$conn->query($sql);
echo 1;
$conn->close();
However, there is a lot more efficient way to handle this, just trying to fit the code you already have in place. You would not need separate pages for each ajax call. You can create all of them in a single file and create different functions. Try searching for php ajax notification example.
Related
After i searched for this solution on this site, nothing i found. Here is basic php code, just for testing.
index.php
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data)
{
//alert(data);
window.location.reload();
}
});
});
});
</script>
qry.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if($_REQUEST['chk'] == true){
$stok = '1';
}
elseif ($_REQUEST['chk'] == false) {
$stok = '0';
}
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
How to set checkbox checked true or false into mysql and then echo if in html? It's always set to 0 in mysql boolen.
<input type="hidden" name="chk" id="chk" value="1" <?php if ($checked == '1') {echo 'checked';} else {} ?>/>
I tried everything from this site and nothing works.
Try this Jquery. This will get rid of the always value 1 problem you're having. What this code does is when you click on the "submit" button it check the status of your check box. If the check box is checked then the code will take the checked check box value and send that in the ajax function if it's not checked then the value 0 get assigned and that will be sent using the ajax.
Doing this will reduce the work has to be done by the back end PHP. I also made some changes to your PHP code as well.
$(document).ready(function() {
$(document).on('click', '#submit', function() {
if ($("#chk").is(":checked")) {
var chk = $('#chk').val();
}else{
chk = 0;
}
$.ajax({
url: "qry.php",
method: "POST",
data: {
check: chk
},
success: function(data) {
//alert(data);
window.location.reload();
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
You will see that the way I'm inserting the data is a bit different from the way you have done. I'm using mysqli_ prepared statements which makes SQL injection a hard to do.
$query = $connect -> prepare("INSERT INTO test(checked) VALUES (?)";
$query -> bind_param("i", $_REQUEST['check']);
if ($query -> execute()) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
jsFiddle if you want to test it.
You write the value into check, but read it back from $_REQUEST['chk']. That won't work. Change that to $_REQUEST['check'].
You are using val() to get the state of the checkbox, you should use checked.
Also, you are possibly open to SQL injection, start using prepared statements.
Add another line while sending the AJAX request.
While sending the value of checkbox, send 1 or 0.
It will reduce our work at PHP end.
So, the code should be:
var check = $('#chk').is(":checked");
check = (check) ? 1 : 0;
Final code should be:
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
check = (check) ? 1 : 0;
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data) {
//alert(data);
window.location.reload();
}
});
});
});
</script>
And PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
$stok = $_REQUEST['chk'];
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
}
else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
I am working on a chrome extension (freshment) and have a little problem.
I have a button, and I want that when button is clicked, to show my information from my database on my extension page.
HTML :
<button class="button" id="show" style="vertical-align:middle" onclick="myAjax()"><span>Show my purchaes</span></button>
<div id="showhere">
//this is where i want to show the info
</div>
Java Script :
$(document).ready(function(){
function myAjax() {
$.ajax({
url:"http://127.0.0.1/show.php",
data:{ action:'showhere' },
method:"POST",
success:function(data) {
('#showhere').html(data);
}
});
}
});
PHP :
<?php
if($_POST['action'] == 'showhere') {
$servername = "localhost";
$username = "root";
$password = "********";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ProductName, Amount, Date, WebStore FROM budget";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ProductName"]."</td><td>".$row["Amount"]."</td><td>".$row["Date"]."</td><td>".$row["WebStore"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
?>
What I want it to do is pretty simple : I have a button and below I have a div called : "showhere", and in this div I want to take mysql info and write it.
your write i didnt write the exact problem, the problem is that the button doesnt do anything.
agian , thx!
I suggest you set it this way:
$(document).ready(function() {
$('#show').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "http://127.0.0.1/show.php",
data: {
action: 'showhere'
},
method: "POST",
success: function(data) {
('#showhere').html(data);
}
});
});
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I made a simple application php & ajax and I don't know why it is not working.
My code:
<?php
$grId = $_GET["groupId"];
$limit = $_GET["limit"];
if ($limit <= 0) {
$limit = 10;
}
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "productsdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, displayName, role, groupId FROM user where groupId = ? limit ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $grId, $limit);
$stmt->execute();
$stmt->bind_result($id, $displayName, $role, $groupId);
$users = array();
while($stmt->fetch()) {
$user = new StdClass();
$user->id = $id;
$user->displayName = $displayName;
$user->role = $role;
$user->groupId = $groupId;
array_push($users, $user);
}
echo json_encode($users);
$stmt->close();
$conn->close();
?>
json-client-get.html:
<html>
<head>
<script src="jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$('#students').hide();
$("#getStudentsButton").click(function() {
$.ajax({
dataType: "json",
type: "GET",
url: "getStudentsJson.php",
data: {
groupId: 1,
limit: 7
},
success: renderTable
});
});
function renderTable(data) {
var trHTML = '';
$.each(data, function(i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.displayName + '</td><td>' + item.role + '</td> <td> ' + item.groupId + ' </td></tr>';
});
$('#students').append(trHTML);
$('#students').show();
}
});
</script>
</head>
<body>
Lista studentilor din grupul 1:
<div id="maindiv">
<table id="students" border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Role</th>
<th>GroupId</th>
</tr>
</table>
</div>
<input id="getStudentsButton" type="button" value="Load students" />
</body>
</html>
I craete in phpmyadmin a new database productsdb with the table user and a single value inserted.
When I run localhost/folder/json-client-get.html and press the button Load student nothing is happening.
EDIT(picture with my db but I don't know why the photo is not working)
I tested your code and there is an issue with SQL which you have:
$sql = "SELECT id, displayName, role, groupId FROM user where groupId = ? limit ?";
check table structure and ensure which you have these fields
for sure run this query in your phpmyadmin and see result
SELECT id, displayName, role, groupId FROM user where groupId = 1 limit 7
This answer will not solve your issue but simply show you how to debug your ajax call. I think you will benefit more from knowing how to solve it than getting it solved.
Take a look at the following ajax call:
$(document).ready(function(e) {
$.ajax({
url: 'ajaxScript.php',
type: 'POST',
data: {
'somevar': 'somevalue'
},
success: function(result)
{
alert('Successfully called');
},
error: function(exception)
{
alert('Exeption:'+exception);
}
})
})
Everything works perfectly except the submit button typically takes three to four times before it works. So I'll have the necessary cid number, plug it into the form, and hit submit. It might work the first time, but it also might take me seven attempts. I've got a bit of a deadline on this thing, and I have no idea how to even go about troubleshooting this so any help at all would be hugely appreciated!
So I've got this form:
<form action="" onsubmit="redirect()">
<input type="text" name="val1" id="val1" placeholder="CID (ten digits)">
<br>
<input type="submit" value="Submit" id="submit">
</form>
Which triggers this javascript function:
function redirect() {
var userID = document.getElementById("val1").value;
var userID = userID.replace(/-/g, "");
//alert(userID);
//var userID = "9183179265";
$.ajax({
type: "POST",
url: './getNetworkType.php',
data: "userID=" + userID,
success: function(data) {
//alert(data);
if(data.indexOf("Search") > -1) {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_search.php?cid=" + data.substr(data.length - 10);
}
else {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_report.php?cid=" + data.substr(data.length - 10);
}
}
});
}
Which executes this script:
<?php
$val1 = $_POST['userID'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql3 = "SELECT * FROM account_type WHERE cid ='" . $val1 . "'";
$result3 = $mysqli->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
echo $row3["network"];
}
}
?>
I think the problem is in your function onsubmit.
You should try something like this.
Set ID to form to example "myForm". Remove onsubmit from Form.
And add this code. This should send data successfull and avoid the submit that you don't won't.
$("#myForm").submit(function() {
redirect();
return false; // this avoid submit.
});
How can i update the database by adding users choices? I have two fields in the database for this purpose, when the user click on yes, it updates the (useful) field and (not_useful) if clicked on no button. I am very new on javascript, so please be patient! :) I appreciate any help in advance.
PHP
<?php
require 'db/conn.php':
$id = (int)$_GET['id'];
if($result = $db->query("SELECT * FROM table_user WHERE table_user_id = $id")){
if($result->num_rows){
while($row = $result->fetch_assoc()) {
echo "
<div class='rating'>
<center>
<p>Are you alrite " . $row['table_user_name'] . "?</p>
<div>
<button type='button' id='yes'>Yes</button>
<button type='button' id='no'>No</button>
</div>
</center>
</div>
<div class='1' style='display:none;'>Text YES</div>
<div class='2' style='display:none;'>Text NO</div>
";
}
}
}
?>
JS
$(document).ready(function(){
$("#yes").click(function(){
$(".rating").hide();
$(".1").show();
});
$("#no").click(function(){
$(".rating").hide();
$(".2").show();
});
});
You can't connect your mySQL database directly with JavaScript from client browser. Event if it would be possible you really don't want to do that because you would have to include mysql login credentials into your JavaScript which is served to client computers.
Of course you could use database like LocalStorage from within JavaScript but these databases are on client computer. If I got it right thats not what you are looking.
You have to send the data to a script on your server which then insert them into your mySQL database. As you stated you don't like the browser to reload to just submitting a form is not an option. In these cases AJAX is used. You will find several tutorials how to send data with JavaScript / JQuery using AJAX to your server.
On server side you could handle for example with a php script. The code you have posted to your question is not PHP but simple HTML. Fred -ii- posted some sample SQL statements to increment a column. I would recommend you to use PHP PDO with mysql driver as this helps you to prevent security issues.
After some working hard, i found a solution. Sharing for those who is facing similar problem. This was my solution. Anyways, have fun! ;)
I think there's a better way to organize the JS script to interact with the php files which manage the sql scripts. If someone would like to help optimize it, will be welcome.
PHP main
<?php
require 'db/conn.php':
$id = (int)$_GET['id'];
if($result = $db->query("SELECT * FROM table WHERE user_id = $id")){
if($result->num_rows){
while($row = $result->fetch_assoc()) {
echo "
<div class='rating'>
<center>
<p>Are you alrite " . $row['user_name'] . "?</p>
<div id='rating-div'>
<a href='#' id='yes' class='custom-btn'>Yes</a>
<a href='#' id='no' class='custom-btn'>No</a>
<input type='hidden' id='" . $id . "' />
</div>
</center>
</div>
";
}
}
}
?>
JS
$(function(){
$('#yes').on('click', function(e){
e.preventDefault();
var usr_id = $('#rating-div input').attr('id');
$.ajax({
url: 'db/rating-yes.php',
type: 'post',
data: {'action': 'rating', 'usr_id': user_id},
success: function(data, status){
if(data == "ok"){
$('.rating').html('<p>Nice!</p>');
}//end of if
},//end of success function
error: function(xhr, desc, err){
console.log(xhr);
console.log("Details: " + desc + "\nError: "+ err);
}
});//end of ajax
}); //end of onclick function
}); //end of main function
$(function(){
$('#no').on('click', function(e){
e.preventDefault();
var usr_id = $('#rating-div input').attr('id');
$.ajax({
url: 'db/rating-no.php',
type: 'post',
data: {'action': 'rating', 'usr_id': user_id},
success: function(data, status){
if(data == "ok"){
$('.rating').html('<p>Oh no! :(</p>');
}//end of if
},//end of success function
error: function(xhr, desc, err){
console.log(xhr);
console.log("Details: " + desc + "\nError: "+ err);
}
});//end of ajax
}); //end of onclick function
}); //end of main function
PHP rating-yes
<?php
$rating = $_POST['action'];
$user_id = $_POST['usr_id'];
if($rating == "rating") {
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('your_database');
if(mysql_query("UPDATE table SET useful = useful + 1 WHERE user_id = $user_id")){
echo "ok";
}
}
?>
PHP rating-no
<?php
$rating = $_POST['action'];
$user_id = $_POST['usr_id'];
if($rating == "rating") {
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('your_database');
if(mysql_query("UPDATE table SET not_useful = not_useful + 1 WHERE user_id = $user_id")){
echo "ok";
}
}
?>