How to return database query into ajax? - php

I want to check if a user has favourited an item but I'm unsure how to return the result of a database query to ajax.
I will show different html depending on the result.
Php
$query = "SELECT itemID from favourites WHERE userid = '" . $user. "'";
$result = mysql_query($query);
echo json_encode($result);
Jquery
$.ajax({
url: "inc/functions.php",
type: "POST",
data: {--result--},
success: function () {
// if result found in database
$('favourite').hide();
// if result not found
$('favourite').show();
}
});
I can't figure out how to display $result in the jquery code.
Any help much appreciated.

$result in this case is a PHP object representing a result.
You will have to use a fetch() method in order to extract the result before sending it back to your JS.
See this link. There's a list of all fetch-family method right above the comments.
Also, you will need to make a connection with you database beforehand using mysqli_connect (or mysql_connect in your case).
As stated in the comments, you should however use mysqli* functions family instead of mysql*.

Thanks to the comments for info regarding mysqli. I updated the code and solved the ajax part.
For anyone else stuck, I got it working like this:
PHP
require ("../../connection.php");
$sql = "SELECT * FROM favourites WHERE userID = ? AND itemID = ?";
$user = $_POST['userID'];
$item = $_POST['itemID'];
$statement = $db->prepare($sql);
if($statement === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db->error, E_USER_ERROR);
}
$statement->bind_param('ii',$user,$item);
$statement->execute();
$statement->bind_result($user,$item);
while($statement->fetch()){
echo 1;
}
$statement->close();
Jquery
$.ajax({
url: "inc/userList.php",
data: userList,
type: "POST",
success: function (result) {
if (result == 1){
$('#addItem').css('display', 'none');
$('#removeItem').css('display', 'inline-block');
} else {
$('#addItem').css('display', 'inline-block');
$('#removeItem').css('display', 'none');
}
}
});

Related

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 request not changing HTML

I created a form with two selects and my idea was when the first select is changed, a query is made to the database and the second select is updated with new information.
Since is the first time I'm doing this kind of things, I tried insert some data from that query in a H3 tag instead of using a select tag, but something is not working... The H3 tag starts empty and after changing the select box, the H3 tag remains empty.
This is my code:
<script>
$(document).ready(function(){
$("#show-form-button").click(function(){
$("#show-form-button").hide();
$("#bot-form").show();
});
$("#distrito").on('change', function() {
var selected = $(this).val();
makeAjaxRequest(selected);
});
});
function insertResults(json){
alert("cenas");
$("#teste").val(json["nome"]);
}
function makeAjaxRequest(placeID){
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
}
});
}
</script>
And this is my PHP script:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "paulocristo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$placeId = $_GET["placeId"];
$query = "SELECT nome from local WHERE id =".$placeId ." AND tipo=0";
$result = $conn -> query($query) or die("Query failed");
if($result -> num_rows > 0)
{
while ($row = $result -> fetch_assoc())
{
echo $row['nome'];
echo json_encode($row);
}
}
?>
Any idea what can be wrong?
I think the problem must be with AJAX because when I run this code, the right information is being displayed in the browser.
Thanks for your patience and sorry for my bad english.
1) Remove echo $row['nome']; if you echo ANYTHING along with the JSON response, the full response will not be valid JSON and the success function will not be called
2) dont echo your JSON for each row like that, that's not valid either. –
Instead do this:
$response = [];
while ( $row = $result->fetch_assoc() ){
$response[] = $row;
}
echo json_encode($response);
3) you're checking $_GET['placeId'] but your ajax is using type: "POST". Change your php to $placeId = $_POST["placeId"];
Additionally, and an error function after your success function in your AJAX like the following to better see what is going wrong:
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
},
error: function(xhr, status, error){
console.log(xhr);
}
});
4) Remember also that the response will be an array of rows not a single row so you'll need to update your function like so:
function insertResults(json){
alert("cenas");
$("#teste").val(json[0]["nome"]); // grab the 'nome' property from the first row in the response
}
In your PHP do this:
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
echo json_encode($arr);
mysql_close($con);
Also don't forget to do mysql_close($con) at the end. Hope this helps you!
From what I see you are using val() on h3 change your function to the following and use html(), The .val() method is primarily used to get the values of form elements such as input
function insertResults(json){
alert("cenas");
$("#teste").html(json["nome"]);
}

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?

How do i process this ajax data?

How will i process this Ajax in php.
What i want to do is send the data to process.php and if mode=loadlinks it will do a mysql query
function PresentLinks(div_id){
$("#loading-status").fadeIn(900,0);
$("#loading-status").html("<img src='img/bigLoader.gif' />");
$.ajax({
type: "POST",
url: "process.php",
data: "mode=loadlinks",
success: function(msg){
$("#loading-status").fadeOut(900,0);
$("#"+div_id).html(msg);
}
});}
What i want to process is
if($_POST['mode'] == loadlinks){ // this is what i want to ask
$query = "SELECT * FROM site ORDER BY link_id DESC";
$result = MYSQL_QUERY($query) or die (mysql_error());
while($data = mysql_fetch_row($result)){
echo ("$data[1]");
}}
else {
}
You need to quote strings in PHP. Otherwise they will be assumed to be constants. You should also be using PDO.
if($_POST['mode'] == 'loadlinks'){
$pdo = new PDO('mysql:host=HOST;dbname=DATABASE'), 'username', 'password');
$stmt = $pdo->execute('SELECT * FROM site ORDER BY link_id DESC');
$sites = $stmt->fetchAll();
foreach($sites as $site) {
echo "<div>" . $site['name'] . "</div>"; // Or whatever info you want to output
}
}
For performance you should be specifying table column names to retrieve instead of using *.
you need to quote the string value
if($_POST['mode'] == 'loadlinks'){.....

Categories