I have a jqm app I'm working on. I am querying a mysql db to create links, they aren't working . I have read and learned that you cant use location.search in jq mobile, so I have added an attribute data-link in my .
I have a cookie set with the userid, when the user goes to look up recipes, it reads his cookie gets his userid then does a query for all the recipes with the corresponding userid, then displays them.
I would like to be able to click on one of the created links, go to a different page, then do a query with that link id and pull up the actual recipe.
Here is the js I am using to pull up the php file.
$(document).on("pageshow","#retrieve",function(){
var uid1 = $.cookie('recuid');
var uid = uid1.substr(7);
var data;
var response = '';
$.ajax({ type: "GET",
url: "retrieve_recipes.php?userid=" + uid,
dataType: "html",
async: false,
success : function(response)
{
$("#show_recipe").html(response);
}
});
});
Here is the php code used to create the link list.
<?php
include_once('../recipe_holder/connect.php');
$uid = $_GET['userid'];
$sql = "SELECT * FROM recipes WHERE userid = '$uid'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<a href='#showRecipe' class='ui-btn' data-link='".$row['uid']."'>".$row['title']."</a> ";
}
} else {}
?>
Here is the jquery/js code I am using to get the uid of the particular recipe to query the db and display the data. I have this simplified, simply with an alert to display the uid, I figure if I can get that much to work, I can get the rest to work.
$('[data-link]').click(function(){
var uid = $(this).attr('data-link');
alert(uid);
});
any ideas would be much appreciated.
thanks.
Related
I'm facing an issue in updating rows in mysql table. I'm currently working on social media website. There's a notification table where we've all users notification.
For example
"John liked your post, Sara commented on your post" Just like this
Table structure is given below.
As you can see i have a column "IsRead". If the user click on "Mark all as read button"
a query executes.
UPDATE notification SET isRead = 1 WHERE toUser = $id
When i execute this query it takes about 2 minutes or above and at the end it says connection to server has been lost. Error snap is attached below
Please suggest me what's the right way to create a table for notification. My created table structure is given above.
This is my javascript code:
function markAsRead(){
$('.notifications-area').html('<li><center>Noting to display</center></li>');
$('.list-notification').html('<li><center>Noting to display</center></li>');
$('#countNotifications').html(0);
$('#countNotifications1').html(0);
$.ajax({
type: 'ajax',
method:'POST',
url: "<?php echo site_url()?>/Main/markAsRead",
datatype:"JSON",
success:function(responce)
{
},
error:function(e)
{
console.log(e);
}
});
}
My Controller:
public function markAsRead(){
$data=$this->m->markAsRead();
echo json_encode($data);
}
Model:
public function markAsRead(){
$userid = $this->session->userdata('userid');
$query = $this->db->query("UPDATE notification SET isRead = 1 WHERE toUser = $userid and isRead = 0");
return $query;
}
I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.
Here is the Java Script / AJAX
function fetchdata(){
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser},
success: function(read){
$("#readarea").html(read);
}
});
}
Here is the PHP code to get messages:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$_POST['cuser']){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
}
Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.
You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.
Something like this:
PHP:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();
while($row=mysqli_fetch_assoc($result)){
$messages[] = $row;
}
echo json_encode($messages);
JS:
//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;
function fetchdata()
{
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
dataType: "json",
data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
success: function(read) {
for (var i = 0; i < read.length; i++)
{
var className = "ouser";
if (read[i].fromid == cuser) classname = "cuser";
$("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
lastMessageID = read[i].id;
}
}
});
}
P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.
This is my ajax code:
$(document).ready (function() {
$("#send").click (function() {
var username = $(this).val();
alert (username);
$.ajax({
url : "sendpost.php",
type: 'POST',
async: false,
data: {username},
success: function(datat){}
})
});
});
This is my php code
include ('connection_socio.php');
if(isset($_POST['body']))
{
$body=mysqli_real_escape_string($db, $_POST['body']);
$date_added="123";
$added_by="123";
$username = mysqli_real_escape_string($db, $_POST['username']);
$check = "SELECT * FROM users";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$user_posted_to = $username;
echo $user_posted_to;
$query_post = "INSERT INTO posts VALUES ('', '$user_poste_to',)";
mysqli_query($db, $query_post);
echo "POSTED SUUCESSFULLY";
}
This is my profile.php code:
if (isset($_GET['u']))
{
$username = mysqli_real_escape_string($db, $_GET['u']);
//checks and remove symbols like # , ' etc
if(ctype_alnum($username))
{
//check user existance
$check = "SELECT * FROM users WHERE username='$username'";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
if(mysqli_num_rows($result_profile) == 1)
{
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$username = $getusername['username'];
}
else
{
echo "User dont exist";
exit();
}
}
}
what I want is to fetch variable $username from profile.php page and assign it to $user_posted_to variable in senpost.php page and insert into database using javascript if any expert can help will really appreciate it i have tried this.attr() but thats not working also this.value is also not working I'm unable to fetch username from that page can anyone help me with this the username variable i want to fetch is the username of the user profile which I want to assign to $user_poste_to
I believe, the best way to access the value of $username is to store it to a cookie, once you are in senpost.php, all you need to do is to get the cookie you stored and assign it to $user_posted_to variable. the correct way to get the value of a textbox/form element in by using this $(input[type="text"]).val()
Update your AJax call.
data: {username:username},
here first username will be the index and 2nd username will be the variable which you got using $(this).val()
So, I've been looking for a variety of sources to answer my question the last few day and thus have found nothing that's worked for me. I'll preface this further by saying that in regards to PHP and Javascript I started learning them like a week ago. I also understand that there will likely be better ways to format/write the code I'm about to post so please bear with me! :)
Essentially, I am trying to use a page name play.php in combination with AJAX to echo MYSQL queries back onto the page inside certain page elements.
So the code for main.js which is linked directly to play.php. I've tried about three different way that I've seen in various answers and have not gotten the information I wanted. I either get no response or I get undefined in all of them.
function selectChar(uname, cname)
{
var data = {
username : uname,
charname : cname
};
$.ajax({
data : data,
type : 'Get',
url : 'start.php',
dataType:"json",
success : function (result) {
var data_character = JSON.parse(result);
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
}
});
}
The one above I see most often and the one below I just found earlier today. I get undefined when I attempt to call the array.
function selectChar(uname, cname)
{
$.get("start.php?username="+uname+"&charname="+cname).done(function(data_character){
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
});
}
and finally the PHP code that queries the database and echos the data back.
<?php
$conn = new mysqli($hostname,$username,$dbpassword, $dbname);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_GET['username'];
$charname = $_GET['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
//Send the array back as a JSON object
echo json_encode($result);
?>
I'm not looking for someone to do work for me but I do require some guidance here. What would be an appropriate way to make this work? Is my code terribly incorrect? Am I missing an aspect of this altogether? Please, I would really seriously appreciate any help someone could give me!
P.S. I did just get done reviewing several other similar questions none of which seemed to help. Either there was never a conclusive outcome as to what worked for them or the solution didn't work when I attempted it.
try this:
php get post and return json_encode
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_POST['username'];
$charname = $_POST['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
//Send the array back as a JSON object
echo json_encode($rows);
?>
JS ajax response and request
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
Hey Logan the issue may be with how the AJAX request is being sent. Try adding the processData property to your request and setting it to false. It just means the data won't be read as a query string and it is as raw data.
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
processData: false,
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
I would also try echo json_encode($_POST) to see if the you get the following response back :
{username: "hello", charname: "hl"}
I want to query a mysql table in my project in every 1 minute. I used javascript setInterval method for timing and ajax for sending request and receives output as html. but there is many problems with it:
1- whole website goes very slow only for performing this action.
2- with this I can't query something else from database.
my code is :
function ajaxGetAllOrders(){
$.ajax('<?php echo url()?>/admin/getAllOrders',{
dataType:'json',
async: true,
success:function(data){
$('#page-content').html(data.content);
}
});
}
and interval method:
$(function(){
setInterval('ajaxGetAllOrders();',60000);
ajaxGetAllOrders();
});
I tried to create another connection to database for this but it wont help anyway.
and the php getAllOrders method:
public function getAllOrders(){
if (!$this->isAdmin()){
return;
}
$fields = DB::connection('mysql2')->table('z_orders')->orderBy('id','desc')->get();
$nFields = DB::connection('mysql2')->table('z_food_orders')->orderBy('id','desc')->get();
$count=0;
$i=1;
if (count($fields)>0){
foreach($fields as $field){
$userid = DB::connection('mysql2')->table('z_users')->whereId($field->user_id)->first();
$data['username']=$userid->name;
$data['address'] = $userid->address;
$orderId = DB::connection('mysql2')->table('z_food_orders')->whereOrderId($field->id)->first();
$foodId = DB::connection('mysql2')->table('z_foods')->whereId($orderId->food_id)->first();
$data['foodname'] =$foodId->title;
$data['foodcount'] = $orderId->foodcount;
$foodPrice = $foodId->price;
$count += $foodPrice * $orderId->foodcount;
$i++;
}
$cid = DB::connection('mysql2')->table('z_users')->whereId($userid->id)->first();
$data['customer_id'] = $cid->cctt;
$data['price']=$count;
$data['fields']=$nFields;
}
return response()->json(['content'=>view('admin.orders',$data)->render()]);
}
the whole idea behind this is user orders something.then in admin panel in orders section admin can see all orders. so i want to able that admin won't reload page and in every minute the list of orders show new orders.