Scenario: I'm trying to incorporate it so that when you click this button, it adds 1 to a value in the database.
I've read so many articles about AJAX today but no solution.
P.S. The query works fine directly from the command line.
This is what I've written so far but I think I'm completely missing something.
game.php
<script>
function logCountAdd(){
var request = $.ajax({
type: "GET",
url: "logCountAdd.php"
});
request.done(function(msg ) {
alert('Success');
return;
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
};
</script>
</head>
<body>
<button type="button" onclick="logCountAdd()">Gather Resources</button>
logCountAdd.php
<?php
$connection = mysqli_connect("localhost","root","","users");
if (mysqli_connect_errno())
{
echo 'NOT_OK';
}
mysqli_query($connection, "UPDATE uc_users
SET logCount = logCount + 1
WHERE user_name='Gregory'";)
mysqli_close($connection);
echo 'OK';
?>
Problem: After I click the button, the value in the database does not change.
The Error Code: GET logCountAdd.php 500 (Internal Server Error)jquery-1.11.2.min.js:4 m.ajaxTransport.sendjquery-1.11.2.min.js:4 m.extend.ajaxgame.php:7 logCountAddgame.php:22 onclick
First question asked on here, sorry guys!
mysqli_query($connection, "UPDATE uc_users
SET logCount = logCount + 1
WHERE user_name='Gregory'";)
^ misplaced semicolon
move it to after the close parenthesis. You may want to turn on error reporting to make debugging easier
error_reporting(E_ALL);
ini_set('display_errors','On');
Related
I am trying to work implement ajax due to maximum site load which PHP causes. But I am not aware of where I am making a mistake here. it is an anchor tag, when it is clicked the status of the particular row should be changed to a string which is hard coded.
PHP WAY
USERDETAIL.PHP
Next
Then it triggers This (IGNORE SQL INJECTION)
if(isset($_GET['changeStatus'])){
$id = $_GET['changeStatus'];
$user=$_SESSION['user'];
$sql = "select * from productOrder where id = ".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
$sql = "update productOrder set prodStatus = 'Ready', By='".$user."' where id=".$id;
if(mysqli_query($conn, $sql)){
header("Location:USERDETAIL.php");
}
}
}
According to this way, it works neat, but the userdetail.php would refresh anyways which is a lot time consuming. Then tried AJAX way is below.
Next
and that hits to
$(document).ready(function() {
$(".changeStatus").click(function(event){
event.preventDefault();
var status = "Ready";
var id = $(this).attr('data-id');
$.ajax({
url : 'action.php',
method : 'POST',
data : {status : status , id : id},
dataType: 'html',
success : function(response){
console.log(response);
}
});
});
});
and in the action.php it is (IGNORE SQL INJECTION AGAIN)
if(isset($POST['prodStatus'])){
$status = $_POST['prodStatus'];
$id = $_POST['id'];
$sql = "update productOrder set prodStatus= '$status' where id=".$id;
$result = mysqli_query($conn, $sql);
if($result){
return 'Updated';
}
}
The output is nothing happens. in the console it is just adding int values. I know I am making a mistake, or understood AJAX in a wrong way. it is just one button click and the string in SQL should be updated without an input text / modal. Please suggest what should be improved?
Also instead of having a seperate action php for these actions, can I do all these in userdetail.php itself with Ajax? is it possible?
Thanks in advance.
As B_CooperA pointed out, $POST should be $_POST.
Also, in $.ajax script data object your property name is status and in action.php you are checking it by prodStatus.
Furthermore, you should check the errors PHP is throwing in your script by enabling error reporting: error_reporting(E_ALL);
It's better to separate ajax calls from your view files. You can create a Class to handle all of your ajax calls (You should also consider authenticating your calls as per your use cases).
This little project of mine involves registering actions associated with buttons pressed on a gamepad (PS3 style for the record). Because html5 supports gamepads I decided to use it as a fast and simple way for development.
The thing is, when running the ajax and the call of the php script, after pressing a button, the insert statement is duplicated. This not happens when I set async: false and use Firefox, but this goes against the purpose of ajax, and from what I've read, not an elegant thing to do.
This is what I have in my index.html (borrowed from here https://gamedevelopment.tutsplus.com/tutorials/using-the-html5-gamepad-api-to-add-controller-support-to-browser-games--cms-21345)
function reportOnGamepad() {
var gp = navigator.getGamepads()[0];
var html = "";
html += "id: "+gp.id+"<br/>";
html += "timestamp: "+gp.timestamp+"<br/>";
html += "<br/>move<br/>"
if (gp.buttons[0].pressed) { var moves=" B1"; $.ajax({
url:'my.php',
method:'POST',
data:{
moves: moves
},
}); html+= " <br/>";
};
and my my.php
$conn = new mysqli($servername, $username, $password, $dbname);
$moves = $_POST['moves'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test (moves) VALUES ('$moves')";
$conn->query($sql);
$conn->close();
Simple stuff as you can see. My knowledge of jquery/javascript is very basic so, if someone with more experience could point me what I'm doing wrong, I would really appreciate it. Thank you.
The tuts+ tutorial you linked has some code to set up a polling interval for Chrome as a workaround for unreliability in the gamepadconnected event:
//setup an interval for Chrome
var checkGP = window.setInterval(function() {
console.log('checkGP');
if(navigator.getGamepads()[0]) {
if(!hasGP) $(window).trigger("gamepadconnected");
window.clearInterval(checkGP);
}
}, 500);
This bug is fixed in the latest version of Chrome and the workaround could be causing your issue. For instance, if checkGP fires before the gamepadconnected event is received, you may register the reportOnGamepad interval twice.
I am trying to update a tables row site_active in mysql using an onClick function with a button.
My button code is:
<button onClick='site_active()' id='site_active'><?php echo $client->site_active; ?></button>
And then of course my Script is:
<script>
function site_active()
{
alert("Site Updated");
}
</script>
I am sure that I need to use a php function to make this happen and I have the following code from my attempt to just do it with a form.
<?php
$con=mysqli_connect("INFORMATION REMOVED");
//Check connnection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con, "UPDATE mypanda_clients SET site_active='$_GET[site_active]' WHERE id='$_GET[id]'");
mysqli_close($con);
?>
The form option did not work because of some clashing problems in the website. ANY help would be great as I have spent hours on this with no progress. Thank You.
I would rather use jquery and do an ajax request to the server
$('#buttonid').click(function(){
//ajax request to the server goes here
});
Here the link for ajax in jquery
http://api.jquery.com/jQuery.ajax/
guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead
I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.