Fetch result in Jquery Lightbox using PHP/Ajax - php

I'm trying to fetch information (u_name and u_email) from database using AJAX into a JQuery lightbox. I'm having problems with the Ajax part.
My HTML structure is:
<div class="boxes">
Show it
</div>
<div class="boxes">
Show it
</div>
So, the user clicks on one of the id, which is matched in the database table, and the result is fetched.
The Javacript code is:
$(function() {
$('#id').ecko({ //ecko is a JQuery lightbox function which im using
height: 200,
holderClass: 'custom',
template: '<p>About</p>' +
'<div>' +
'u_name' +
'u_email' +
'More' +
'</div>'
});
});
The Ajax will be:
$.ajax({
url: 'functions/db.php',
data: "",
dataType: 'json',
success: function(data){
var name = data[0];
var email = data[1];
//What should be here??
} });
PHP code will be like:
$result = mysql_query("SELECT * FROM $tableName WHERE `id` = " what should be written here? ");
$array = mysql_fetch_row($result);
echo json_encode($array);
I've posted everything I tried. I don't know a way of connecting the id clicked to pass it to php's line of $result = mysql_query("SELECT * FROM $tableName WHEREid= "") and then connecting Ajax and the Jquery lightbox.

When someone clicks the button, pass the ID to the data option in ajax, and fetch it on the serverside:
$('.button').on('click', function() {
$.ajax({
type: 'POST',
url: 'functions/db.php',
data: {id: this.id},
dataType: 'json'
}).done(function(data) {
$('#id').ecko({
height: 200,
holderClass: 'custom',
template: '<p>About</p>' +
'<div>' +
''+data[0]+'' +
''+data[1]+'' +
'More' +
'</div>'
});
});
});
Then use the data in the markup, but you can only do that once the ajax call is completed.
PHP
$id = $_POST['id'];
$result = mysql_query("SELECT * FROM $tableName WHERE `id` = " $id);
consider moving onto PDO, as mysql is deprecated!

Related

problem to print result after ajax success

Please help to fix this issue with like counting.
i create a news feed like facebook using php mysql and ajax.
problem is that when i click on like button it prints like count from (this value) and showing to all, let say i have 5 posts and like current value for different posts are 100, 200 , 70 , 80 , 578. when I click on first post ajax success count 100+1 = 101 for first post and for all other post printting same 101 likes. now if i will go to 2nd post and its like value 200, ajax will show 200+1 =201 like. so after click on 2nd post all 5 posts like will show 201. its creating problem for me. I understand that after ajax success i mentioned to show the value to div class (.ajax_like_result), thats why its showing in every post, same result until i am not clicking on different post.
how to fix this so that when I click on any post it wil show only its real like value??
I try to change the DIV attribute id , instead of class then it only works for first post. other post totally not working. if i set div atribute to class then like is working but printing incorrectly as i mentioned above.
I have pasted below- html , php and ajax code . thanks for your help.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.ajax_like').on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(".ajax_like_result").html(data);
}
});
});
});
</script>
html :
<li class="ajax_like" type="submit" name="data-id" data-id="<?php echo $page;?>" value="<? echo $post_id;?>">
<div class= "ajax_like_result" ><?php print $likes;?></div>
</li>
like.php code :
<?php //user info start
session_start();
$conn=mysqli_connect("localhost", "u1068033_ab24", "ab#24", "u1068033_ab24");
mysqli_set_charset($conn,"utf8");
$id=$_SESSION['id'];
$get_post_id = $_POST['post_id'];
$page = $_POST['page'];
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
$likes=$row['likes'];
$sql="UPDATE $page SET `likes`=$likes+1 WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
echo $row['likes'];`enter code here`
?>
You should need some corrections on your jQuery
$(document).ready(function(){
$('.ajax_like').each( function(){
$(this).on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(this).find(".ajax_like_result").html(data);
}
});
});
})
});
you are writing the result to all HTML elements with the same class "ajax_like_result" when using this line:
$(".ajax_like_result").html(data);
you can use something such as:
$("li[data-id='"+page+"'] div.ajax_like_result").html(data);
Also better using native JavaScript and not jQuery, using document.querySelector
document.querySelector(`li[data-id='${page}'] div.ajax_like_result`).innerHTML = data;
and replace the jQuery AJAX with the native JavaScript fetch
example in one piece of code block with native JavaScript (no need for jQuery):
document.addEventListener("DOMContentLoaded", (event) => {
document.querySelectorAll('li[data-id]').forEach((elem)=>{
elem.addEventListener('click', event => {
const domElem = event.target;
const postId = domElem.getAttribute('value');
const page = domElem.getAttribute('data-id');
const data = {post_id:postId, page:page};
console.log({data});
fetch('like.php', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
const selector = `li[data-id='${page}'] div.ajax_like_result`;
document.querySelector(selector).innerHTML = data;
})
.catch((error) => {
console.error('Error:', error);
});
});
});
});
and better also to remove from the PHP code the '?>' as the PHP ends the script execution at the end and it will reduce some possible unwanted white spaces.

