passing id information with ajax - php

hi I am trying to identify the table id in a SQL query command.
here is my query command:
$id = $_POST['id'];
$query = " UPDATE cursos
SET status = '$checkboxstatus'
WHERE id='$id'";
all that code is inside a backend.php file which is loaded trought ajax command from the main php file:
this is the AJAX script which I am using:
$(document).ready(function(e) {
$('input[name=status]').change(function(){
if( $('input[name=status]').prop('checked') )
{checkboxstatus = '1';}
else
{checkboxstatus = '0';}
$.ajax({
type: "POST",
url: "checkboxtestbackend.php",
data: {checkboxstatus: checkboxstatus},
the question is for the record to be inserted in the right field inside the database I Have to put inside $id the id of the element from the sql dump which is done on this page.
while($row = mysqli_fetch_array($result))
{ $id = $row['id'];
?><?php echo "<input type='checkbox' id='$id' name='status'"; if($row['status'] == 1){print "checked='checked'"; }echo "/>";
what I think is that I have to send in this command data: {checkboxstatus: checkboxstatus}, also the id but how this can be done ? or if there is a better way let me know

You are not posting "id".
Insert this
var id = $(this).attr('id');
before $.ajax({
Now, Use this
data: {"checkboxstatus": checkboxstatus,
"id":id
},

Use:
$(document).ready(function(e) {
$('input[name=status]').change(function(){
if ( this.checked ) {
checkboxstatus = '1';
} else {
checkboxstatus = '0';
}
$.ajax({
type: "POST",
url: "checkboxtestbackend.php",
data: {
checkboxstatus: checkboxstatus,
id: this.id
},
this is the element that was clicked on.
Notice that I had to change how you set checkboxstatus. You were always getting the status of the first checkbox, not the one that was changed.

You could also post the ID
data: {checkboxstatus: checkboxstatus,id: $('input[name=status]').attr('id') },

Related

Want to make an AJAX call after x sec time interval to load data from the table and append that data into a div

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.

What is return false in jquery and attr + ajax

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 :)

jquery ajax request fails

I'm new to web programming and I'm trying to select value for a selector box based on value selected in another selector box. Below is the jquery code snippet and php script for your reference. thanks for the help in advance.
jquery-ajax code
$(function(){
$("#tier").change(function(){
var formdata = {'tierval':document.getElementById("tier").value};
alert("Selected Tier : "+document.getElementById("tier").value);
$.ajax({
type: "POST",
url: "/includes/getplayers.php",
data: formdata,
success: function(data)
{
alert("called getplayers.php");
$("#opp").empty();
$("#opp").html(data);
},
error:function()
{
alert('ajax failed');
}
});
});
});
php script:
<?php
if (isset($_POST['tierval']))
{
$tier = $_POST['tierval'];
}
$query = "select PlayerID,First_Name from GOFTEL.PLAYER where TierID = $tier";
$result = mysqli_query($pconn, $query);
$row = mysqli_fetch_assoc($result);
while($row)
{
echo '<option value=\"$row[PlayerID]\" > $row[First_Name] </option>';
}
/* free result set */
$result->free();
/* close connection */
$pconn->close();
?>
Since you are already using jQuery consider the below:
var formdata = {'tierval':$("#tier").val};
alert("Selected Tier : "+$("#tier").val);
// or
console.log(formdata); // using the browser console
// or
alert( this.value );
// or
console.log($(this).val())
then you need to output something in the php script, so that #opp actually gets populated with the result, so
$query="select PlayerID,First_Name from GOFTEL.PLAYER where TierID = $tier";
$result=mysqli_query($pconn, $query);
$row=mysqli_fetch_assoc($result);
print $row['First_Name'];
Then evaluate what you get in the console or alerts and go from there.
You need to use below code in php script
while($row=mysqli_fetch_assoc($result)){
echo "<option value=" . $row[PlayerID]. ">" . $row[First_Name] . "</option>";
}

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?

Table doesn't respond to second jQuery request

My PHP script generates a table with rows which can optionally be edited or deleted. There is also a possibility to create a new Row. The PHP is activated through jQuery Events.
Now all works well, I can edit delete and create an Item. After each action which makes use of the PHP script the HTML table gets updated.
But when I try after an Event to do an action again the HTML Table doesn't get updated though in the background the PHP script makes an entry into the database.
Does someone of you know why my HTML Table doesn't update itself when I trigger a second event?
Here is the Script:
PHP
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if($action == "new")
{
mysql_query("INSERT INTO `place` (`id`, `name`) VALUES (NULL, '$name')");
}
elseif($action == "edit")
{
mysql_query("UPDATE `place` SET `name` = '$name' WHERE `id` = '$id'");
}
elseif($action == "delete")
{
mysql_query("DELETE FROM place WHERE id = '$id'");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function (html){
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").live("click", function() {
myvariable5 = $(this).prevAll(".place_name").html();
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none").siblings().find("input[type=text]").val(myvariable5);
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
$.post("place/place_list.php", {action: "edit", name: ""+myvariable1+"", id: ""+myvariable2+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
$.post("place/place_list.php", {action: "delete", id: ""+myvariable3+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {action: "new", name: ""+myvariable4+""}, function (html){$("#place_container").replaceWith(html);});
});
});
I think I know. You do replaceWith instead of append, so your DIV with ID #place_container disappears after the first operation (you are left with only a table in your page), and of course jQuery does not find it and is unable to refresh it with new content from the second operation.
Just use append or, better yet, html methods.
Shouldnt you replace the complete table ?
$("#place_container").html(html);

Categories