Download a file on page load in Jquery - javascript

I have a file in my server folder and now I want to download that file on page load.
Example :
If I click on Our products than a file has been downloaded automatically in users system from my server.

// in controller
public function download() {
$this->viewClass = 'Media';
// Render app/webroot/files/example.docx
$params = array(
'id' => 'example.docx', // file name
'name' => 'example',
'extension' => 'docx', // its file extension name
'mimeType' => array(
'docx' => 'application/vnd.openxmlformats-officedocument' .
'.wordprocessingml.document'
),
'path' => 'files' . DS
);
$this->set($params);
}
//In view file
echo $this->Html->url(array(
"controller" => "controller_name",
"action" => "action_name",
"ext" => "file_extension_name"
));
Also read Cakephp Media View

This is my ans :
$(document).ready(function(){
if('<?php echo $filename ?>' !=''){
window.location.href ='/files/<?php echo $filename ?>.xls';
}
});
</script>

Related

How to get url with javascript and pass it to php as a variable

I have code to get some data (terms = page-a) built with Wordpress.
Currently, the data of page-a is acquired like'terms' =>'page-a' and displayed on the example.com/page-a page.
I would like to change this data acquisition code so that the data along the lower page url can be acquired (for example, the data on page-b at example.com/page-b).
I created a code to get the url with $_SERVER and convert it, but I can't get the url because I am using ajax. I want to get the url with javascript and pass it to php.
How should I make the changes?
functions.php
add_action('wp_ajax_get_case', 'dk_get_case');
add_action('wp_ajax_nopriv_get_case', 'dk_get_case');
function dk_get_case() {
$headers['Access-Control-Allow-Origin'] = '*';
$return = ['status' => false, 'data' => [], 'message' => ''];
$case_clinics = [1,2,3,4];
foreach($case_clinics as $key => $case_clinic){
// (1)Get the current URL
$http = is_ssl() ? 'https' : 'http' . '://';
$url = $http . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
// (2)Get a string such as'page-a' from the URL
$keys = parse_url($url);
$path = explode("/", $keys['path']);
$terms = $path[2];
$dk_posts = get_posts(
array(
'showposts' => -1,
'post_type' => 'case',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'case_clinic',
'field' => 'term_id',
'terms' => $case_clinic
),
array(
'taxonomy' => 'case_category',
'field' => 'slug',
'terms' => 'page-a'
)
)
)
);
taxonomy-case_category-page-a.php
<div class="col case-right">
<h3 style="font-family:'Futura PT'; font-weight:600">Clinic</h3>
<h4 style="font-weight:600">Clinic</h4>
                                            //data display position
<div class="case-img" data-slider-3></div>
<div class="popup"></div>
</div>
Tried
footer.php
<script>
jQuery(document).ready(function () {
var url = window.location.href;
$.ajax({
type: "GET",
url: "taxonomy-case_category-page-a.php",
data: {"url": url},
});
});
taxonomy-case_category-page-a.php
<?php var_dump($_GET['url']); ?>
error
GET: 404error
https://example.com/pagea/taxonomy-case_category-page-a.php?url=https%3A%2F%2Fcharme-beauty.jp%2Fstaging%2Fcase%2Fpagea%2F

Create post and upload image with Ajax (axios) in Wordpress