How can I select multiple ids generated by a loop dynamically in Jquery and pass them to AJAX?

Ok , I am trying to get different id values through Jquery , and pass them to Jquery AJAX that will hit a PHP file so I can get some data back .... I'm not sure how to get all the multiple different ids because Jquery is only getting the first id of many of the unique id values generated by the while loop .. and I would like each unique ID to also be passed to the AJAX function in Jquery .. Your help would be so much appreciated . I'm still new to the Jquery world
<?php
require('../database/connection.php');
?>
<script type="text/javascript">
jQuery(document).ready(function() {
var ID = $('div#opposition img').attr("id"); alert(ID);
$.ajax({
type:'GET',
url :'get_users_images.php',
data:'screen_name='+ ID,
success: function(result){
$('div#opposition img').attr('src', result);
}
});
});
</script>
<?php
$select2 = "SELECT * FROM AUTHORS WHERE ID <> $id";
$result2 = mysql_query($select2);
$result_count = mysql_num_rows($result2);
echo '<div id ="opposition">';
while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo "<img id ='".$row2['Twitter']."' src='images/ajax-loader.gif' class ='image".$row2['Twitter']."'/>"; // echos different ids,
}
?>
</div>
You can send an stringified array of id's like this -
jQuery(document).ready(function () {
var ID = $('div#opposition img').map(function(){
return this.id;
}).get();
$.ajax({
type: 'GET',
url: 'get_users_images.php',
data: { screen_name : JSON.stringify(ID)},
success: function (result) {
$('div#opposition img').attr('src', result);
}
});
});
If I am correct, Actually , why you are placing the set of images returned by php in one
img tag, $('div#opposition img').attr('src', result); . Rather I think you must do something like $('div#opposition').innerHTML(result) .

Post ajax to PHP - variable isn't being uploaded

I am trying to pass a variable from my ajax to my php script. I can't see to get it to work. It keeps on giving me NULL when I do a var_dump on the variable.
JQUERY:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: id
});
LinkUpload(id);
function LinkUpload(id){
$("#link-upload").dialog();
}
});
});
</script>
PHP:
$id = $_POST['id'];
$query = mysql_query("SELECT * FROM xcart_slideshow_slides where slideid='$id'")or die(mysql_error());
$sli = mysql_fetch_array($query);
$slide_id = $sli['slideid'];
$link = $sli['link'];
var_dump($id);
I need the $id variable to post so I can dynamically change the dialog box when the click function is activated.
EDIT:
So I have changed some of my coding:
Jquery:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.post(
"slide-show-link.php",
{ id: id },
function(data,status){alert("Data: " + data + "\nStatus: " + status); }
);
// alert(id);
LinkUpload(id);
});
function LinkUpload(id){
$("#link-upload").dialog();
}
});
I wanted to see if the data was in fact being passed so I threw an alert in the .post. This is the error I'm getting now:
I have tried passing plain text and echoing it back on the page but it fails. It is just not passing.
Try this -
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: { id : id }
});

jQuery lightbox from database through PHP/Ajax forces to double click the first time

