How do I send data via AJAX? - php

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"

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

Submitting into database, but through AJAX returns blank

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.

AJAX SET INTERVAL

I want to get the latest post_id in the table without refreshing it, but the problem is whenever a user inserts a value to the database, It echoes infinitely the last post_id. I want it to echo only once. But I still want to get the latest post_id from the table.
Here is my main php:
<div id = "this_div">
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id ASC LIMIT 20";
$execute_query = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($execute_query))
{
$get_this_id = $row['post_id'];
echo $get_this_id."<br>";
}
$_SESSION['get_this_id'] = $get_this_id;
?>
</div>
here is my jQuery ajax:
<script>
var refreshId = setInterval(function(){
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
$.ajax({
url: 'another_file.php',
data: {},
success: function(data)
{
if(compare_session != data)
{
$('#this_div').text($('#this_div').text()+data);
}
}
});
},400);
</script>
here is the php code of another_file.php
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id DESC LIMIT 1";
$execute_query = mysqli_query($con,$query);
if($row = mysqli_fetch_assoc($execute_query))
{
echo $get_this_id = $row['post_id'];
}
?>
You are not updating the compare_session variable , it holds always the initial value . So update it inside success callback function
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
var refreshId = setInterval(function () {
$.ajax({
url: 'another_file.php',
data: {},
success: function (data) {
if (compare_session != data) {
$('#this_div').text($('#this_div').text() + data);
}
compare_session = data;
}
});
}, 400);

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.

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

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?

Categories