Codeigniter 4: failed to decrypt encrypted post data - javascript

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

Related

i want to get data from sql data in ajax but not working

i am working withphp ajax but it not responding, but once i remove a row it works help.
this is my code search_query.php
if (isset($_POST['user_post'])) {
$post_user = array();
$user_post = $con->prepare("SELECT * from post where poster_id= ?");
$user_post->execute([$id]);
while($row = $user_post->fetch(PDO::FETCH_ASSOC)) {
$post_user[] = '<div id="thread" class="card promoting-card thread mt-2">
<div class="card-body d-flex flex-row">
<img src="http://localhost/lasu/img/user-profile.png" class="rounded-circle mr-3" height="50px" width="50px" alt="avatar">
<div>
<h4 class="card-title font-weight-bold mb-2" style="text-align:left;"> '.strtoupper(user_detail($row['poster_id'], "username")).'</h4>
<p class="card-text"><i class="far fa-clock pr-2"></i>'. time_elapsed_string($row['reg_date'], $full = false).' </p>
<p>'.$row['post_content'].'</p>
</div>
</div>
</div>';
}
echo json_encode($post_user);
}
and this is javascript
$(function(){
var search_data = new FormData();
search_data.append("user_post", 'post');
search_data.append("user_post_id", <?php echo get_users_page_id(); ?>);
$.ajax({
url:"search_query.php",
type: 'POST',
data:search_data,
contentType: false,
processData: false,
dataType: 'json',
success:function(data)
{
if (data.length < 1) {
$('#results').append('<font>No Post</font><br>');
}else{
for (var i = 0; i < data.length; i++) {
$('#results').append(data[i]+'<br>');
}
}
}
})
})
It works if i remove $row['post_content'] in the php code and i tried it in a plain page it worked pls help
Maybe you forgot to get the id?
if (isset($_POST['user_post'])) {
$post_user = array();
$user_post = $con->prepare("SELECT * from post where poster_id= ?");
// here
$id = $_POST['user_post_id'];
$user_post->execute([$id]);
while($row = $user_post->fetch(PDO::FETCH_ASSOC)) {
$contents = highlight_contents($row['post_content']);
$post_user[] = '<div id="thread" class="card promoting-card thread mt-2">
<div class="card-body d-flex flex-row">
<img src="http://localhost/lasu/img/user-profile.png" class="rounded-circle mr-3" height="50px" width="50px" alt="avatar">
<div>
<h4 class="card-title font-weight-bold mb-2" style="text-align:left;"> '.strtoupper(user_detail($row['poster_id'], "username")).'</h4>
<p class="card-text"><i class="far fa-clock pr-2"></i>'. time_elapsed_string($row['reg_date'], $full = false).' </p>
</div>
</div>
</div>';
}
echo json_encode($post_user);
}

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.

Better way to connect from belongsTo to has many relation in laravel

so I have a code that shows all my product
#foreach($products as $product)
<div class="col-lg-4 col-md-4 col-sm-6 col-12 event-item-col ">
<div class="card card-event info-overlay">
<div class="img has-background h-50">
<div class="pop-info ">
<span class="event-badges ">
<span class="badge price-tag big badge-default">{{$product->price}}</span>
</span>
</div>
<a href="/product/{{$product->id}}" class="event-pop-link">
<span class="event-badges ">
<span class="badge badge-danger"> if he buy</span>
</span>
<div class="event-pop-info">
<p class="badge">{{$product->price}}</p>
<p class="publisher">by <strong><?php $id = $product->user_id; $users = $user->findOrFail($id); echo $users->first; ?> <?php echo $user->last ?></strong></p>
</div>
</a>
<a href="event-details.html">
<img alt="340x230" class="card-img-top img-responsive h-100" data-holder-rendered="true" src="image/products/product{{$product->id}}.jpg"> </a>
</div>
<div class="card-body h-50">
<h4 class="card-title">
{{$product->pname}}
</h4>
<p class="card-tex" style="overflow: hidden">{{$product->smalldescription}}</p>
<div class="card-event-info">
<p class="event-location"><i class="fas fa-location-arrow"></i>
<a class="location" href="/user/product/{{$id}}"><?php echo $users->first; ?> <?php echo $user->last ?></a></p>
<p class="event-time"><i class="fas fa-calendar-alt"> {{$product->created_at->format('m/d/Y')}}</i></p>
</div>
</div>
</div>
</div>
#endforeach
and this is my controller
public function index()
{
$user = User::find(1);
$products = product::orderBy('created_at', 'desc')->Paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null);
return view('welcome', compact('products', 'user'));
}
like you can see in my view I have this code
<?php $id = $product->user_id; $users = $user->findOrFail($id); echo $users->first; ?> <?php echo $user->last ?>
that makes me able to get the name of the user that create this product, product and user table has one too many relations.i want to change this code to a better and smaller code.
product->user->first
don't work.
I tried it so many ways but that just doesn't work.
if anyone can help me to get data with laravel way I will be grateful. (sry if my question is duplicate, I tried so many ways but didn't work )
to give u guys more info this is my class
class User extends Authenticatable
{
use Notifiable;
use Friendable;
protected $fillable = [
'first','last', 'email', 'password','phone','question','answer','description',
];
protected $hidden = [
'password', 'remember_token',
];
public function products()
{
return $this->hasMany(Product::class);
}
}
and product class :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
the class product extends Model
{
protected $fillable = [
'part_id', 'smalldescription', 'description', 'pname', 'link', 'price',
];
public function users()
{
return $this->belongsTo(User::class);
}
}
Firstly I would like to point you out that you have already defined the relation in your product model you could use that to access the related user by calling the function. I would also like to suggest you to change the function name in your product model from users to user as belongsTo returns only single instance of the related model.
public function user()
{
return $this->belongsTo(User::class);
}
Coming back to your query when querying products use with load a relation like in your case it would be.
product::with('user')->orderBy('created_at', 'desc')->Paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null);
Then inside your foreach loop on blade get user's name calling user function on $product like:
$product->user->name
I would also suggest to go through the laravel documentation about eloquent relations again.
Querying a relation

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.

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