AJAX - doesn't return value - javascript

I am trying to show mysql results from images.php to index.php. After I click on one link of my categories(which are named by id) then I want to show values from images.php.
Every category has one <div> which is tagged by id
The script doesn't work well, it only shows Loading...
$("a.load").on('click',function() {
var id = $(this).attr('data-gallery');
$.ajax({
url: 'http://example.com/images.php?c=' + id,
beforeSend: function() {
$("#" + id).html("Loading...");
},
success: function(data) {
$("#" + id).html(data);
}
});
},function() {
var id = $(this).attr('data-gallery');
$("#" + id).html("");
});
Thanks
[EDIT]
Here is my HTML code in index.php
<section class="mainmywork" id="categories">
<div class="container">
<!--<h1 class="myworkheading"><p>CATEGORIES</p></h1>!-->
<?php
foreach($images as $categories) {
echo '<div class="col-lg-4 col-md-6 col-sm-6 col-xs-12 categories">
<a class="load" data-gallery="'.$categories["code"].'" style="cursor: pointer;"><img class="center-block" src="'.showConfigValues("img_source").'/'.$categories["photos_name"].'" alt=""></a>
<a class="load" data-gallery="'.$categories["code"].'" style="cursor: pointer;"><h2><p>'.$categories["name"].'</p></h2></a>
</div>
<div id="'.$categories["code"].'">
</div>';
}
?>
</div>
</section>
and here is the which is in images.php
<?php
if(isset($_GET["c"])) {
$gallery_code = htmlspecialchars($_GET["c"]);
require_once 'init.php';
$db = new DB;
$query = "SELECT *
FROM photos
INNER JOIN gallery
ON gallery.code = photos.gallery_code AND photos.title_photo != 'y'
WHERE photos.gallery_code = '".$gallery_code."' OR gallery.name = '".$gallery_code."'
ORDER BY photos.id";
$photos = $db->get_special($query);
?>
<div id="lk-gallery">
<div class="wrapper">
<main id="main" role="main" class="photo-lk">
<?php
if($photos[0] != '') {
foreach($photos as $image) {
$mask_description = $image["photos_description"];
echo '<img src="'.showConfigValues("img_source").'/'.$image["photos_name"].'" />';
}
}
else
{ echo '<p class="inprogress">Sorry, I am working on this one!<br>Check out my other photos</p>'; }
?>
</main>
</div>
</div>
<div class="lk-gallery-touch">
<div class="flexslider">
<div class="wrapper">
<main id="main" role="main" class="photo-lk">
<ul class="slides">
<?php
if($photos[0] != '') {
foreach($photos as $image) {
$mask_description = $image["photos_description"];
echo '<li><img src="'.showConfigValues("img_source").'/'.$image["photos_name"].'" /></li>';
}
}
else
{ echo '<p class="inprogress">Sorry, I am working on this one!<br>Check out my other photos</p>'; }
?>
</ul>
</main>
</div>
</div>
</div>
<?php
}
?>

Try this:
$("a.load").on('click',function() {
var id = $(this).data('gallery'); // use .data() method
var $id = '#'+id;
$.ajax({
url: 'http://example.com/images.php?c=' + id,
beforeSend: function() {
$id.html("Loading...");
},
success: function(data) {
$id.html(data);
},
error: function(){
$id.html("Error...");
}
});
});