So I want my users to be able to create a post in the frontend and upload an image with a form I've created.
When the image is uploaded I want to update an ACF-field with the uploaded image.
I've seen some posts on this but none of them are explained any good.
I want to use Ajax and I want to use axios, so please no jQuery. I also use Qs.
The image itself is never uploaded but the file name is inserted in the media library.
Thank you!
HTML
<form enctype="multipart/form-data" method="post" id="register-store-form">
<fieldset class="store-images mb-3">
<label for="store-images">Add images</label>
<input type="file" id="store_images" name="store_images" accept="image/png, image/jpeg">
</fieldset>
<button class="btn btn-primary" id="update-store">Save store</button>
</form>
JS
const Qs = require('qs');
const axios = require('axios');
const saveStoreBtn = document.querySelector('#update-store');
const addStore = document.querySelector('#add-one-more-store');
function saveStore(e) {
const storeName = document.querySelector('#store-name');
const storeImages = document.querySelector('#store_images');
const storeImageFile = storeImages.files[0];
const ajaxData = {
action : 'create_store',
security : shkGlobal.addStore,
name : storeName.value,
image_name : storeImageFile.name,
image_type : storeImageFile.type,
description : storeDescription.value
};
axios.post(shkGlobal.adminUrl, Qs.stringify(ajaxData))
.then(function(response) {
saveStoreBtn.innerHTML = "Thank you";
})
.catch(err => console.log('Not working', err));
};
updateStoreBtn.addEventListener('click', saveStore);
PHP
function create_store() {
check_ajax_referer('add_store', 'security');
$name_value = $_POST['name'];
$image_name = $_POST['image_name'];
$image_type = $_POST['image_type'];
$post_data = array(
'post_type' => 'store',
'post_title' => htmlentities($name_value),
'post_content' => $_POST['description'],
'post_status' => 'draft'
);
$post_id = wp_insert_post( $post_data );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES[$image_name];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ($movefile) {
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'].'/'.$image_name,
'post_mime_type' => $image_type,
'post_title' => $image_name,
'post_content' => 'File '.$image_name,
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $movefile['file']);
update_field('field_602019eba7767', $attach_id, $post_id);
}
echo json_decode($response);
exit;
}
add_action('wp_ajax_create_store', 'create_store');
add_action('wp_ajax_nopriv_create_store', 'create_store');
There are two problems in your case, first one that you are uploading multiple files, so structure of $_FILES will be different. Second one is that you specified store_images instead store_images[] for multiple file upload.
So in html change <input type="file" name="store_images" multiple> to <input type="file" name="store_images[]" multiple>
And in php, change your code accordingly to example below.
$files = $_FILES['store_images];
foreach ($files as $key => $value) {
if ($files['name']) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
wp_handle_upload($file);
}
}
}

Autocomplete data fields in CakePHP

I am new in CakePHP. I have a CakePHP (2.5.1) application which has streets table (with columns id, street_name, house_no, district, city). I need to autocomplete a form by extracting the table data. It should be like, the user will be typing a street name in the Street Name field of a form which has fields- Street Name, House No, District and City. After selecting a street name from auto suggestions, corresponding data (House No, District and City) will be populated in the other fields.
Now, over 25000 data rows are loaded in the streets table which is the entire street database of a city. it is a ClearDB database on Windows Azure. streets table is not linked with other tables of the application through foreign keys. I have Street model, StreetsController , but view is in different folder (app/View/User/add.ctp ). Street model in app/Model/Street.php is following:
class Street extends AppModel {
public function getStreetNames($term = null) {
if(!empty($term)) {
$streets = $this->find('list', array(
'conditions' => array(
'street_name LIKE' => trim($term) . '%'
)
));
return $streets;
}
return false;
}
}
In app/Controller/StreetsController.php,
class StreetsController extends AppController {
public $components = array('RequestHandler');
public function autocomplete($term){
if ($this->request->is('get')) {
$this->autoRender = false;
$data = $this->Street->getStreetNames($term);
$this->set(compact('data'));
$this->set('_serialize', array('data'));
echo json_encode($data);
}
}
}
In app/webroot/js/View/Users/streetdata.js file,
(function($) {
$('#autocomplete').autocomplete({
source: "/streetdata.json",
minLength: 1
});
})(jQuery);
The input forms are in different controller. In app/View/Users/streetdata.ctp file,
<?php
echo $this->Html->script('View/Users/streetdata', array('inline' => false));
?>
<?php echo $this->Form->create('Street', array(
'class' => 'form-horizontal',
'role' => 'form',
'inputDefaults' => array(
'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
'div' => array('class' => 'form-group'),
'class' => array('form-control'),
'label' => array('class' => 'col-lg-2 control-label'),
'between' => '<div class="col-lg-3">',
'style'=>array('width:200px; height:35px;'),
'after' => '</div>',
'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
))); ?>
<fieldset>
<legend><?php echo __('Street data '); ?></legend>
<?php
echo $this->Form->input('Street.street_name', array(
'class' => 'ui-autocomplete',
'id' => 'autocomplete'));
echo $this->Form->input('Street.house_no');
echo $this->Form->input('Street.district');
echo $this->Form->input('Street.city');
?>
</fieldset>
<?php echo $this->Form->end(__('Proceed')); ?>
in View/Layouts/default.ctp, i have added followings
echo $this->Html->script('jquery.js');
echo $this->Html->script('bootstrap.min');
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('inline' => false));
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', array('inline' => false));
echo $this->Html->css('https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css');
echo $this->Html->css('font-awesome.min');
echo $this->Html->css('bootstrap.min');
echo $this->Html->meta('icon');
echo $this->fetch('meta');
echo $this->fetch('css');
echo $this->fetch('script');
echo $this->Html->charset();
But the autocomplete fields (street name and others) are not working.
I found following error messages in the console of chrome browser :
-Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:26949/Users/js/jquery.js
-Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:26949/Users/js/bootstrap.min.js
-Uncaught TypeError: Cannot read property 'offsetWidth' of undefined bootstrap.min.js:6
I am struggling to find a solution. Could anyone tell me please what is wrong here ? is it because of the location of .js file ? am i missing anything here?

