Ajax result not being loaded in div - javascript

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.

Related

Codeigniter 4: failed to decrypt encrypted post data

Sorry for my English
I'am newbe in Codeigniter 4. I try to decrypt data from encrypted post request. I'm succeed encrypted my data in views, but can't to decrypting back again in my controller after post it with javascript. Here my code
My Controller
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\Store_MDL;
class Home extends BaseController
{
protected $ProductModel;
protected $request;protected $session;protected $encrypt;
public function __construct() {
$this->ProductModel = new Store_MDL();
$this->request = \Config\Services::request();
$this->encrypt = \Config\Services::encrypter();
$this->session = \Config\Services::session();
$this->session->start();
}
public function index()
{
$data['encrypter'] = $this->encrypt;
return view('home_page', $data);
}
public function encthis()
{
$val = $_POST['str'];
$encrypters = $this->encrypt;
//$ciphertext = $encrypters->encrypt('My secret message');
echo $encrypters->decrypt($val);
//echo $val;
return view('product/product-v');
}
}
here my views home_page.php
<?php $n=0; foreach ($product as $rows){
$n++;
//echo count($rows);
if($n < count($rows)){
$dev = '<div class="divider mb-3 mt-n2"></div>';
}else{$dev = '';}
if($n % 2 == 0){
echo '<a href="#" value = "'.base_url().'/home/encthis" data-v="'.$encrypter->encrypt($rows['prno']).'" class = "n-link"><div class="row">
<div class="col-6">
<h1 class="font-20 mb-0 line-height-l">'.$rows['prname'].'</h1>
<p class="mb-3">
'.$rows['prdescription'].'
</p>
<h2 class="font-16 mb-0">Rp. '.$rows['prprice'].'</h2>
</div>
<div class="col-6">
<img src="'.base_url().'/public/uploads/'.$rows['prpath'].'/'.$rows['primage'].'" class="img-fluid rounded-circle shadow-xl">
</div>
</div></a>'.$dev;
}else{
echo '<a href="#" value = "'.base_url().'/home/encthis" data-v="'.$encrypter->encrypt($rows['prno']).'" class = "n-link"><div class="row">
<div class="col-6">
<img src="'.base_url().'/public/uploads/'.$rows['prpath'].'/'.$rows['primage'].'" class="img-fluid rounded-circle shadow-xl">
</div>
<div class="col-6">
<h1 class="font-18 mb-0 line-height-l">'.$rows['prname'].'</h1>
<p class="mb-3">
'.$rows['prdescription'].'
</p>
<h2 class="font-16 mb-0">Rp. '.$rows['prprice'].'</h2>
</div>
</div></a>'.$dev;
}
} ?>
than here my script
<script>
$('.n-link').on('click', function () {
var link = $(this).attr('value');
var pos = $(this).attr('data-v');
$.post(link, { str:pos})
.done(function(data) {
document.getElementById("context").innerHTML = data;
});
});
</script>
I always get notification 500 (Internal Server Error).
After struggling hours, i find some clue,
just change
$encrypter->encrypt($rows['prno']);
with base64_encode($encrypter->encrypt($rows['prno']));
and in controller,
change
$encrypters->decrypt($val);
with $encrypters->decrypt(base64_decode($val));
Hope its useful

Laravel AJAX get request return 500 (Internal Server Error)