According to the documentation, the second argument to the .on function when there is more than 2 arguments is a selector string, but you have passed what appears to be your desired event handler. The last argument should be the event handler, in your code sample that is:
function() {
var id = $(this).attr('data-gallery');
$("#" + id).html("");
If you remove that last function, leaving just 2 arguments to .on, your handler should be called as expected.

Related

Javascript document ready is not running

This is my html page:
<html>
<div class="panel-body text-center">
<div class="ttl-info">
STOK TM
</div>
<h4 class="show-value">
<span id="stktimur">0</span>
<h4>
</div>
$(document).ready(function(){
$('#stktimur').ambilData({
url : '<?php echo site_url('data/datastk') ?>',
reload: 65,
success: function(dt, th){
$('#stktimur').data('list', dt.data);
if( parseInt($('#stktimur').text()) != parseInt(dt.total) ){
$('#stktimur').text(parseInt(dt.total) )
.textEffect({effect: 'jumble',jumbleColor :'#FFF', letterJumble: txt});
}
}
})
}
</html>
You are missing the <script> tag. Also some formatting issues.
Try it like this:
<div class="panel-body text-center">
<div class="ttl-info">
STOK TM
</div>
<h4 class="show-value">
<span id="stktimur">0</span>
<h4>
</div>
<script>
$(document).ready(function(){
$('#stktimur').ambilData({
url : '<?php echo site_url("data/datastk") ?>',
reload: 65,
success: function(dt, th){
$('#stktimur').data('list', dt.data);
if( parseInt($('#stktimur').text()) != parseInt(dt.total) ){
$('#stktimur').text( parseInt(dt.total) ).textEffect({effect: 'jumble',jumbleColor :'#FFF', letterJumble: txt});
}
}
})
});
</script>
I assume you want to do ajax request while the stktimur is click. The correct code should be like this.
jQuery Ajax
jQuery Click Event Listener
<div class="panel-body text-center">
<div class="ttl-info">
STOK TM
</div>
<h4 class="show-value">
<span id="stktimur">0</span>
</h4>
</div>
<script>
$(document).ready(function () {
$('#stktimur').click(function () {
$.ajax({
url: "<?php echo site_url('data/datastk') ?>",
success: function (dt, th) {
$('#stktimur').data('list', dt.data);
if (parseInt($('#stktimur').text()) != parseInt(dt.total)) {
$('#stktimur').text(parseInt(dt.total)).textEffect({
effect: 'jumble',
jumbleColor: '#FFF',
letterJumble: txt
});
}
}
})
})
});
</script>

Make Load more Button disappear after fetching all data

My code works fine, it displays more users when the load more button is clicked.
my constraint right now is how to remove the Load more button if there is no more value on the response.
This is how my model looks like
public function getFreeAds($page){
$offset = 10*$page;
$limit = 10;
$this->db->select('*');
$this->db->from('escort');
$this->db->where('status', 'Approved');
$this->db->limit($offset ,$limit);
$this->db->order_by("time_stamp, UPPER(time_stamp)", "DESC");
$query = $this->db->get();
return $query->result();
}
My Controller looks like this
public function getCountry(){
$page = $_GET['page'];
$countries = $this->Home_model->getCountry($page);
foreach($countries as $country){
echo
'<div class="col-md-4 col-sm-6">
<div class="portfolio-item">
<div class="thumb">
<a ><div class="hover-effect" data-e_id="'.$country->e_id.'" id="profile2">
<div class="hover-content">
<h1> '.$country->ProfileName.'</em></h1>
<p> '.$country->Height.' CM tall '.$country->BreastCup.' Breast Size <b>Nationality: '.$country->Nationality.' </b></p>
<button type="button" class="btn-info">View More</button>
<button type="button" class="'.$country->confirmstatus.'">'.$country->confirmstatus.'</button>
<div class="top">
</div>
</div>
</div></a>
<div class="image" width="70%" height="1000px">
<img src="uploads/'.$country->ProfilePicture.'">
</div>
</div>
</div>
</div>';
}
exit;
}
Here is my query code that displays the response.
$(document).ready(function(){
getcountry(0);
$("#load_more").click(function(e){
e.preventDefault();
var page = $(this).data('val');
getcountry(page);
});
});
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>Home/getCountry",
type:'GET',
data: {page:page}
}).done(function(response){
$("#show_data").append(response);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
scroll();
});
};
var scroll = function(){
$('html, body').animate({
scrollTop: $('#load_more').offset().top
}, 1000);
};
What you can do is get the next values in the same function and if there are values available you can make an input field(hidden) and then show or hide the button according to its value.
I'm writing a possible solution for your case, comments are mentioned wherever necessary. Remember there are better ways of doing this like using count but this is according to your code. See if it helps you.
Controller
public function getCountry(){
$page = $_GET['page'];
$countries = $this->Home_model->getCountry($page);
$nextValue = $this->Home_model->getCountry($page+1); // get the values for the next page
$showButton = !empty($nextValue) ? 'yes' : 'no'; // show the button if next value exists
foreach($countries as $country){
echo
'<div class="col-md-4 col-sm-6">
<div class="portfolio-item">
<div class="thumb">
<a ><div class="hover-effect" data-e_id="'.$country->e_id.'" id="profile2">
<div class="hover-content">
<h1> '.$country->ProfileName.'</em></h1>
<p> '.$country->Height.' CM tall '.$country->BreastCup.' Breast Size <b>Nationality: '.$country->Nationality.' </b></p>
<input type="hidden" class="showButton" value="'.$showButton.'" />
<!-- make a hidden input field and assign a value (yes/no) -->
<button type="button" class="btn-info">View More</button>
<button type="button" class="'.$country->confirmstatus.'">'.$country->confirmstatus.'</button>
<div class="top">
</div>
</div>
</div></a>
<div class="image" width="70%" height="1000px">
<img src="uploads/'.$country->ProfilePicture.'">
</div>
</div>
</div>
</div>';
}
exit;
}
View
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>Home/getCountry",
type:'GET',
data: {page:page}
}).done(function(response){
$("#show_data").append(response);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
// check the value of input field
if($('.showButton:last').val() == "no"){
$('#load_more').hide(); // hide the button
}
scroll();
});
};
Add to your response metadata with total pages count. During every request make count query to your DB with same clauses. In your JS code after every request compare current page with total pages from response and hide button if last page reached.

