Codeigniter 4 dropzone upload after redirect url - codeigniter

I am uploading files with Codeigniter 4. I want the page to refresh after loading but my code is not working. Here is the controller I use.
At the bottom I have the code for the redirect but this code is not working.
<?php namespace App\Controllers;
use App\Models\Hizmetmodels;
use App\Models\Dosyamodels;
class Dosyacontroller extends BaseController
{
protected $helpers = ['form' ,'url'];
protected $Dosyamodels;
public function index($sap = null)
{
$Hizmetmodels= new Hizmetmodels();
$data['hizmetsat'] = $Hizmetmodels->where('sap', $sap)->first();
$Dosyamodels= new Dosyamodels();
$where = "sap='$sap'";
$data['dosya'] = $Dosyamodels->orderBy('id', 'ASC')->where($where)->findAll();
return view('Admin/Dosyalar/index', $data);
}
public function form()
{
$sap = $this->request->getPost('sap');
$Dosyamodels= new Dosyamodels();
helper(['text','inflector']);
$file = $this->request->getFile('file');
$size = $file->getSize();
$kilobytes = $file->getSizeByUnit('kb');
$path = 'public/uploads';
$name = convert_accented_characters(underscore($file->getName()));
$newname = "$sap-$name";
$file->move(ROOTPATH . $path, $newname);
$ext = $file->getClientExtension();
$data = [
'adi' => $newname,
'yol' => $path . '/' . $name,
'sap' => $sap,
'boyut' => $kilobytes,
'uzt' => $ext,
];
$save = $Dosyamodels->insert($data);
return redirect()->to('/Dosyalar/index/'. $sap)->with('success', 'Tebrikler! <br> Dosyalar başarı ile yüklendi.');
}
}

The issue could be with the redirect URL that you are trying to redirect to. In this case, the URL is /Dosyalar/index/'. $sap which is missing the base URL. To resolve the issue, you can use the base URL in the redirect URL, like this:
return redirect()->to(base_url('Dosyalar/index/'. $sap))->with('success', 'Tebrikler! <br> Dosyalar başarı ile yüklendi.');

Try to change
this.on('queuecomplete', function (file) { location.reload(); }); to this.on('success', function (file, responseText) { location.reload(); });

With dropzone the document is uploaded to the correct folder. saved to the database. no problems so far. the only problem is i can't refresh the page no matter what i do after it loads.here is my java script code:
$(function() {
Dropzone.options.dropzoneform = {
paramName: 'file',
maxFilesize: 2, // MB
maxFiles: 5,
init: function () {
this.on('queuecomplete', function (file) {
location.reload();
});
}
}
});

Related

How to flash validation errors to session in Laravel

The built in behavior for flashing back validation errors in Laravel does not seem to be working for my use case.
I have a (React) form that posts it's data via fetch API using this method, which reloads or redirects the page with (hopefully) any session data after the response is returned:
fetch(props.register_route, {
method: 'POST',
headers: {
'X-CSRF-Token': props.csrf,
},
body: data,
})
.then((result) => {
return result.json();
})
.then((result) => {
console.log(result);
window.location.href = result.url;
},
(error) => {
console.log(error);
});
In my controller, I validate this data but if I structure it as follows, the errors are not available as $errors in the resulting page
if ($validator->fails()) {
return redirect()->back()->withErrors($validator);
}
However if I manually flash the errors to the session and return a url instead of a redirect, suddenly the behavior works.
if ($validator->fails()) {
Session::flash('errors', $validator->errors());
return response->json([
'url' => route('register'),
], Response::HTTP_NOT_ACCEPTABLE);
}
I feel as if I must be doing something incorrectly here to have to use this workaround. I could also manually send the errors back in the response, which may be the right way to structure things in the long run.
when you are calling api from javascript or front end applications like Reactjs,Angular,android etc.. .So it expect return result should be in json format so it should be like
if ($validator->fails()) {
return response()->json( $validator->errors(),422);
}
if you not calling Method from direct laravel blade then pass response in JOSN Format.
like
https://laravel.com/docs/8.x/responses#json-responses
Or
make one ResponseManager File
<?PHP
namespace App\Libraries\utils;
class ResponseManager {
public static $response = array('flag' => true, 'data' => '', 'message' => '', 'code' => 01,);
public static function getError($data = '', $code = 10, $message = '', $flag = false) {
self::$response['flag'] = $flag;
self::$response['code'] = $code;
self::$response['data'] = $data;
self::$response['message'] = $message;
return self::$response;
}
public static function getResult($data = '', $code = 10, $message = '', $flag = true) {
self::$response['flag'] = $flag;
self::$response['code'] = $code;
self::$response['data'] = $data;
self::$response['message'] = $message;
return self::$response;
}}
Define in config/app.php
//custom class
'ResponseManager' => App\Libraries\utils\ResponseManager::class,
and then use in whole project
Error Message Like
if ($validation->fails()) {
$message = $validation->messages()->first();
return Response()->json(ResponseManager::getError('', 1, $message));
}
Success Message Like
return Response()->json(ResponseManager::getResult(null, 10, "Success"));

