I'm trying to make a like button, but i can't send proper query from a loop.
this is my sample code:
$supql="SELECT * FROM `tbl_users_posts`";
$rez=mysqli_query($conn,$supql);
while ($row=mysqli_fetch_assoc($rez)){
$psid=$row['id'];
echo $row['post']."<br>";
$squlk="SELECT uid FROM t_plik WHERE pid='$psid' AND uid='$uid'";
$msqs=mysqli_query($conn,$squlk);
$asnu=mysqli_num_rows($msqs);
if($asnu==0){?>
like
<?php }else{ ?>
unlike
<?php }
}
i try send this query:
if(isset($_POST['liked'])){
$pstid=$_POST['postid'];
$inslik="INSERT INTO t_plik (pid,uid)VALUES('$pstid','$uid') ";
mysqli_query($conn,$inslik);
}
with this jquery code:
<script>
$(document).ready(function() {
//when click on like
$('.like').click(function(){
var postid = $(this).attr('id');
$.ajax({
url:'test.php',
type:'post',
async: false,
data:{
'liked': 1,
'postid':postid
},
success:function(){
}
});
});
});
</script>
but every time when i click like button i can send query for last post id. how can i affect other postids inside the while?
thanks
Related
Student.php -here i am getting list of students from a specific Institution in a tag
<?php
if(isset($_POST['c_id'])) { //input field value which contain Institution name
$val=$_POST['c_id'];
$sql="select RegistrationId from `students` where `Institution`='$val' ";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$number=$row['RegistrationId'];
?>
<a href='<?php echo "index.php?StudentID=$number"; ?>' target="index" id="link">
//getting student id in the dynamic link
<?php echo "$number";
echo "<br/>";
}}
?>
<div id="index" name="index"> </div>
<div id="Documents"> </div>
<script>
$(document).on('change', 'a#link', function()
{
$.ajax({
url: 'Documents.php',
type: 'get',
success: function(html)
{
$('div#Documents').append(html);
}
});
});
</script>
In index.php - I am Getting students details based on $_GET['StudentID'] ('a' tag value)
<?php
$link=$_GET['StudentID'];
$sql = "select StudentName,Course,Age,Address from `students` where `RegistrationId`="."'".$link."'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['StudentName']."<br/>";
echo $row['Course']."<br/>";
echo $row['Age']."<br/>";
echo $row['Address']."<br/>";
}
?>
In Documents.php -I am getting documents related to the speific student selected in 'a' tag
$link=$_GET['StudentID'];
$qry = "select Image,Marksheet from `documents` where `RegistrationId`='$link'";
$result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$image = $row["Image"];
$image1 = $row["Marksheet"];
echo '<embed src='. $image.'>';
echo ' <object data='. $image1.'width="750" height="600">';
echo ' </object>';
}
On click of student id i am trying to get result from index.php to div()
and result from Documents.php to div()
(i.e)two target for one click in tag
My code only take me to the index.php file result in a new Window
Please Help me to solve this problem
(sorry if my question seems silly i am new to php)
Update:
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
});
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
From your question, it seems that you want to load the two results, one from index.php and one from Documents.php in two separate divs on the same page when the link is clicked.
But you're using a change event on the link, not a click event. The change event is not fired when the link is clicked, so JavaScript does not get executed and the page loads to the URL specified in the href attribute of the link. So first you need to change $(document).on('change') to $(document).on('click').
Furthermore, since you want two results to load - one from index.php and one from Documents.php, you'll need to create two ajax requests, one to index.php and the other for Documents.php. In the success function of each of the ajax requests, you can get the response and put it in the corresponding divs.
In addition to this, you'll also need to prevent the page from loading to the new page specified in href attribute when the link is clicked, otherwise the ajax requests fired on clicking the link will get lost in the page load. Thus, you need to add a e.preventDefault(); to your onclick event handler like this:
$(document).on('click', 'a#link', function(e) {
// Stop new page from loading
e.preventDefault();
// Two ajax requests for index.php and Documents.php
});
Update: You don't need to add two click handlers for each ajax request. Inside one click handler, you can put both the ajax requests.
Also your event handlers won't register if you're adding them before jQuery, or if you're adding them before the DOM has loaded. So move your code to bottom of the HTML page, just before the closing </body> tag.
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Link
You can change your <a> tag like below :
..
Then , in your jquery code do below changes :
$(document).on('click', 'a.link', function(e) {
var StudentID = $(this).attr("data-id") //get id
console.log(StudentID)
e.preventDefault();
$.ajax({
url: "details.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
call_next_page(StudentID);//next ajax call
}
});
});
function call_next_page(StudentID) {
$.ajax({
url: "index.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
}
});
}
And then at your backend page use $_POST['StudentID'] to get value of student id instead of $_GET['StudentID'];
I want to increment count field in database when a link is clicked in php file.
So, I've added the following jquery part to my .php file. But still, it doesn't work. Please help!
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
You made a several mistakes in your code.
Update
You can send your SID input type text from ajax with data and you can get the value in your php file with the $sid = $_POST['sid'].
<body>
click here
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
After the ajax success response you can make redirect to your desire location.
Code.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
in code.php in mysqli_close you should use $conn not $connection.
Go with this code. It might help you. I have just tested all the things in localhost. This is working perfect.
use preventDefault() when click event is called.check jquery :
<body>
click here
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
Redirect your link on ajax success. Like this -
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".Categories").click(function () {
var catId = $(this).attr('id');
catId = String(catId);
jQuery.ajax({
url: "index.php",
data: { catId },
type: "POST",
success: function (data) {
$("#categoryField").html(data);
}
});
});
});
</script>
I need to pass my clicked button id to the same index.php page, without page refreshing and work with that id value.My code is wrong, because page is rendered second time.
Here is my php code:
<?php
$category=$user_home->runQuery("SELECT DISTINCT category FROM products");
$category->execute();
$categoryArray=$category->fetchAll(PDO::FETCH_ASSOC);
foreach($categoryArray as $listID){
?>
<input type="button" id="<?php echo $listID['category']?>" class="Categories" value="<?php echo $listID["category"]?>"/><br>
<?
}
?>
Call preventDefault method inside the button click event handler to prevent default button behaviour ("page is rendered second time"):
...
$(".Categories").click(function (e) {
e.preventDefault();
...
There is a syntax error in your code
$(document).ready(function () {
$(".Categories").click(function () {
var catId = $(this).attr('id');
catId = String(catId);
jQuery.ajax({
url: "index.php",
data: { catId: catId },
type: "POST",
success: function (data) {
$("#categoryField").html(data);
}
});
});
});
You have to pass data in valid literal object format. {"property_name": "property_value"}.
Change: data: { catId } to data: { "catId": catId }
For server side:
<?
if (isset($_POST['catId'])) {
/* YOUR CODE FOR CATEGORY */
$catId = intval($_POST['catId']);
echo 'SUCCESS';
exit(0);
}
// YOU OTHER PHP CODE
?>
I think I need to post my variable to another page and then return it.I dont know how to do it in same page.This variant with exit(0) is bad because all variables inside if statement after exit(0) will be deleted.
<?
if (isset($_POST['catId'])) {
/* YOUR CODE FOR CATEGORY */
$catId = intval($_POST['catId']);
echo 'SUCCESS';
exit(0);
}
// YOU OTHER PHP CODE
?>
I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="some-class"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
url: "foo.php",
type: "POST",
data: "id=" + somedata,
success: function(){
$("#someid").html();
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
<?php
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['info'];
}
mysqli_close($con);
?>
This what i have in HTML file:
<p id="someid"></p>
Data1
Data2
Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file
You have a few problems:
You are not using the data as mentioned in the other answers:success: function(data){
$("#someid").html(data);
},
You are not cancelling the default click action so your link will be followed:$('a[class="some-class"]').click(function(e){
e.preventDefault();
...;
As the id's are integers, you can use data: "id=" + somedata, although sending an object is safer in case somedata contains characters that need to be escaped:data: {"id": somedata},;
You have an sql injection problem. You should cast the variable to an integer or use a prepared statement:$data = (int) $_POST['id'];;
As also mentioned in another answer, you have two $(document).ready() functions, one wrapping the other. You only need one.
success: function(){
$("#someid").html();
},
should be:
success: function(data){
$("#someid").html(data);
},
You should add parameter in success
success: function(data){ //Added data parameter
console.log(data);
$("#someid").html(data);
},
The data get the values what you echo in PHP end.
This:
success: function(data){
$("#someid").html(data);
},
and you have two document ready, so get rid of:
$(document).ready(function () { ...
});
data: "id=" + somedata,
Change it to:
data: { id : somedata }
I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>
Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)
<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>