How i find out installation path on Cakephp 3 - ajax

I have a Cakephp installation on a local wamp in:
c:\wwww\appname
and I have a countdown script in a view:
<script type="text/javascript">
$(document).ready(function()
{
var austDay = new Date();
austDay = new Date(<?= $nextclaimtime * 1000;?>);
$("#countdown").countdown({until: austDay, format: 'HMS', expiryUrl: "/users/add"});
});
</script>
If i specify /users/add in the expiryUrl everything works in live enviroment but in my local environment it doesn't work because the app is installed under appname.
What is the correct way to change the code so the Ajax call works in both encironments?

The correct way would be to use the router to generate the URL, which would create a URL with respect to the base path/URL.
<?php $url = \Cake\Routing\Router::url(['controller' => 'Users', 'action' => 'add']); ?>
var expiryUrl = <?= json_encode($url) ?>;
$("#countdown").countdown({until: austDay, format: 'HMS', expiryUrl: expiryUrl});
See also
Cookbook > Routing > Generating URLS

Related

Frontend custom post submission results in wp_insert_post() undefined

I've been struggling for a few days with this issue and I really hope you can help me out.
I've created a plugin, which is located in:
'/wp-content/plugins/my-cool-plugin'.
My plugin allows users to post a custom post type via a form on a public page, basically anyone should be able to post something.
Using jQuery, I listen to when my frontend form is submitted and using Ajax I pass the data from the form to a php file to process it into a post.
This file is located at:
'/wp-content/plugins/my-cool-plugin/inc/processor.php'.
Below is the content of my processor file:
$var1= $_POST['some'];
$var2= $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish',
'mcp_1' => $var1,
'mcp_2' => $var2
);
$post_id = wp_insert_post( $new_post, $wp_error );
if ($wp_error == 'false'){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
When I test my form, it results in the following error:
Call to undefined function wp_insert_post() on line ... which is the following line:
$post_id = wp_insert_post( $new_post, $wp_error );
Do I need to include something since I'm not in the WordPress 'scope' anymore?
Or is there another (much better) way for inserting custom posts from a front end form?
Why are you running the file out of wordpress scope? That is not the best practive. Instead you could run it in wordpress scope and user wordpress native ajax.
add_action('wp_ajax_yourplugin_create_post', 'yourplugin_create_post');
add_action('wp_ajax_nopriv_yourplugin_create_post', 'yourplugin_create_post');
function yourplugin_create_post() {
// your code here
}
Then you would need your ajax url to be passed from php to js:
function your_plugin_ajaxurl() {
?>
<script type="text/javascript">
var yourPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php
}
add_action('wp_head','your_plugin_ajaxurl');
Then you can use your ajax request but you would need to indicate action:yourplugin_create_post and url = yourPluginAjaxUrl
Try adding
require(dirname(__FILE__) . '/wp-load.php');
It took me some time to process Nick's answer, but I finally got it to work! Like Nick said, I dropped using the process file because is was out of the scope of WordPress. I moved my post creation from my proces file to a new function in the plugin init file (my-cool-plugin.php), as Nick suggested. This resulted in the following new function:
add_action('wp_ajax_coolplugin_create_post', 'coolplugin_create_post');
add_action('wp_ajax_nopriv_coolplugin_create_post', 'coolplugin_create_post');
function coolplugin_create_post() {
$var1 = $_POST['some'];
$var2 = $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish'
'post_title' => 'Some title'
);
$post_id = wp_insert_post( $new_post, $wp_error );
// check if there is a post id and use it to add custom meta
if ($post_id) {
update_post_meta($post_id, 'mcp_1', $var1);
update_post_meta($post_id, 'mcp_2', $var2);
}
if ($wp_error == false){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
}
I also had to change the way I inserted my custom values into the newly created post, because the wp_insert_post() function only accepts default post parameters (see the wp_insert_post documentation for these parameters).
Next to my insert/create post function I also had to make some adjustments to my javascript file, which retrieves the filled in data from my form. Therefore (as Nick suggested) I needed to pass my Ajax URL from PHP to JS by adding the following function to my-cool-plugin.php like this:
function your_plugin_ajaxurl() { ?>
<script type="text/javascript">
var coolPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php }
add_action('wp_head','your_plugin_ajaxurl');
By adding the coolPluginAjaxUrl variable to the head I'm able to use the URL in my javascript to post the data to when my form is submitted, like this:
$( '#form' ).on( 'submit', function(e) {
var request;
e.preventDefault();
var val_one = $( '#val-one' ).val();
var val_two = $( '#val-two' ).val();
var formData = {
action: 'coolplugin_create_post',
some: val_one,
data: val_two,
};
request = $.ajax({
type: 'POST',
url: coolPluginAjaxUrl,
data: formData,
});
});
The formData holds the coolplugin_create_post action defined in PHP and the request is posted to the coolPluginAjaxUrl URL, defined in the head.
Thanks Nick for pointing me into the right direction and I hope that my solution will also help others. Please note that I've stripped my code of several security measures for others to easily understand how the code works.

Force download file IN IE

while download file using codeigniter in IE it redirects image path with out showing any popup like firefox or chrome to download file
code I am using in my controller:
public function download_file($filename)
{
$this->load->helper('download'); //load helper
$data = file_get_contents('wall-images/'.$filename); // Read the file's contents
$name = $filename;
force_download($name, $data);
}
I use javascript & it works for all browsers.
<a target="_blank" class="btn btn-primary" id="download" href="#">Download File</a>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#download').click(function(){
var url = "<?php echo site_url($filename); ?>";
document.location = url;
});
});
</script>
IE does not support neither navigating to a data URI nor the download attribute.
You can use navigator.msSaveBlob to save file for IE 10+.
You can check window.navigator.msSaveBloband write IE specific Code otherwise use existing code to save file.
You can check following link for more details:
Saving files locally using Blob and msSaveBlob

