Context
Learning plugin creation, i want to save the content of a div each time the user click outside of it. In a nutshell, the purpose is to create a text backup of a notepad.
I'm working in Local.
Steps
- Some text is written in a div (thanks to Trumbowyg.js).
- On div blur event, the plugin sends the content data with ajax.
- Plugin function opens a json file, and update its content with the new text.
Issues
Several. I think i'm blocked at step 3. Hours of info search made me lost my mind.
Update
I tried to use wp_remote_get() instead of file_get_contents(), and it returns an error : [0] => A valid URL was not provided. However i can't figure out what path it needs.
jdr.js
$path = plugin_dir_path ( __FILE__ ) . "assets/json/notes.json";
// $path = plugin_dir_url ( __FILE__ ) . "assets/json/notes.json";
// $path = ABSPATH . "assets/json/notes.json";
// $path = plugins_url("/jdr/assets/json/notes.json");
$args_for_get = array(
'stream' => true,
'sslverify' => false,
'filename' => $chemin3,
'reject_unsafe_urls' => true,
'method' => "POST"
);
$response = wp_remote_get( $chemin, $args_for_get );
print_r(response);
$response in console
WP_Error Object
(
[errors] => Array
(
[http_request_failed] => Array
(
[0] => L’URL fournie n’est pas valide. // A valid URL was not provided
)
)
[error_data] => Array
(
)
)
My code
Wordpress plugin structure:
plugins/
-jdr.php
-lbh-jdr/
-inc/
-enqueue-scripts.php
-fonctions.php (= functions)
-assets/
-js/
-plugin-jdr.js
-json/
-notes.json
jdr.php
<?php
/*
Plugin Name: jdr
etc..
*/
function lbh_jdr() {
defined('MYPLUGIN_DIR') or define('MYPLUGIN_DIR', plugin_dir_path( __FILE__ ));
include_once( MYPLUGIN_DIR . '/inc/enqueue-scripts.php');
include_once( MYPLUGIN_DIR . '/inc/fonctions.php');
$texte = $_REQUEST["texte"];
$sessionPerso = $_REQUEST["sessionPerso"];
$appelFonction = $_REQUEST["ajaxAction"];
switch($appelFonction) {
case 'sauvegarderNote' : do_action("sauvegarderNote", $texte); break;
}
if(defined('DOING_AJAX') && DOING_AJAX) die();
}
add_action("wp_ajax_lbh_jdr", "lbh_jdr");
add_action("wp_ajax_nopriv_lbh_jdr", "lbh_jdr");
?>
enqueue-scripts.php
note : If i encapsulate enqueued script + add_action, it doesn't work. Can't figure out why
The proper way :
function my_script_enqueuer() {
wp_enqueue_script( "jdr-script", plugins_url("jdr/assets/js/plugin-jdr.js", __FILE__),
array("jquery"), "", true );
wp_localize_script( "jdr-script", "myAjax", array(
"ajaxurl" => admin_url( "admin-ajax.php"
)));
}
add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );
The working-for-me way :
wp_enqueue_script( "jdr-script", plugins_url("jdr/assets/js/plugin-jdr.js", __FILE__),
array("jquery"), "", true );
wp_localize_script( "jdr-script", "myAjax", array(
"ajaxurl" => admin_url( "admin-ajax.php"
)));
Fonctions.php
add_action('wp_ajax_nopriv_sauvegarderNote', 'sauvegarderNote');
add_action('wp_ajax_sauvegarderNote', 'sauvegarderNote');
function sauvegarderNote() { // sauvergarderNote means saveNote
$json = getJsondata();
$jsonTableau = $json[0]; // Tableau means array
$jsonChemin = $json[1]; // Chemin means path
$jsonTableau["notes"] = [$texte];
array_push($jsonTableau, $texte);
$newJsonString = json_encode($jsonTableau, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE |
JSON_UNESCAPED_SLASHES);
file_put_contents($jsonChemin, $newJsonString);
}
function getJsondata() {
$chemin = plugin_dir_url( __FILE__ ) . "inc/json/notes.json";
$jsonString = file_get_contents($chemin);
$tempArray = json_decode($jsonString, true);
return $tempArray;
}
plugin-jdr.js
jQuery( document ).ready( function() {
let newData = {
action: "lbh_jdr",
ajaxAction: "sauvegarderNote",
texte: jQuery("#blocNotes").text(),
sessionPerso: sessionPerso
};
jQuery.ajax({
url: myAjax.ajaxurl,
data: newData,
type: 'post',
error: function(e) {
console.log(e);
}
})
.done(function(response) {
console.log(response);
});
});
Questions
So... Why my enqueue_scripts does not work if i do it the way intended ? Why file_get_contents returns nothing ? What is the proper way to read/write in a json file using wordpress + Ajax ?
Thank you by advance, i will stay tuned !
plugin_dir_url
, this will return a URL rather than a file path, and I also notice you did not pass it the plugin file, but rather a file in a subfolder (fonctions.php
) which is an incorrect usage. It must be the main plugin file, if it is not the main plugin file it will not work