Ajax cannot display the response from php - 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>";

Related

How do I send data via AJAX?

I'm working on a social site. When I click the like button it runs the php page called "like.php", and inserts data into the data base BUT it is not receiving the post id, yet it will console log the post id from the jQuery.
here is my jQuery:
<script>
$(document).on('click', '.like_button', function() {
var postId = $(this).data('post-id');
console.log(postId);
$.ajax({
url: 'db/like.php',
type: 'POST',
data: { post_id: postId },
success: function(data) {
$('.like_count[data-post-id="' + postId + '"]').text(data);
console.log(data);
}
})
})
</script>
And here is my PHP:
<?php
session_start();
include("db.php");
$post_id = $_POST['post_id'];
$date = time();
// Get Current Post Likes
$sql = "select * from posts where id = '$post_id'";
$result = mysqli_query($conn, $sql);
$curr_likes = mysqli_fetch_assoc($result);
$new_likes = $curr_likes['likes'] + 1;
// Insert Into Likes table
$sql2 = "insert into likes (userid, postid, date) values ('$_SESSION[id]', '$post_id', '$date')";
mysqli_query($conn, $sql2);
if(isset($post_id)) {
echo "SET";
}else{
echo "NOT SET";
}
From the php page I'm getting "NOT SET"

Ajax cannot display json data from php. What's wrong with json format?

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.

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.

ajax send data not working

I tried using ajax to send data from onclick event on image
This is the ajax code
function get_img(name) {
$.ajax({
type: "POST",
url: "img_main.php",
data: "img_name="+name,
success: function(response)
{
alert("main image selected");
}
});
}
This is the img tag where I put the onclick event
while($row = mysql_fetch_array($query))
{
$test = $row['img_name'];
$result .= "<td><img src='".$uploaddir.$row['img_name']."' class='imgList' onclick='get_img(\"".$test."\")' /></td>";
This is the img_main.php
<?php
include("connect.inc.php");
echo "<script type='text/javascript'> alert('test'); </script>";
$img_name = $_POST['img_name'];
$query = "UPDATE upload set status = 1 where img_name = $img_name";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name != $img_name";
$result2 = mysql_query($query2);
?>
What I want is when I clicked on the image, it update the field status on the database.
The success function in the ajax code give me the alert function but the status field is not updated.
My console returns no error.
Can somebody please help?
try change
data: "img_name="+name,
to
data: {img_name:name},
or
$.ajax({
type: "POST",
url: "img_main.php", or use full url like "http://domain/img_main.php"
data: {img_name:name},
success: function(response)
{
alert("main image selected");
}
});
and img_main.php (add quotes to your query variable)
$query = "UPDATE upload set status = 1 where img_name = '$img_name'";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name != '$img_name'";
$result2 = mysql_query($query2);
Add quotes to $img_name in the update queries like:
$query = "UPDATE upload set status = 1 where img_name='$img_name'";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name!='$img_name'";
As you are getting alert as response, I don't think that there is error in ajax call.

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