Modal window will not open after paginating retrieved data from the database

I have built an image gallery using the Bootstrap framework, php, SQL and jQuery where users can click a thumbnail to see their selected image enlarged inside a modal window. All the images are stored in a database. The code worked as expected until I paginated the gallery. Now, when a thumbnail is clicked, the modal window does not open. Can anyone suggest a fix for this problem? I have tried some solutions myself but none have worked so far. Many thanks.
gallery.php code:
<div class='row' id='pagination_data'>
<!--Fetch and display images from database -->
<?php ?>
</div>
<!--Bootstrap modal window -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal"><span aria- hidden="true">×</span><span class="sr-only">Close</span></button>
<img src="" class="imagepreview" style="width: 100%;" >
</div>
</div>
</div>
</div>
<script>
//PAGINATION SCRIPT
$(document).ready(function(){
//when fucntion is called fetch data from gallery table
load_data();
function load_data(page) {
$.ajax({
url:"pagination.php",
method: "POST",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function() {
var page = $(this).attr("id");
load_data(page);
});
});
</script>
<script>
//MODAL SCRIPT
$(function() {
$('.pop').on('click', function() {
$('.imagepreview').attr('src', $(this).find('img').attr('src'));
$('#imagemodal').modal('show');
});
});
</script>
pagination.php code:
$record_per_page = 18;
$page = ''; //store current page number
$output = '';
//check if page variable is present
if (isset($_POST["page"])) {
//ajax function
$page = $_POST["page"];
} else {
$page = 1;
}
$start_from = ($page - 1) * $record_per_page;
$query = "SELECT * FROM gallery ORDER BY id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
$img = $row["path"];
$uploadDate = $row["uploadDate"];
$img = "<img id='modalImg' src='useruploads/" . $row['path'] . "' style='max-width: 100%; height: auto;'/>";
$output .= "
<div class='col-md-4 mainGalleryImg'>
<div class='myImg'>
<div class='pop'>
$img
</div>
<br>
</div>
</div>
";
}
$output .= "<div class='col-md-12' align='center'> <nav aria-label='Page navigation example'>
<ul class='pagination justify-content-center'> <li class='page-item'>
<a class='page-link' href='#' aria-label='Previous'>
<span aria-hidden='true'>«</span>
<span class='sr-only'>Previous</span>
</a>
</li>";
$page_query = "SELECT * FROM gallery ORDER BY id DESC";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for ($i=1; $i <=$total_pages; $i++) {
$output .="<span class='pagination_link page-link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
$output .= " <li class='page-item'>
<a class='page-link' href='#' aria-label='Next'>
<span aria-hidden='true'>»</span>
<span class='sr-only'>Next</span>
</a>
</li></ul>
</nav> </div>";
echo $output;
Bootstrap version: 4.4.1
jQuery version: https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
$('.pop').on('click', function() { only attaches the handler to elements currently in DOM. Since you call it before you even retrieved the images it does nothing.
You need to use delegated event handlers.
$(document).on('click', '.pop', function() {

Ajax result not being loaded in div

I am sending a value to a php script and want to show the result of that script inside a div on my homepage, but somehow nothing is shown. When I check the network settings I can see the value is correctly posted to the php script.
My code:
On my index:
<li class="active lidcat">
<input type="radio" name="bedno" '.$checked.'>
<a class="zoekvalue" href="'.$void.'">'.$ledeninfo['title'].'</a>
</li>
<div id="result">
</div>
My js file:
<script>
$(document).ready(function () {
$(".lidcat").click(function () {
var zoekvalue = $(this).children(".zoekvalue").text();
var posting = $.post("includes/leden.php", {zoekwaarde: zoekvalue});
posting.done(function (data) {
var content = $(data).find("#content");
// Gooi $result eerst leeg voordat de inhoud wordt getoond vanwege vorige ajax requests
$("#result").empty().append(content);
console.log(zoekvalue);
});
});
});
</script>
And finally my php file:
<div class="blog-content" id="content">
<div class="home-wrapper">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h2 class="osLight">Onze leden</h2>
<div class="row">
<?php
$zoekwaarde = $_POST['zoekwaarde'];
echo $zoekwaarde;
// De leden zelf worden hiermee opgehaald
$ledeninfo1 = "
SELECT ct.id, ct.catid, ct.title as content_title, ct.alias, ct.introtext, ct.state, ct.images, ct.ordering , cn.id, cn.title as category_title
FROM snm_content ct
INNER JOIN snm_categories cn
ON ct.catid = cn.id
WHERE ct.catid IN (" . $useableids . ")
AND ct.state = 1
AND ct.title LIKE %" . $zoekwaarde . "%
ORDER BY ct.ordering";
$ledeninfocon1 = $conn->query($ledeninfo1);
while ($ledeninfo1 = $ledeninfocon1->fetch_assoc()) {
$ledenimage = $ledeninfo1['images'];
$ledenimg = json_decode($ledenimage);
if ($ledenimg->image_intro != '') {
$image = '<img class="ledenimg" src="cms/' . $ledenimg->image_intro . '" alt="image">';
} else {
$image = '<img class="ledenimg" src="cms/images/afbeeldingen/logo.jpg" alt="image">';
}
if (strlen($ledeninfo1['introtext']) > 150) {
$shortstr = substr($ledeninfo1['introtext'], 0, 150) . '...';
} else {
$shortstr = $ledeninfo1['introtext'];
}
$ledenoverzicht .= '
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="article">
' . $image . '
<div class="article-category">' . $ledeninfo1['category_title'] . '</div>
<h3 class="osLight">' . $ledeninfo1['content_title'] . '</h3>
<p>' . strip_tags($shortstr) . '</p>
</div>
</div>';
}
echo $ledenoverzicht;
?>
</div>
</div>
</div>
</div>
</div>
The php works so that is not the issue, and even if it didn't I would probably see an error in the result div, or at least the h2 tag.
The value of zoekwaarde is correctly sent it shows a 200 status to leden.php
Am I missing something? I got the code from the official jquery website.

Submitting multiple dynamic forms

I'm trying to submit multiple forms at once when a single button is clicked. These forms are all generated automatically. They all have different action urls but the same id's. That's how the system (SaaS) works.
The problem is that I'm having issues getting the correct selectbox values and then send the forms. I'm not getting any error but I think it has something to do with identifiers. I'm working on this one for a few days now and I can't figure this one out.
So for every set/product there's some empty html, like so:
HTML
<div id="sets" class="clearfix">
// first set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// second set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// etc... can be as much as 10 sets
</div><!-- .#sets -->
Inside the above HTML .product there comes an automatically generated form. This form is generated like so:
Jquery
$('#sets .set').each( function(){
$(this).click(function(){
if($(this).hasClass('open')){
$('.close').click(function(){
$('#sets .product').fadeOut();
$('.products',this).animate({
width: 'toggle'},500, function() {
.......
});
});
} else {
.....
}
var url = $(this).data('handle')+'?format=json';
$.getJSON(url, function (data){
var product = data.product;
var $container = $('.products .product');
var productsHtml = [];
var fullurl = 'http://www.shop.com';
var variants = '';
$.each(product.related, function(index, rel){
var url = ''+fullurl+''+rel.url+'?format=json';
...... etc ...
var productHtml = '<div id="'+rel.id+'" class="p"><form method="post" id="product_configure_form" action="http://www.shop.com/cart/add/'+rel.vid+'/" name="formsub"><div class="foto"><img class="rollover" src="'+image+'" hover="'+image2+'" alt="'+rel.fulltitle+'"/></div><div class="prijs" data-price="'+rel.price.price_incl+'">€'+rel.price.price_incl+'</div><div class="varianten_'+rel.id+'">';
$.getJSON(url, function (data){
var rel = data.product;
var wqsSelectVariants = $('<div class="product-configure-variants tui" />');
var select = $('<select id="product_configure_variants"/>');
$.each(rel.variants, function (index, variant){
select.append('<option value=' + variant.id + '>' + variant.title + '</option>');
wqsSelectVariants.append(select);
});
$('.varianten_'+rel.id).html(wqsSelectVariants);
});
var price = rel.price.price_incl;
sum += price;
productHtml = productHtml + '</div></form></div>';
productsHtml.push(productHtml);
});
$('.total').text('€'+sum.toFixed(2));
productsHtml = productsHtml.join('')
$container.html(productsHtml);
});
}
});
});
etc....
<script type="text/javascript">
$(document).ready(function(){
$(".trigger").on("click", function(e){
e.preventDefault();
$('form[name="formsub"]').each(function(){
var variant = $('#product_configure_variants').val();
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action')+variant+'/?quantity=1',
data: $form.serialize(),
success: function(data, status){
if(status == 'success'){
}else if(status == 'error'){
}
}
});
});
});
});
</script>
Does anyone know what's going wrong or give me some directions on how to fix that?
Try using $('form[name="formsub"]:visible') as your selector. That should give you just the visible forms instead of all the ones on the page.

Categories

Resources