Adding Parameters in Routing URL Codeigniter

I have some problem with routing and parameters.
I have routing in routes.php like this :
$route['register/(:any)'] = 'member/register/$1';
And in my controller I have like this :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Register extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Page_model');
$this->load->model('member_model');
$this->load->model('login_model');
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('html');
$this->load->helper('form');
}
public function index()
{
$slug = $this->uri->segment(1);
$type = $this->uri->segment(2);
var_dump($type);
exit();
if ($slug != NULL)
{
$data['page'] = $this->Page_model->get_page($slug);
if (empty($data['page']))
{
// show_404();
$data['page'] = new stdClass();
$data['page']->page_template = 'forofor';
$data['page']->title = 'Page Not Found';
$data['page']->meta_description = 'Page Not Found';
$data['page']->meta_keywords = 'Page Not Found';
}
else
{
$data['slider'] = $this->Page_model->get_slider($data['page']->page_id);
}
}
else
{
$data['page'] = $this->Page_model->get_page('home');
$data['slider'] = $this->Page_model->get_slider($data['page']->page_id);
}
$data['head_title'] = $data['page']->title;
// load all settings and data
$data['settings'] = $this->Page_model->get_settings();
$data['gallery'] = $this->Page_model->get_gallery();
$data['meta'] =
array(
array(
'name' => 'description',
'content' => $data['page']->meta_description
),
array(
'name' => 'keywords',
'content' => $data['page']->meta_keywords
)
);
// $data['meta'] = $this->meta;
$data['menu'] = $this->Page_model->get_menu('frontend','header');
$data['settings'] = $this->Page_model->get_settings();
$data['notice'] = $this->session->flashdata('notice');
// $this->load->view('frontend/template/index_full', $data);
$this->load->view('frontend/template/head', $data);
$this->load->view('frontend/template/pre_header');
$this->load->view('frontend/template/header');
$this->load->view('frontend/template/modal');
//$this->load->view('frontend/template/modal_registration');
/*if ($page[0]->page_template != 'forofor' && $data['page']->slider != 0)
{
$this->load->view('frontend/template/slider');
}*/
if ($slug != 'home' && $slug != NULL)
{
//$this->load->view('member/'.$data['page']->page_template);
$this->load->view('member/register');
}
else
{
$this->load->view('frontend/template/slider');
$this->load->view('frontend/page_template/homepage');
}
$this->load->view('frontend/template/pre_footer');
$this->load->view('frontend/template/footer');
$this->load->view('frontend/template/js');
$this->load->view('frontend/template/closing_body_html');
}
}
But if I input the routes in my browser it gives me 404 Page not found
This is my routes :
127.0.0.1/project/register/buyer
And 127.0.0.1/project/ is my Base URL
Anyone knows why it could be happen ?
Thank you.
Your routing is wrong. According to your post you are setting Member controller then register method.
Try below code
$route['register/(:any)'] = 'register/index/$1';
$route['register/(:any)/(:any)'] = 'register/index/$1/$2'; // Optional
The second option is only optional:
This is how routes work in Codeigniter
Typically there is a one-to-one relationship between a URL string and
its corresponding controller class/method. The segments in a URI
normally follow this pattern:
example.com/class/function/id/ In some instances, however, you may
want to remap this relationship so that a different class/method can
be called instead of the one corresponding to the URL.
For example, let’s say you want your URLs to have this prototype:
example.com/product/1/ example.com/product/2/ example.com/product/3/
example.com/product/4/ Normally the second segment of the URL is
reserved for the method name, but in the example above it instead has
a product ID. To overcome this, CodeIgniter allows you to remap the
URI handler.
Reference : https://www.codeigniter.com/userguide3/general/routing.html
So,the routes follow this syntax
$route['route_url'] = 'controller/method/$paramater';
So,your route will be
Let me know your queries
$route['register/(:any)'] = 'register/index/$1';

