the success function is working but the data is not going in the database
$(document).ready(function() {
$("#ChatText").keyup(function(e){
if(e.keyCode == 13) {
var ChatText = $("#ChatText").val();
$.ajax({
type:'POST',
url:'InsertMessage.php',
data:{ChatText:ChatText},
success:function(){
$("#ChatText").val("");
}
});
}
});
setInterval(function(){
$("#ChatMessages").load("DisplayMessages.php");
},15000000);
$("#ChatMessages").load("DisplayMessages.php");
});
PHP
<?php
session_start();
include "connectToDB.php";
if(isset($_POST['ChatText'])){
$uid = $_SESSION['userid'];
$gid = $_SESSION['GameId'];
$ct = $_POST['ChatText'];
$sql = "INSERT INTO `chats`( `ChatUserId`, `chatGameId`, `ChatText`) VALUES ('$uid','$gid',$ct);";
$result = mysqli_query($_db , $sql);
}
?>
one thing u could do to debug is that echo your sql query and see if you get the correct query that works. You can event try out that query in phpMyAdmin and see whats going on. Hard to tell anything without debug.
Related
I would like to update the data in the frontend when it is changed in the database. The code I'm using is given below:
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div id="test">
<?php
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = 1;";
if(mysqli_fetch_assoc(mysqli_query($conn, $query))["name"] == "MyName")
echo 'Hi <b>MyName!</b>';
else
echo 'You are not <b>MyName</b>.';
?>
</div>
<script>
setInterval(function(){
$.get("/test.php", function(data){
let $data = $(data);
$("#test").append($data.find("#test > *"));
});
}, 1000);
</script>
However, when the data is updated, it does not get updated in the frontend unless refreshed. When I use jQuery's load() function, it works perfectly. Why does this not work?
As I suggested in the comment, if you create a stand alone PHP Script, it might be like:
getUserName.php
<?php
$id = (int)$_GET['id'];
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = $id;";
$myName = "";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$myName = $row;
}
}
mysqli_free_result($result);
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myName);
?>
This is a very basic example and I would strongly advise you switch to using prepared statements to avoid the risk of SQL Injection.
In your HTML you can now do:
<script>
setInterval(function(){
$.getJSON("/getUserName.php", { id: 1 }, function(data){
$("#test").append(data.name);
});
}, 1000);
</script>
This will ping the script every second and you will have a list of names appearing.
I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.
The code should work the following way: Press a button -> row gets deleted from database.
I tried to follow and copy answers from other questions but with no working solution.
The jquery code:
$(document).on('click', ".menuRemove", function(event) {
var del_h3name2 = $(this).parent().parent().prev().text();
$.ajax({
type:'POST',
url:'deleteaccordion2.php',
data:{'del_h3name2':del_h3name2},
success: function(data){
if (data=="YES") {
alert("YES")
} else {
alert("can't delete the row")
}
}
});
}
and php code (deleteaccordion2.php):
<?php
require 'database.php';
if ( isset($_SESSION['user_id']) ) {
$id = $_SESSION['user_id'];
$accordion = $_POST['del_h3name2'];
echo '$accordion';
$delete = "DELETE FROM useraccordion WHERE id='$id', h3= '$accordion' ";
$result = mysqli_query($delete);
if ($result) {
echo "YES";
} else {
echo "NO";
}
}
?>
You didn't add the html so I really don't know if the value you are sending is correct, but you do have error in your SQL syntax:
DELETE FROM useraccordion WHERE id='$id', h3= '$accordion'
^ This is wrong.
You can DELETE where id = x AND h3 = y:
$delete = "DELETE FROM useraccordion WHERE id='$id' AND h3= '$accordion' ";
Note that your code is vulnerable for SQL injections (read about boby tables).
Ajax does not want to recognize my $google['cities'] when called as data.cities.
The output is: 12 undefined undefined.
It works well (output are database records) if i remove $google['number']=12, and define database array just as $google[]=$row.
Any ideas?
PHP:
<?php
$con = mysql_connect("localhost","root","");
if(!$con) {
die("Connection Error: ".mysql_error());
}
mysql_select_db("avtost", $con);
$pasteta = $_POST["white"];
$places = mysql_query("SELECT sDo FROM bstop WHERE sOd='$pasteta'");
mysql_close($con);
$google=array();
while ($row=mysql_fetch_array($places)) {
$google["cities"]=$row;
}
$google['number']=12;
if (mysql_num_rows($places)>0) {
echo json_encode($google);
} else { echo 'Ni rezultatov';}
?>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
dataType:'json',
data:{white:white},
success: function(data){
var result='';
$.each(data.cities, function(i,e) {
result += '<div>'+e.sDo+'</div>';
});
$("#res").append(data.number);
$("#res").append(result);
}
});
});
});
</script>
you are overwriting the cities key in $google every time you loop for a row in $places.
you can use:
while ($row=mysql_fetch_array($places)) {
$google[]=$row;
}
$google[]=12;
and then simply grab the last value value of the array if you want to get the number key, or just pass the number as a separate variable $number.
Some tips:
1) you should be using prepared statements to secure your code (mysqli prepared). This will give you something like:
// connect to database and check it
// ...
$stmt = $mysqli->prepare('SELECT sDo FROM bstop WHERE sOd=?');
$stmt->bind_param('s',$pasteta);
$stmt->bind_result($sDo);
$stmt->execute();
while($stmt->fetch())
$google['cities'][] = $sDo;
$google['number'] = 12;
$stmt->close();
$mysqli->close();
// ...
2) Improve your variable, table and column names. They are a bit confusing.
3) Instead of returning 'Ni rezultatov', you should return JSON. Such as, {"status":"FAILED"}, subsequently returning {"status":"OK", ... } for successful requests.
I solved it myself:
PHP:
while($row=mysql_fetch_array($places)){
$google['cities'][]=$row;
}
$google['number']=12;
echo json_encode($google);
I am creating a facebook like posting system..
My problem today is it doesn't seem to insert the value i get from the text area into my data base..
here is my java script:
$("#share").click(function()
{
//var typeNew = document.getElementById("content").value;
var update = $( "textarea#content" ).val();
//document.write(update);
if(update.length == 0)
{
alert("empty, please type something.");
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
}
else
{
//$("#flash").show();
$("#flash").html('<img src="loader.gif" />Loading Comment...').fadeIn("slow");
$.ajax({
type: "POST",
url: "post_update.php",
data: 'update=' + update,
success: function(msg)
{
$("#flash").ajaxComplete(function(event, request, settings){
//alert("Successfully Inserted")
$("#flash").hide();
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
});
}
});
}
return false;
});
then here is my php code:
<?php
$post=$_REQUEST['update'];
$post=$_POST['update'];
//echo '$post';
# $db = new mysqli('localhost', 'root', '', 'wall');
if(mysqli_connect_errno())
{
echo "Error! Could not connect to database. Reset fields.";
exit;
}
$sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
$result = $db->query($sql);
if($result){
echo 'OK';
}
else{
echo 'FAIL';
}
$db->close();
?>
can someone tell me what's wrong?
it worked well when the delete function was in error but now that it's functional my share function does not work..
In your PHP code you have the following lines:
$post=$_REQUEST['update'];
$post=$_POST['update'];
You shouldn't have these both. In Your case, You actually need only the second one but for testing, try commenting it out leaving only the $_REQUEST line. Now you can pass parameters by GET too.
To see, if the query is correct, print it out too like this:
echo $sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
Now direct your browser to that location your.domain/post_update.php?update=testmessage and see the output.
If everything seems to be working, replace the POST/REQUEST lines with this:
$post=$db->real_escape_string($_POST["update"]);
I ran into this the other day. Use autocommit or start and commit transactions. Also, try a semicolon at the end of your statement (probably not the issue).
http://dev.mysql.com/doc/refman/5.0/en/commit.html
If your $post is coming out to be fine then try:
$post = $db->real_escape_string($_POST["update"]);
if (!db->query("INSERT INTO posts(update,date_posted) VALUES('$post' ,NOW())")) {
echo $db->sqlstate; //show error
}
else {
echo "inserted";
}
Assuming the column type of update is varchar / charand date_posted is datetime:
$sql = sprintf("INSERT INTO posts(update,date_posted) VALUES('%s',NOW())",
mysql_real_escape_string($post));
$result = $db->query($sql);
Please change the column name "update" to anyother. it may works. And Avoid some predefined varibales for column names.
Hope it helps.