passing data from view to controller with ajax

I'm currently doing an application which uses ajax in getting user inputs from form fields then concatenate it in a string, this works fine but I'm getting a
"POST 500 (Internal Server Error")
and cannot pass the data. How do I pass a string from view to controller with ajax and access it in a controller.
Here are my codes:
the script
<script>
// $(document).ready(function(){
function saveData(){
var con = document.getElementById('tiks').value;
// var dataString = {'conid':con};
alert(con);
var cct = $("input[name=csrf_token_name]").val();
var base_url = <?php base_url(); ?>;
$.ajax({
url: base_url + "welcome/newShortestPath",
type: "POST",
data: {'conid':con, 'csrf_token_name':cct},
success:function(){
alert("SUCCESS KALUY-I "+con);
$('#myForm')[0].reset();
}
});
}
controller
public function newShortestPath(){
echo "REACHED";
$var = $this->input->post('conid');
//$this -> load -> model('edge_model');
//$this->edge_model->setConstraints();
}
really need your help guys. thanks in advance. :)
UPDATE
Im no longer getting any error by fixing the errors at calling the base_url() function but at the same time I cant fetch the passed data, is there any other way fetching data from post to controller?
you have to echo the base_url and wrap your var with ''
var base_url = '<?php echo base_url(); ?>';
Update
based on the error you are getting which is:
Fatal error: Call to undefined function base_url()
as you mentioned in your comment.
what you have to do is to go to application/config/autoload.php
and find
$autoload['helper'] = array();
then change it to
$autoload['helper'] = array('url');
or manually load the url helper:
$this->load->helper('url');
read more here
Tips:
Tip 1:
You can setup all url:
var url = <?php echo site_url('welcome/newShortestPath'); ?>;
Tip 2:
Use site_url() instead base_url(). base_url must be used to resources (img, css, js, etc.)
To build URL's use site_url()

How can I use Ckfinder with Ckeditor?