Phalcon: HMVC view not working

I got a problem rendering nested view, here is what I'm trying to do
I changed your 'request' of HMVC (HMVC-GitHub or/and HMVC-Pattern) function into an Elements module
namespace Modules\Main\Libraries;
/**
* Elements
*
* Helps to build UI elements for the application
*/
class Elements extends \Phalcon\Mvc\User\Component
{
public function loadModule($path = '', $data = array()) {
$di = clone $this->getDI();
$dispatcher = $di->get('dispatcher');
$paths = explode('/', $path);
$data = is_array($data) ? $data : array($data);
// get controller name
if (isset($paths[0])) {
$controller = $paths[0];
}
// get action name
if (isset($paths[1])) {
$action = $paths[1];
}
// get params
if (isset($paths[2])) {
array_splice($paths, 0, 2);
$params = array_merge($paths, $data);
} else {
$params = $data;
}
if (!empty($controller)) {
$dispatcher->setControllerName($controller);
} else {
$dispatcher->setControllerName('index');
}
if (!empty($action)) {
$dispatcher->setActionName($action);
} else {
$dispatcher->setActionName('index');
}
if (!empty($params)) {
if(is_array($params)) {
$dispatcher->setParams($params);
} else {
$dispatcher->setParams((array) $params);
}
} else {
$dispatcher->setParams(array());
}
$dispatcher->dispatch();
$response = $dispatcher->getReturnedValue();
if ($response instanceof ResponseInterface) {
return $response->getContent();
}
return $response;
}
}
and I have 2 controllers:
namespace Modules\Main\Controllers;
class IndexController extends ControllerBase
{
public function indexAction()
{
$secondContent = $this->elements->loadModule('test/hello/json');
$this->view->setVar('secondContent', $secondContent);
}
}
and
namespace Modules\Main\Controllers;
use \Phalcon\Http\Response;
class TestController extends ControllerBase
{
public function indexAction()
{
}
public function helloAction($format='html', $param = 'empty')
{
$this->view->setVar('content', 'Hello this is test value "'.$param.'"');
$content = $this->view->getContent();
return (string)$content;
// return 'Hello this is test value "'.$param.'"';
}
}
my DI
$di['elements'] = function() {
return new \Modules\Main\Libraries\Elements();
};
Views files
IndexController::Index
<h1>Congratulations!</h1>
<p>You're now flying with Phalcon. Great things are about to happen!</p>
<p>Second content: {{ secondContent}}</p>
<p>HMVC: {{ elements.loadModule('test/hello/json', 'test') }}</p>
and HelloController::test
This is :: {{ content }}
expecting to get
Congratulations!
You're now flying with Phalcon. Great things are about to happen!
Second content: This is :: Hello this is test value "empty"
HMVC: This is :: Hello this is test value "test"
but it only rendering the HelloController (First call from IndexController::indexAction):
This is :: Hello this is test value "empty"
if I change IndexController::indexAction to
public function indexAction()
{
$secondContent = '';
$this->view->setVar('secondContent', $secondContent);
}
and TestController::helloAction to
public function helloAction($format='html', $param = 'empty')
{
$this->view->setVar('content', 'Hello this is test value "'.$param.'"');
$content = $this->view->getContent();
//return (string) $content;
return 'Hello this is test value "'.$param.'"';
}
the result that i get is (Second content is empty):
Congratulations!
You're now flying with Phalcon. Great things are about to happen!
Second content:
HMVC: Hello this is test value "test"
Any solution to solve this ?
Thanks,
Helman
Phalcon have built-it modules feature, you dont have to built your own module loader, you just need create module bootstrap that extend ModuleDefinitionInterface.
Just take a look this sample from phalcon multi module
https://github.com/phalcon/mvc/tree/master/multiple
this example below is taken from link above, This contain module bootstrap code.
<?php
namespace Multiple\Frontend;
class Module
{
public function registerAutoloaders()
{
$loader = new \Phalcon\Loader();
$loader->registerNamespaces(array(
'Multiple\Frontend\Controllers' => '../apps/frontend/controllers/',
'Multiple\Frontend\Models' => '../apps/frontend/models/',
));
$loader->register();
}
/**
* Register the services here to make them general or register in the ModuleDefinition to make them module-specific
*/
public function registerServices($di)
{
//Registering a dispatcher
$di->set('dispatcher', function () {
$dispatcher = new \Phalcon\Mvc\Dispatcher();
//Attach a event listener to the dispatcher
$eventManager = new \Phalcon\Events\Manager();
$eventManager->attach('dispatch', new \Acl('frontend'));
$dispatcher->setEventsManager($eventManager);
$dispatcher->setDefaultNamespace("Multiple\Frontend\Controllers\\");
return $dispatcher;
});
//Registering the view component
$di->set('view', function () {
$view = new \Phalcon\Mvc\View();
$view->setViewsDir('../apps/frontend/views/');
return $view;
});
$di->set('db', function () {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
});
}
}
you can load module using this code below
$app = new \Phalcon\Mvc\Application();
$app->registerModules(array(
'frontend' => array(
'className' => 'Multiple\Frontend\Module',
'path' => '../apps/frontend/Module.php'
),
'backend' => array(
'className' => 'Multiple\Backend\Module',
'path' => '../apps/backend/Module.php'
)
));