I am trying to make a search bar with AJAX, but I keep getting Internal Server Error.
This is my Document Ready code.
$(document).ready(function(){
fetch_ads_data();
function fetch_ads_data(query = ''){
$.ajax({
url:"{{route('adSearch.action')}}",
method: 'GET',
data:{query:query},
dataType:'json',
success:function(data){
$('#total_ads').html(data.total_ads);
}
});
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_ads_data(query);
});
});
The Route is under a route group (LaraCast).
Route::get('/AdsController/action', 'AdsController#action')->name('adSearch.action');
This is the function inside the controller.
public function action(Request $request){
if($request->ajax()){
$query = $request->get('query');
if($query != ''){
$data = Ad::orderBy('created_at', 'desc')->where('title','like', '%'.$query.'%');
}else{
$data = Ad::orderBy('created_at', 'desc');
}
$total_ads = $data->count();
if($total_ads > 0){
foreach($data as $ad){
$output .= '
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="featured-box">
<figure>
<div class="icon">
<i class="lni-heart"></i>
</div>
<img class="img-fluid" alt="">
</figure>
<div class="feature-content">
<div class="product">
<i class="lni-folder"></i> Real Estate
</div>
<h4>'.$ad->title.'</h4>
<span>Last Updated: '.$ad->updated_at.'</span>
<ul class="address">
<li>
<i class="lni-map-marker"></i> Dallas, Washington
</li>
<li>
<i class="lni-alarm-clock"></i> '.$ad->created_at.'
</li>
<li>
<i class="lni-user"></i> John Smith
</li>
<li>
<i class="lni-package"></i> Used
</li>
</ul>
<div class="listing-bottom">
<h3 class="price float-left"> ' .$ad->price. '</h3>
</div>
</div>
</div>
</div>
';
}
}else{
$output .= '
<p>No Ads Found</p>
';
}
$data = array(
'total_ads' => $output
);
echo json_encode($data);
}
}
The error that keeps appearing in the console is:
app.js:1 GET http://localhost:8000/ar/AdsController/action?query= 500
(Internal Server Error)
send # app.js:1
ajax # app.js:1
fetch_ads_data # ads:312
(anonymous) # ads:310
j # jquery-min.js:2
fireWith # jquery-min.js:2
ready # jquery-min.js:2
I # jquery-min.js:2
There are two string operators in PHP. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
in your case, you use (.=) operator, that's mean you need to declare the variable first.
$output="";
if($total_ads > 0){
$output.="...";
}

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() {

Getting "Parameter undefined" in jQuery with AJAX, MySQL and PHP

I'm building a shopping site in PHP with mysqli database and I have a "category" and a "brands" sections in that.
What I want is that the user can filter the products in the store by clicking on category & brands section without page refreshing with help of ajax jQuery.
For example on Category>Electronics and it will show him the Electronics products on site main page.
Maybe with the code, it will be clearer.
This is the part of the HTML:
<div class="panel panel-info">
<div class="panel-heading">Products</div>
<div class="panel-body">
<div id="getProduct"></div>
</div>
This is the PHP code in the "action.php" file:
<?php
if(isset($_POST["getSelectedCategory"])){
$cid=$_POST["categoryID"];
$sql="SELECT * FROM products WHERE productCat = '$cid' ";
$run_query=mysqli_query($con, $sql);
while($row=mysqli_fetch_arry($run_query)){
$productID = $row["productID"];
$productCat = $row["productCat"];
$productBrand = $row["productBrand"];
$productTitle = $row["productTitle"];
$productPrice = $row["productPrice"];
$productIMG = $row["productIMG"];
echo " <div class='col-md-4'>
<div class='panel panel-info'>
<div class='panel-heading'>$productTitle</div>
<div class='panel-body'>
<img src='assets/$productIMG' style='width: 160px; height: 250px;'/>
</div>
<div class='panel-heading'>$productPrice.00$
<button pid='$productID' style='float: right;' class='btn btn-danger btn-xs'>Add To Cart</button>
</div>
</div>
</div> ";
}
}
?>
This is the jQuery code:
$("body").delegate(".category","click",function (event) {
event.preventDefault();
var cid = $(this).attr("categoryID");
/*Used this alert to see if the
right category number is shown, Here it says undefined*/
alert(cid);
$.ajax({
url: "action.php",
method: "POST",
data: {getSelectedCategory: 1, categoryID: cid},
success: function (data){
$("#getProduct").html(data);
}
})
});
I can't seem to find the problem in my code.
You js code is listening to .category class. And there is no such class in your php code template. That's how your echo should look like to work:
echo " <div class='col-md-4'>
<div class='panel panel-info'>
<div class='panel-heading'>$productTitle</div>
<div class='panel-body'>
<img src='assets/$productIMG' style='width: 160px; height: 250px;'/>
</div>
<div class='panel-heading'>
<a class='category' categoryID = '$productCat'>$productBrand</a>
$productPrice.00$
<button pid='$productID' style='float: right;' class='btn btn-danger btn-xs'>Add To Cart</button>
</div>
</div>
</div> ";
Look - I've added <a class="category" categoryID = '$productCat'>$productBrand </a> to you panel-header.

AJAX - doesn't return value

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.

Categories

Resources