I was used Ckeditor in my project. It was worked well. I can put picture in texts but with an url. I know that,if I want upload an picture from my pc, I must used CKfinder.
How can I use Ckfinder with Ckeditor?
I use this code to call CKeditor:
protected void Page_Load(object sender, EventArgs e)
{
String StrScript = "CKEDITOR.replace( '" + TextBox1.ClientID + "',{toolbar : 'Full'});";
ClientScript.RegisterStartupScript(this.GetType(), "Ck-Js/ckeditor", StrScript, true);
}
Thanks.
it takes nearly 5 minutes to complete setup:
Download CKEditor and CKFinder.
Put extracted code of both in one folder inside xampp as below.
Create index file (index.html) which will be containing the editor as below code.
<html>
<head>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckfinder/ckfinder.js"></script>
</head>
<body>
<h1>CKEditor CKFinder Integration using PHP</h1>
<textarea id="editor1" name="editor1" rows="10" cols="80"></textarea>
<script type="text/javascript">
var editor = CKEDITOR.replace( 'editor1', {
filebrowserBrowseUrl : 'ckfinder/ckfinder.html',
filebrowserImageBrowseUrl : 'ckfinder/ckfinder.html?type=Images',
filebrowserFlashBrowseUrl : 'ckfinder/ckfinder.html?type=Flash',
filebrowserUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
filebrowserImageUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
filebrowserFlashUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
});
CKFinder.setupCKEditor( editor, '../' );
</script>
</body>
</html>
so your folder structure will be something like this:
htdocs
|_integrated
|_ckeditor
| |_config.js
| |_...
|_ckfinder
| |_config.php
| |_...
|_uploads
|_index.html
Now open file config.php inside ckfinder & make following changes:
function CheckAuthentication() {
return true;
}
$baseUrl = 'http://localhost/integrated/uploads/';
$enabled = true;
$config['SecureImageUploads'] = false;
$config['ChmodFolders'] = 0777 ;
Now open url http://localhost/integrated/ and try uploading image.
I think you want use CKFinder and CKEditor, try this :
Documentation : http://docs.cksource.com/CKFinder_2.x/Developers_Guide/ASP/CKEditor_Integration
http://docs.cksource.com/CKFinder_2.x/Developers_Guide/ASP/FCKeditor_Integration
En Francais : http://creer-un-site.fr/integration-du-formulaire-d-upload-ckfinder-a-l-editeur-ckeditor-202.php
If anyone is still having problems integrating CKFinder with CKEditor, try using KCFinder (http://kcfinder.sunhater.com/) instead.
It has all the same functions as CKFinder, but its free, open source, and much easier to install and setup. (Personally, I was never able to get CKFinder installed properly....)
The installation instructions for KCFinder are here:
http://kcfinder.sunhater.com/install
And the integration instructions are here:
http://kcfinder.sunhater.com/integrate
https://ckeditor.com/ckeditor-4/download/
download ckfinder place it both in single place then
<textarea class="ckeditor" id="editor1"></textarea>
place this code in footer.php or direct on page also
CKEDITOR.replace( 'editor1', {
filebrowserBrowseUrl: 'https://example.com/admin/ckfinder/ckfinder.html',
filebrowserImageBrowseUrl: 'https://example.com/admin/ckfinder/ckfinder.html?type=Images',
filebrowserUploadUrl: 'https://example.com/admin/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
filebrowserImageUploadUrl: 'https://example.com/admin/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images'
});
in ckfinder/config.php file open and make some change
$config['authentication'] = function () {
return true;
};
$config['backends'][] = array(
'name' => 'default',
'adapter' => 'local',
'baseUrl' => 'https://example.com/admin/ckfinder/userfiles/',
// 'root' => '', // Can be used to explicitly set the CKFinder user files directory.
'chmodFiles' => 0777,
'chmodFolders' => 0755,
'filesystemEncoding' => 'UTF-8',
);
That's it, it work for me.
If this is helpful for you please rate us me

Magento - link to a frontend skin js file from an admin file

I'm already using jQuery in my frontend skin files. I've now added some extra functionality in an admin phtml file, that also needs to use jQuery. I don't want to have to include it twice, but how can I link to the existing jQuery file dynamically, assuming I don't know what theme package name is being used on the frontend (because obviously that can change, so I don't want it hardcoded)?
For example, I tried this, but it gives me the admin theme package name, not the frontend package:
<?php
// Get the package name
$configData = Mage::getStoreConfig('design');
$package = $configData['package']['name'];
?>
Anyone?
OK, this seems to be working. I can access the db directly, look for the "design/package/name" in the core_config_data table and then build the url to the js file using that:
<?php // Get the current theme being used, so we can build the url link to our jQuery file
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$tablename = Mage::getSingleton('core/resource')->getTableName('core_config_data');
$results = $connection->fetchAll("SELECT * FROM $tablename WHERE path='design/package/name';");
foreach($results as $row) { $theme = $row['value']; };
?>
<script type="text/javascript" src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN).'frontend/'.$theme; ?>/default/js/jquery.min.js"></script>
for me helped to set $storeId as 1 not 0
$package = Mage::getStoreConfig('design/package/name', 1);
$theme = Mage::getStoreConfig('design/theme/default', 1);

Resources