Save path image with Ajax in Laravel

I can save all data varchar/text element from my form, but I can't save my path image.
Whats is wrong with my code?
Lets see my create.blade.php I can save value of var deadline but I can't save value of var path:
Form::open(array('url' => 'imagesLoker', 'files' => true))
<form class="form-horizontal">
<div class="box-body">
<div class="form-group">
{!!Form::label('Deadline Lowongan : ')!!}
{!!Form::date('deadline',null,['id'=>'deadline','class'=>'form-control','placeholder'=>'Deadline Lowongan'])!!}
</div>
<div class="form-group">
{!!Form::label('Image Lowongan : ')!!}
{!!Form::file('path') !!}
</div>
</div><!-- /.box-body -->
</form>
{!!Form::close()!!}
This is my Controller:
public function store(Request $request)
{
Lowongan::create($request->all());
return "data all";
}
This is my Ajax to create the data:
$("#createLoker").click(function(){
var datas = $('form').serializeArray();
var route = "http://localhost:8000/lowongan";
var token = $("#token").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post(route,{
deadline: $("#deadline").val(),
path: $("#path").val()
}).done(function(result){
console.log(result);
});
});
I don't know this is important or no to setting parse data in my Modal, but I just put this code in my Modal:
class Lowongan extends Model
{
protected $table = 'Lowongan';
protected $fillable = ['path','deadline'];
public function setPathAttribute($path){
$this->attributes['path'] = Carbon::now()->second.$path->getClientOriginalName();
$name = Carbon::now()->second.$path->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($path));
}
}
And the last I set the directory to save the image. This is setting in the config/filesystem:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('imagesLoker'),
],
I can save the data deadline but no for image :( .. If there is any idea for how to save the image path, I will be pleased to know it.
In your form you have to allow file upload option in laravel like.
Form::open(array('url' => 'foo/bar', 'files' => true))
check the file upload section of laravel doc
Hope it helps..
please follow these steps
in view
change {!!Form::file('path') !!} to {!!Form::file('file') !!}
In controller
please note i have set the upload path to root/public/uploads/ folder
public function store(Request $request)
{
$file = Input::file('file');
$path = '/uploads/';
$newFileName = Carbon::now()->second.$file->getClientOriginalName(). '.' . $file->getClientOriginalExtension();
// Move the uploaded file
$upSuccess = $file->move(public_path() . $path, $newFileName);
$result = file_exists(public_path() . $path . $newFileName);
$fileData =[
'fileType' => $file->getClientOriginalExtension(),
'filePath' => substr($path, 1) . $newFileName
];
Input::merge(array('path' => $fileData["filePath"]));
Lowongan::create($request->all());
return "data all";
}

CGridView AjaxRequests brokes javascript custom CFormatter

I'm having problems with CGridView and one custom Formatter that uses javascript. When CGridView triggers an ajax request of any kind, my Formatter that works with javascript stops working.
Let's try one trivial example:
The Formatter
class DFormatter extends CFormatter {
public function formatTest(){
$js = <<<EOD
console.log("test");
EOD;
$cs = Yii::app()->getClientScript();
$cs->registerScript("testjs", $js);
return false;
}
}
The view:
<?php $this->widget('zii.widgets.grid.CGridView',
array(
'id' => 'development-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
array(
'name' => 'testField',
'type' => 'test',
),
array(
'class' => 'CButtonColumn',
),
),
)); ?>
After the first Ajax Request, the javascript code used in the formatter stops working, How can I get my javascript code works after every ajax call made by CGridView Widget?
Thanks.
You should not put scripts in the formatter.
Remove:
$js = <<<EOD
console.log("test");
EOD;
$cs = Yii::app()->getClientScript();
$cs->registerScript("testjs", $js);
Configure your grid view:
<?php $this->widget('zii.widgets.grid.CGridView', array(
//.. other options
// ADD THIS
'afterAjaxUpdate' => 'function() { afterAjaxUpdate(); }',
Add to <head> of /layouts/main.php:
<script src="<?= Yii::app()->getBaseUrl(true); ?>/js/myCustomJS.js"></script>
Create new JS file at /js/myCustomJS.js:
function afterAjaxUpdate() {
// do your formatting here
}

Categories