Afternoon
My php and Ajax is now almost complete, but I'm stuck on one thing I'm getting the data sent back through to the ajax but its only showing [object Object] in the div I've specified and I'm wanting the number of results sent back to be in there.
<? $call="SELECT * FROM notifications WHERE notification_targetuser='$user1_id' ORDER BY notification_id DESC LIMIT 1";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
$num=mysqli_num_rows($chant);
while($notification_id=mysqli_fetch_array($chant))
{
?>
<script type="text/javascript">
setInterval(function(){
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(response){
$("#mes").prepend(response);
}
});
},20000);
</script>
<? }?>
Vuewajax.php
<?php
include"database.php";
if(isset($_GET['notification_id'])){
$id=$_GET['notification_id'];
$user1_id=$_SESSION['id'];
$json = array();
$com=mysqli_query($mysqli,"select notification_id from notifications where notification_id > '$id'");
echo mysqli_error($mysqli);
$num = mysqli_num_rows($com);
if($num>0){
echo '<span id="mes">'.$num.'</span>';
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
mysqli_free_result($com);
echo json_encode($json);
}
?>
My returned response in firebug
<span id="mes">1</span>{"notification_id":"3306"}
You are returning a json object, so you need to access the correct propery, in this case notification_id. Its also good practice to set the correct content-type header:
//php set json header
header('Content-Type: application/json');
echo json_encode($json);
//js access property of returned object
$("#mes").prepend(response.notification_id);
EDIT as per comment - if you are sending json, only send json, not mixed in html:
if($num>0){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
mysqli_free_result($com);
header('Content-Type: application/json');
echo json_encode($json);
//js
$("#mes").prepend('<span id="mes">'+ response.num + '</span>');
Further EDIT
You can check the value of num, and only prepend if its not 0. As 0 evaluates to false, the following will work
if(response.num){
$("#mes").prepend('<span id="mes">'+ response.num + '</span>');
}
This answer can seems to be off-topic but the code you show us is not secure. He's prone to easy sql injection
eg :
$id = $_GET['notification_id'];
$com = mysqli_query($mysqli,"select notification_id from notifications where notification_id > '$id'");
Injecting "'; DELETE FROM users WHERE 1 or username = ''" in your notification_id parameter will delete all your users !
Use prepared statements, it's easy and far safer an XKCD ;-)
Related
I'm trying to create this like button which goes +1 after clicking on it. You can only click the like once (like is bonded to the account with what u logged in, so a user can not 15x like the same post.)
In my HTML I have this button
<a class="like" id="<?php echo $rows['id']; ?>" href="index.php?id=.$rows['ID']">like</a>
As my AJAX/JQuery I have these
$('a.like').on('click',function () {
var id = $(this).attr('id');
$.ajax({
url:"ajax/post_like.php",
method: "POST",
data: ({ id: id }), // first id is the name, second is the actual id variable we just created
beforeSend: function(data) {
// you can do stuff in here before you send the data, display spinner gif etc
alert('sending the like');
},
success: function(data) {
// same here but when the ajax request is successful
// the data variable is coming from the echo of your PHP script
alert(data);
},
complete: function(data) {
// yet again but on completion
alert('completed the like');
}
});
// stops the browser following the link (href) in the a tag
return false;
});
Now here is the part where I am struggling, mainly the PHP handling. We have created a load more button which loads more posts which works well. The code is as follows. How can I know work out the like part in the same way as the load more button?
<?php
include_once("../classes/db.class.php");
session_start();
$userid = $_SESSION['userid'];
$output = "";
$limit = $_POST['limit'];
if(isset($limit)){
if($limit != ""){
$conn = db::getInstance();
$query ="SELECT posts.id, posts.post_title, posts.picture ,posts.description, posts.location, posts.post_date
FROM posts
INNER JOIN friends
ON posts.user_id = friends.user1_id OR posts.user_id = friends.user2_id
WHERE friends.user1_id='$userid' OR friends.user2_id='$userid'
ORDER BY posts.post_date DESC
LIMIT $limit";
$result = $conn->prepare($query);
$result->execute();
while($row = $result->fetch()) {
$output.=' <div class="post">';
$output .='<div class="post_desc"><p>'. $row['post_title'].'</p></div>';
$output .='<div class="post__picture"><img src="'. $row['picture'].'" alt=""></div>';
$output .='<div class="post_desc"><p>'. $row['description'].'</p></div>';
$output .=' <div class="post_date">'. $row['post_date'].'</div>';
$output .='</div>';
};
echo $output;
}
}
else{
}
?>
Our database is as follows.
Assuming you can set the id column freely, and the userid and postid sections are alphanumerical, you can require the id column to be unique. The following will then always work:
include_once("../classes/db.class.php");
$conn = db::getInstance();
$userid = $_SESSION['userid'];
$postid = $_POST['id'];
$id = "$userid/$postid";
$query = "INSERT INTO likes (id, user_id, post_id) VALUES ('$id', '$userid', '$postid')";
if ($conn->query($sql) === TRUE) {
echo json_encode({postid: postid});
} else {
// There was a small problem processing the like
// You might want to add a check in your success function just to be sure
header('HTTP/1.1 500 Internal Server Error');
}
However, be sure to add a few tests to prevent SQL injections (e.g. by ensuring $postid consists only of integers). If no such guarantee can be made, you should check out this thread.
Otherwise (e.g. if id is generated using AUTO_INCREMENT), you'd have to add a test which tries to retrieve ($userid, $postid) to check if it doesn't exist already:
if (conn->query("SELECT 1 FROM likes WHERE userid=$userid AND postid=$postid")->num_rows == 0) {
// Place the code starting from `$id = ` in here.
};
I am trying to create a chat system using php and ajax. I started the ajax request when the user hit the send button and after that the request will be called after 5 sec automatically. I want fetch the latest entry from the database. I am passing a last item id "tid".
I am getting the data from the database after the last id but it appending my div the same data until I entered a new record.
function startajax()
{
var usfrnd = $("#username").text();
var data = 'lastid=' + tid + '&usfrnd=' + usfrnd;
$.ajax({
type: "POST",
url: "includes/wow_message.php",
data: data,
//dataType: "JSON",
success: function(msg){
$("#msgbody").append(msg);
console.log(msg);
},
complete: function() {
setTimeout(startajax, 5000);
}
});
}
php code.
<?php
include '../include/database.php';
session_start();
$username = $_SESSION['uName'];
if(isset($_POST['lastid'], $_POST['usfrnd']))
{
$lastid = $_POST['lastid'];
$sent_to = $_POST['usfrnd'];
$qry2 = "select * from msg_tab where (((sent_by= '$username' AND sent_to='$sent_to') OR (sent_by= '$sent_to' AND sent_to='$username')) AND $lastid < msg_id) ORDER BY msg_id ASC";
$res = mysqli_query($conn, $qry2);
if (mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_assoc($res)) {
$message = $row['msg'];
$msg_id = $row['msg_id'];
$sent_by = $row['sent_by'];
echo ' <tr data-msg-id="'.$msg_id.'">
<td><span class="subject">'.$sent_by.'</span></td> <td><span class="subject">'.$message.'</span></td>
</tr>';
}
}
}
?>
If you want create chat maybe you should use ex. WebSocket.
Send request in some time interval in my opinion is no so good solution.
First let me show you the code
This is the script
var user_id = $(this).attr("id");
var datastring = 'user_two='+ user_id;
$(".follow").click(function(){
$.ajax({
type: "POST",
url: "include.php",
data: datastring,
success: function(html){}
});
$("#follow"+user_id).hide();
$("#unfollow"+user_id).show();
return false;
});
Here is php
<?php
$query = $handler->query("SELECT * FROM users");
while ($row = $query->fetch()) {
$user_two = $row['id'];
$user_one = 1;
?>
<p><?php echo $row['username'];?></p>
<?php
$follow_check = $handler->query("SELECT * FROM follow WHERE user_one='$user_one' AND user_two='$user_two'");
if ($follow_check->rowCount() == 0) {?>
<div id="follow<?php echo $user_one;?>">
Follow
</div>
<div id="unfollow<?php echo $user_one;?>" style='display:none'>
Following
</div>
<?php }else{?>
<div id="follow<?php echo $user_one;?>" style='display:none'>
Follow
</div>
<div id="unfollow<?php echo $user_one;?>" >
Following
</div>
<?php } ?>
<?php } ?>
Here is the php for Insert query
<?php
include('db.php');
$user_two = $_POST['user_two'];
$query = $handler->query("INSERT INTO follow (user_one,user_two) VALUES ('1','$user_two')");
?>
there two things i need to insert which is user_one = Session=0 or the current logged in user but i just made it static for the mean time and the user_two which is the users id or the one you will click to follow that person. But idk how to do it in ajax, like in php you can get the value of the link like <a href="?id="> and then to get the value, $_GET['id'] but idk how to store that value to script
I just need an explanation on user_id = $(this).attr("id");
and the return false inside the $(".follow").click and when I make it to false i need to refresh the page just to see the changes of links to follow and following why is it like that?
By the way, When i click the follow link it will successfuly insert to the database but the user_two's value is always 0 because I dont know how to store link id to the script.
Not 100% sure if i understood but let me try:
First: id="<?php echo $user_id; ?>" it's ok.
You can get it with var user_id = $(this).attr("id");
Maybe you should move this line inside the $(".follow")... block
$(".follow").click(function() {
var user_id = $(this).attr("id"); //"this" will refer the element with the "follow" class. Then user_id will be the value of the id for the clicked element.
$.ajax({
type: "POST",
url: "include.php",
data: {user_two: user_id}
}).done(function(data) {
data = JSON.parse(data);
if(data.msg) {
//everything is ok
$("#follow"+user_id).hide();
$("#unfollow"+user_id).show();
} else {
//handle the error
}
)}
});
PHP part:
<?php
include('db.php');
$user_two = $_POST['user_two'];
$query = $handler->query("INSERT INTO follow (user_one,user_two) VALUES ('1','$user_two')");
if($query) { //check if query ran successfully
echo json_encode(array("msg" => 1)); 1 for success
} else {
echo json_encode(array("msg" => 2)); 2 for error
}
?>
As for the "what is return false in ajax":
.follow -> targets an tag. Clicking on an a tag makes your browser navigate to the url specified in href="". return false disables this behaviour as you don't need the page to refresh or go to another page :)
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'];
Background:
I have a page which dynamically pulls up a modal window, which displays extended information on a row (with multiple columns) through mySQL. I am having issues where my JSON code will not populate the information correctly so that it can be outputted. I have tried multiple nested arrays, while loops and for loops. However, I only need to return one full row of information from the database. After scratching my head, I am asking the help of all the SO experts. Any pointers are much appreciated.
Ajax Code For Div Population (Works)
var data_id = $(this).data('id');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: {id: data_id},
dataType: 'json',
success: function(data){
$('.view_modal_content').html(data.html); // LOAD THE DATA INTO THIS DIV
},
error: function(jqXHR, textStatus, errorThrown){
$('.view_modal_content').html(''); // LOAD THE DATA INTO THIS DIV
alert('Error Loading Information');
}
});
JSON Code To Pull Information and return HTML
<?php
$customer_id=$_SESSION['customer']['customer_id'];
$id = (int)$_POST['id'];
$query = "SELECT * FROM collections_list WHERE id={$id} && customer_id=$customer_id LIMIT 1"; //expecting one row
$result = mysql_query( $query );
//$message = mysql_fetch_assoc( $result ); //expecting just one row
$message=array();
while ($row = mysql_fetch_assoc($result)) {
$message[]=$row['agency_name'];
$message[]=$row['account_number'];
$message[]=$row['phone'];
}
$json = array();
$json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';
header('Content-Type: application/json');
echo json_encode( $json );
?>
Additional Question:
Is it possible to reference the headers in the array using " $message['agency_name'] "inside the html that gets returned?
After solving this problem, I will need to turn the outputted html into a structure to allow my users to view the information in a properly understandable format. I know how to do this in html, but I am unfamiliar with JSON... Is there a way to output the information without having to manually code the structure?
Thank you in advance.
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(db_nname", $con);
$result = mysql_query("SELECT phone,agency_name FROM '''' ");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['results'][] = $r;
}
print json_encode($rows);
?>
and in your html
<table id ="listtable"></table>
var listdiv = $("#listtable");
$.getJSON("whatever.php",function(json){
$.each(json.results,function(i,data){
listdiv.append("<tr><th>" + data.phone + "</th><th>" + data.agency_name + "</th></tr>");
});
});
and in the append use data. and whatever your fields are
data.agency_name
data.phone
etc....