Profile view counter - variable showing as null despite being declared and used elsewhere - php

I'm trying to build a profile view counter with PHP and jquery ajax. I want the page count to be fetched, and incremented and input into the database when the page is loaded.
Here is my jquery:
var views = "<?php echo $views;?>";
$(document).ready(function(){
view = parseInt(views) + 1;
$.ajax({
url: "user.php",
type: "POST",
data: {
'views' : view //array of objects
},
success:function(data, response){
console.log(data);
alert(view);
}
});
and the php that picks up the ajax:
if(isset($_GET["id"]) && isset($_GET['activ'])){
$activ = preg_replace('#[^0-2]#i', '', $_GET['activ']);
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
} else {
header("location: http://www.unlimitedtutors.com");
exit();
}
if (isset($_POST['views'])){
$views = mysql_real_escape_string($_POST['views']);
$views = intval($views);
$sql1 = "UPDATE users SET views='$views' WHERE id='$id' LIMIT 1";
$query1 = mysqli_query($db_conx, $sql1);
echo $id;
}
the problem is that the $id variable doesnt seem to be showing up although I know it's been declared. This obviously means that the sql is not working correctly. Does anyone have any suggestions?

Related

Ajax cannot display the response from php

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>";

PHP/MySQL/AJAX - Refresh query values with AJAX

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.

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

passing id information with ajax

hi I am trying to identify the table id in a SQL query command.
here is my query command:
$id = $_POST['id'];
$query = " UPDATE cursos
SET status = '$checkboxstatus'
WHERE id='$id'";
all that code is inside a backend.php file which is loaded trought ajax command from the main php file:
this is the AJAX script which I am using:
$(document).ready(function(e) {
$('input[name=status]').change(function(){
if( $('input[name=status]').prop('checked') )
{checkboxstatus = '1';}
else
{checkboxstatus = '0';}
$.ajax({
type: "POST",
url: "checkboxtestbackend.php",
data: {checkboxstatus: checkboxstatus},
the question is for the record to be inserted in the right field inside the database I Have to put inside $id the id of the element from the sql dump which is done on this page.
while($row = mysqli_fetch_array($result))
{ $id = $row['id'];
?><?php echo "<input type='checkbox' id='$id' name='status'"; if($row['status'] == 1){print "checked='checked'"; }echo "/>";
what I think is that I have to send in this command data: {checkboxstatus: checkboxstatus}, also the id but how this can be done ? or if there is a better way let me know
You are not posting "id".
Insert this
var id = $(this).attr('id');
before $.ajax({
Now, Use this
data: {"checkboxstatus": checkboxstatus,
"id":id
},
Use:
$(document).ready(function(e) {
$('input[name=status]').change(function(){
if ( this.checked ) {
checkboxstatus = '1';
} else {
checkboxstatus = '0';
}
$.ajax({
type: "POST",
url: "checkboxtestbackend.php",
data: {
checkboxstatus: checkboxstatus,
id: this.id
},
this is the element that was clicked on.
Notice that I had to change how you set checkboxstatus. You were always getting the status of the first checkbox, not the one that was changed.
You could also post the ID
data: {checkboxstatus: checkboxstatus,id: $('input[name=status]').attr('id') },

php jquery iterate php array in success function

I have jquery pop form . It takes one input from the user ,mapping_key , Once the user enters the mapping key ,i make an ajax call to check if there is a user in the database with such a key.
This is my call .
Javascript:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
success: function(response) {
alert(response)
}
});
PHP:
$sql = "select first_name,last_name,user_email,company_name from registered_users where mapping_key = '$mapping_key'";
$res = mysql_query($sql);
$num_rows = mysql_num_rows($res);
if($num_rows == 0)
{
echo $num_rows;
}
else{
while($result = mysql_fetch_assoc($res))
{
print_r($result);
}
}
Now i want to loop through the returned array and add those returned values for displaying in another popup form.
Would appreciate any advice or help.
In your php, echo a json_encoded array:
$result = array();
while($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
echo json_encode($result);
In your javascript, set the $.ajax dataType property to 'json', then you will be able to loop the returned array:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
dataType : 'json',
success: function(response) {
var i;
for (i in response) {
alert(response[i].yourcolumn);
}
}
});
change
data : {"mapping_key":mapping_key} ,
to
data: "mapping_key=" + mapping_key,
You have to take the posted mapping_key:
$mapping_key = $_POST['mapping_key'];
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = '$mapping_key'";
or this:
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = $_POST['mapping_key']";

Categories