Unable to edit recode in cake php when I load the value in select box using j-query

I am unable to load select box value when I want to update the value. The same code perfectly working when I am going to save value.
My controller code is:
public function listwardByCircle($category = "") {
$this->layout = 'ajax';
$this->beforeRender();
$this->autoRender = false;
$ward=$this->Ward->find('list',array(
"fields" => 'id, wardname',
"conditions" => array('Ward.circle_id' => $category)
));
//$this->set('ward',$ward);
print_r($ward);
foreach($ward as $key => $val) {
echo "<option value=$key>$val</option>";
}
}
And this is my js code :
$("#AreaCircleId").change(function() {
alert("testing....");
$.post('../Admins/listwardByCircle/' + $(this).val(), function(data) {
alert( data);
$("#AreaWardId").empty().append(data);
}, 'html');
});
In js file
Url in Controller Like
`\../../Admins\/listwardByCircle`
You may need to update your URL post location in the ajax from:
$.post('../Admins/listwardByCircle/'
to
$.post('/admins/listwardByCircle/'
This is if the controller name is admins.

Unable to get_the_content(); of a post in Wordpress via AJAX

I'm trying to ajaxify my Wordpress theme and I use the ajax-in-WordPress method and I'm now trying get_the_content of post via functions.php. Using jQuery, when I do alert(data) I get the 'title' echo but not the content of the existing post I want (returns 0).
What am I doing wrong?
The jQuery part
$('.ajaxed,.ajaxed a,.menu-item-home a,.menu-item-object-page a').live('click', function(event) {
event.preventDefault();
var link = $(this).attr('href');
var toRemove = MySettings.url;
var rewritepath = link.replace(toRemove,'');
var handler = function(data) {
$('title').html($('title', data).html());
$('#primary').html($('#primary', data).html());
$('#primary').hide().fadeIn('slow');
$.address.title(/>([^<]*)<\/title/.exec(data)[1]);
};
$.post(ajax_object.ajaxurl, {
action: 'ajax_action',
post_id: $(this).find('input.post_id').attr('value')
},function(data) {
alert(data.post_title);
alert(data.post_content);
});
/*$.ajax({
url: link,
error: function(XMLHttpRequest, textStatus, errorThrown) {
handler(XMLHttpRequest.responseText);
},
success: function(data, textStatus, XMLHttpRequest) {
handler(data, function(){
});
}
});*/
$.address.state(MySettings.path).crawlable(true).value(rewritepath);
return false;
});
The functions.php part
<?php
function javascripts() {
if( !is_admin()){
$blogurl = get_bloginfo('url');
$thumbnail_width = get_option('thumbnail_size_w');
$thumbnail_height = get_option('thumbnail_size_h');
$path = parse_url(get_bloginfo('siteurl'), PHP_URL_PATH);
$url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js';
wp_deregister_script('jquery');
if (get_transient('google_jquery') == true) {
wp_register_script('jquery', $url, array(), null, true);
}
else {
$resp = wp_remote_head($url);
if (!is_wp_error($resp) && 200 == $resp['response']['code']) {
set_transient('google_jquery', true, 60 * 5);
wp_register_script('jquery', $url, array(), null, true);
}
else {
set_transient('google_jquery', false, 60 * 5);
$url = get_bloginfo('wpurl') . '/wp-includes/js/jquery/jquery.js';
wp_register_script('jquery', $url, array(), '1.7', true);
}
}
wp_enqueue_script('plugins.js', get_bloginfo('template_directory') . "/js/plugins.js" , array('jquery'));
wp_enqueue_script('ajax-script', get_bloginfo('template_directory') . "/js/scripts.js", array('jquery'));
wp_localize_script('ajax-script', 'ajax_object', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_localize_script('jquery', 'MySettings', array('width' => $thumbnail_width,'height' => $thumbnail_height,'url' => $blogurl,'path' => $path));
}
}
add_action('wp_enqueue_scripts', 'javascripts');
add_action('wp_ajax_ajax_action', 'ajax_action_stuff'); // ajax for logged in users
add_action('wp_ajax_nopriv_ajax_action', 'ajax_action_stuff'); // ajax for not logged in users
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
echo json_encode($post_data);
}
?>
What am I doing wrong? Thanks
Without seeing the entire scope of your code, it appears that you might be calling get_the_content() outside of the context of The Loop. If so, the function doesn't understand which post you'd like to retrieve the content for. Try organizing the function this way:
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
$title = $post_data->post_title;
$content = $post_data->post_content;
echo $title;
echo $content;
}
Here we've used get_post() to return an object with all of the post data.
The jQuery function you've created...
function(data) {
alert(data);
});
... should essentially contain a string in the data object that contains your title and content.
Here's a recommendation though, on how you can return your data in a more organized fashion, if you like.
The 'data' object (which is what you've echoed in the php function ajax_action_stuff()) is just a string value. The problem though is that the data isn't really structured in a way for jQuery to fully understand and use to its full potential. If you change your php function to return a JSON object though, then you can use all your properties in jQuery individually. I'll show you how...
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
echo json_encode($post_data);
}
Then in the jQuery function you have access to each property like this:
$.post(ajax_object.ajaxurl, {
action: 'ajax_action',
post_id: $(this).find('input.post_id').attr('value')
},function(data) {
alert(data.post_title);
alert(data.post_content);
});
Have a look at the get_post() function to see all of the properties that you have available to you.
You aren't telling get_the_content() which post to retrieve the content for. Internally, this function checks for the global $post object and filters the content of that object.
So change your ajax function to something like this:
function ajax_action_stuff() {
global $post;
$post_id = $_POST[ 'post_id' ];
update_post_meta( $post_id, 'post_key', 'meta_value' );
$post = get_post( $post_id );
$title = 'title';
$content = get_the_content();
echo $title;
echo $content;
}
This will use the ID you've passed in to query the database for a specific post and populate the global $post object. Now, get_the_content() and even get_the_title() should function normally.

Resources