ajax send data not working - php

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.

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

ajax run mysql query and check whether mysql query was true or false?

I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks
mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}

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?

JQuery Ajax not updating record

I have some jquery ajax code to update a record but it's not working as expected.
Here is the code:
function update_records() {
$.ajax({
type: "POST", // Set the type then $_GET['id'] or $_POST['id']
url: "update_record.php",
data: { category: "John", image: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}; //end function
Then the php
<?php
$id = $_REQUEST['id'];
include 'config.php';
$result = mysql_query("UPDATE mytable SET title = 'something' where id=$id");
$result = mysql_query("SELECT * FROM mytable WHERE id = '$id'");
$array = mysql_fetch_row($result);
?>
Example from jQuery.com
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST", // Set the type then $_GET['id'] or $_POST['id']
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
I can't understand what your query returns.
Maybe you need to select where id = $id;
// $id = $_POST['id'] or $_GET['id'] Where is $id???
$result = mysql_query("UPDATE mytable SET title = 'something' where id=$id");
$result = mysql_query("SELECT * FROM mytable WHERE id = '$id'");
$array = mysql_fetch_row($result);
//You can use mysql_error() function to see the error.
$result = mysql_query("UPDATE mytable SET title = 'something' where id=$id") or die(mysql_error());
I see you have:
$result = mysql_query("UPDATE mytable SET title = 'something' where id=$id");
I don't see where you take the value of $id
u need
$id = $_REQUEST['id'];
I think you forgot to include this line before executing the update query.

Categories