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.
Related
I know that this question is already answered a lot, but even the previous responses from php are working, this response cannot work and i cannot find the reason for this issue.
Although php was send the response succesfully, ajax cannot display without refreshing the page first.
Here is my jquery.ajax code in the file helpers.js:
function likeButton(commentId, userId) {
$.ajax({
url: "requests.php",
type: "POST",
data: {
like: "likeUp",
commentId: commentId,
userId: userId
},
success: function(response) {
$("#comment_body").append(response);
}
});
}
Here is my php code in requests.php:
if(isset($_POST['like'])) {
if($_POST['like'] == "likeUp") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sql = "SELECT gaming_comment_like FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result = mysqli_query($conn, $sql);
if($row = mysqli_fetch_assoc($result)) {
$gaming_comment_like = $row['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update = mysqli_query($conn, $sql_update);
exit();
}
}
here is the eventhandler that calling the likeButton function, which is in a php file:
<p><img src='like.png' class='like_button' onclick='likeButton(".$gaming_comment_id.", ".$user_id.");'>$gaming_comment_like</p>";
I have read all the related questions that reference to this topic, but still cannot find answer here. So, php and ajax works great. The problem starts when i try to include json, between php and ajax, to passing data.
here is my ajax:
function likeButton(commentId, userId, sessionUserId) {
// check if the comment belong to the session userId
if(sessionUserId == userId) {
alert("You cannot like your own comment.");
}
else if(sessionUserId != userId) {
var like_upgrade = false;
$.ajax({
url: "requests.php",
type: "POST",
dataType: "json",
data: {
keyLike: "like",
commentId: commentId,
userId: userId,
sessionUserId: sessionUserId,
like_upgrade: like_upgrade
},
success: function(data) {
var data = $.parseJSON(data);
$("#comment_body td").find("#updRow #updComLike[data-id='" +commentId+ "']").html(data.gaming_comment_like);
if(data.like_upgrade == true) {
upgradeReputation(userId);
}
}
});
}
}
Note, that i try not to include this:
var data = $.parseJSON(data);
Also i tried with diferent variable like so:
var response = $.parseJSON(data);
and also tried this format:
var data = jQuery.parseJSON(data);
None of these worked.
here is requests.php file:
if(isset($_POST['keyLike'])) {
if($_POST['keyLike'] == "like") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sessionUserId = $_POST['sessionUserId'];
$sql_upgrade_like = "SELECT * FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result_upgrade_like = mysqli_query($conn, $sql_upgrade_like);
if($row_upgrade_like = mysqli_fetch_assoc($result_upgrade_like)) {
$gaming_comment_like = $row_upgrade_like['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update_like = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update_like = mysqli_query($conn, $sql_update_like);
$sql_insert_like = "INSERT INTO gaming_comment_likes (gaming_comment_id, user_id, user_id_like) VALUES ('$commentId', '$userId', '$sessionUserId')";
$result_insert_like = mysqli_query($conn, $sql_insert_like);
$like_upgrade = true;
//json format
$data = array("gaming_comment_like" => $gaming_comment_like,
"like_upgrade" => $like_upgrade);
echo json_encode($data);
exit();
}
}
Note: i also try to include this to the top of my php file:
header('Content-type: json/application');
but still not worked.
What am i missing here?
Don't call $.parseJSON. jQuery does that automatically when you specify dataType: 'json', so data contains the object already.
You should also learn to use parametrized queries instead of substituting variables into the SQL. Your code is vulnerable to SQL injection.
I am trying to insert values from my form into my database.
When I have the form action to the script directly, it inserts:
require_once("../../includes/database.class.php");
session_start();
$uid = $_SESSION['uid'];
$title = $_POST['blog-title'];
$content = $_POST['blog-content'];
$image = $_POST['article-image'];
$active = $_POST['active-inactive'];
$comments = $_POST['enable-comments'];
$sql = "INSERT INTO blog_article (blog_title, blog_body, blog_author, blog_image, active, comments) VALUES ('$title', '$content', '$uid', '$image', '$active', '$comments')";
// print_r($sql);
$result = $database->query($sql);
if ($result) {
echo "Article created.";
}else {
echo "Query failed" . print_r($sql);
}
However, when I set up ajax to handle it without reloading the page, the query submits perfectly. However, the values are blank other that the uid:
var submit_button = $('#submit_article');
var data = $("#addarticleform").serialize();
submit_button.click(function() {
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: 'addarticle.php',
success: function(html) {
update_div.html(html);
}
});
});
I apologize if this is an obvious mistake, I've only just started playing with AJAX.
I figured it out. As it turns out, i had
var data = $("#addarticleform").serialize();
in the wrong place. Should be after
submit_button.click(function() {
not before it.
I have built a login script that uses AJAX to submit form data.
The PHP part works fine without AJAX. But the system doesnt work with AJAX Implementation.
It always Displays the below message even though the PHP file returns true[correct username & password] ... Seems like the if condition in Jquery is not working.
Incorrect Username/Password
HTML Result Div
<div id="user-result" align="center"></div>
Jquery
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data == "true") {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>
fn_login.php
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo "true";
}
else {
die();
}
}
}
?>
Can someone please point out the mistake in the code/practice.
EDIT
Just Tried disabling AJAX, the PHP file works correctly echoing true when username/pass is correct
You have spaces after ?>
So, the AJAX response is having spaces after true.
Solution:
Remove ?> from the end of PHP file.
It will not affect any PHP functionality.
And you AJAX response will be without spaces.
Excluding closing tag ?> from the end of PHP file is standard practice for modern PHP frameworks and CMSs.
Tips for debugging AJAX:
1) Always use Firefox (with Firebug Add) on Or Chrome.
2) Use Console tab of Firebug, to check which AJAX requests are going.
3) Here, you can see input parameters, headers and most important response.
4) So, in short you can debug a whole AJAX request life cycle.
You can echo json_encode(array('success'=>true)) from php code and modify your if condition in jquery with if(data.success){} Your modified code becomes
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo json_encode(array('success'=>true));
}
else {
die();
}
}
}
AND JQuery becomes
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data.success) {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>
I have this form:
<form method = \"get\" action = \"\" onsubmit = \"return addBeer('$user','$id','$name','$abv','$ibu','$icon','$style','$brewery','$breweryID','$icon')\" >
<p> <input type = \"submit\" value = \"Go Fishing\" /> </p>
</form>
which calls this JavaScript function:
function addBeer(user,id,bname,abv,ibu,icon,bstyle,brewery,breweryID,icon)
{
//get elements
alert('userID' + user);
alert('beerid'+id);
alert('beername'+bname);
alert('style'+bstyle);
alert('brewery'+brewery);
alert('abv'+abv);
alert('ibu'+ibu);
alert('brewery id'+ breweryID);
alert('icon'+icon);
//run ajax
var ajaxSettings2 =
{
type: "POST",
url: "addBeer.php",
data: "uID="+user+"&bID="+id+"&bName="+bname+"&bStyle="+bstyle+"&bBrewery="+brewery+"&abv="+abv+"&ibu="+ibu+"&breweryID="+breweryID,
success: function()
{
$('#sbutton').remove();
alert('Load was performed.');
},
error: function(xhr, status, error) { alert("error: " + error); } };
$.ajax(ajaxSettings2);
}
All the alerts work so I know for a fact that the information is getting passed fom the form to the function, but it fails on the ajax call to addBeer.php because it runs the error function and pop up the error alert. Unfortunetley nothing is reported in the pop up.
This is the addBeer.php file that is called to add to the database:
<?php
require_once('myConnectDB.inc.php');
require_once('page.inc.php');
session_start();
//add beer to database code
$userID = $_POST['uID'];
$beerName = $_POST['bName'];
$beerID = $_POST['bid'];
$brewery = $_POST['bBrewery'];
$style = $_POST['bStyle'];
$abv = $_POST['abv'];
$ibu = $_POST['ibu'];
$breweryID = $_POST['breweryID'];
//$icon = $_POST['icon'];
//get brewery icon
$uri3 = "http://api.brewerydb.com/v2/brewery/$breweryID?key=myKey&format=json";
$response3 = file_get_contents($uri3);
//parse xml
$myBrew = json_decode($response3);
$iconBrew = $myBrew->data->images->medium;
//add above data to database
$db = new myConnectDB();
$beerName = $db->real_escape_string($beerName);
$beerID = $db->real_escape_string($beerID);
$brewery = $db->real_escape_string($brewery);
$style = $db->real_escape_string($style);
$userID = $db->real_escape_string($userID);
$abv = $db->real_escape_string($abv);
$ibu = $db->real_escape_string($ibu);
$breweryID = $db->real_escape_string($breweryID);
$icon = $db->real_escape_string($icon);
$query3 = "INSERT INTO tableName (userID,beerID,beerName,beerStyle,beerBrewery,abv,ibu,breweryID,icon, brewIcon) VALUES ($userID, '$beerID', '$beerName', '$style' , '$brewery', '$abv','$ibu','$breweryID', '$icon', '$iconBrew')";
$db->query($query3);
?>
I took out my api key and table name for security.
I have checked the network tab in chrome under inspect element and when I click on addBeer.php call and look under headers it shows in form data that the information is being passed.
Update:
I am escaping my quotes because its being printed from php
After lots and lots of frustration, I figured out my problem. The information I was sending, I was querying from another database and all that info was not always complete.
If I clicked submit and it and one of the variables in the function call was an empty string it did not like it.
You have your method as GET in the form but POST in your Ajax.