It's a weird issue. I've to click on certain buttons (having some ids). The id is passed through Ajax in a PHP script. That id is searched in the database, and the matching entries are passed as data in which is shown in my jQuery lightbox. However, I have to double-click on the button for the first time.
My HTML structure is as follows:
<div class="boxes">
Show it
</div>
<div class="boxes">
Show it
</div>
And the Javascript function is:
$('.button').click( function() {
$.ajax({
type: 'POST',
url: 'functions/db.php',
data: {id: this.id},
dataType: 'json'
}).done(function(data) {
$('#'+data[0]).avgrund({
//data [0] is both the id being clicked and that stored in the database
height: 200,
holderClass: 'custom',
showClose: true,
template: '<p>'+data[2]+'</p>' +
'<div>' +
''+data[0]+'' +
''+data[1]+'' +
'More' +
'</div>'
});
});
});
My relevant PHP script:
$id = $_POST['id'];
$result = mysql_query("SELECT * FROM `eventdetails` WHERE `id` = '".$id."'");
$array = mysql_fetch_row($result);
echo json_encode($array);
I'm running the files on an XAMPP server on Windows 7. Is it normal that I've to double click for the first time? How can I improve it?
EDIT #1
One of the users suggested of using success instead of done in Ajax. Still, it requires a double-click. Here's the javascript code using success in Ajax.
$('.button').click( function() {
$.ajax({
type: 'POST',
url: 'functions/db.php',
data: {id: this.id},
dataType: 'json',
success:(function(data) {
$('#'+data[0]).avgrund({
height: 200,
holderClass: 'custom',
showClose: true,
template: '<p>'+data[2]+'</p>' +
'<div>' +
''+data[0]+'' +
''+data[1]+'' +
'More' +
'</div>'
});
})
});
});
to init avgrund with ajax data set its special param called "openOnEvent" to "false"
it will look like
$.ajax({
type: 'POST',
url: 'testpost.php',
dataType: 'json',
data: { id: this.id },
success: function(id) {
$('#' + id).avgrund({
openOnEvent: false,
height: 200,
template: '<p>content <b>' + id + '</b> here!</p>'
});
}
});
docs - https://github.com/voronianski/jquery.avgrund.js#update-sep-30-2012
test page - http://labs.voronianski.com/test/test-avgrund.html

how to pass multiple values to a function in jquery to

I have this list of comments that i want to remove from database using AJAX, and fadeout from current view with Javascript.
I call this function removeComment() which sends ID of div to be removed to server ( ID is also row id in database )
The problem i have is, after i run the function first time, it stops working.
jquery code
function removeComment(PostId) {
var commentid = 'com' + PostId;
$(document).ready(function() {
$(commentid).fadeToggle('slow');
// send to php script
$.ajax({
type: 'POST',
cache: false,
url: 'actions/adminProcessor.php',
data: 'action=removeComment' + '&PostId=' + PostId,
success: function(done) {
alert(done);
}
});
}); // <-- Sorry, was missing a '}'
}
and below is the html of the comment list and how the functionis called
<div class="comments" id="com3">
<label><admin>UD</admin></label>Remove
<span>17/09/12</span>
<p>adfadfadfadf</p>
</div>
<div class="comments" id="com3">
<label><admin>UD</admin></label>Remove
<span>17/09/12</span>
<p>adfadfadfadf</p>
</div>
please i would like to know where i got it wrong
below is the php script
if($action == "removeComment"){
extract($_POST) ;
$query = "DELETE FROM comments WHERE id = '$cId'" ;
$result = mysql_query($query);
}
You should not wrap your behavior into a $(document).ready function. You should read more about what $(document).ready means. This code should work now:
function removeComment(PostId) {
var commentid = 'com' + cid;
var coms = document.getElementById(commentid);
$(coms).fadeToggle('slow');
$.ajax({
type: 'POST',
cache: false,
url: 'actions/adminProcessor.php',
data: 'action=removeComment' + '&PostId=' + PostId,
success: function (done) {
alert(done);
}
});
}

Categories