In a plugin, How to update a json file using ajax

Question

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.

Steps

  1. Some text is written in a div (thanks to Trumbowyg.js).
  2. On div blur event, the plugin sends the content data with ajax.
  3. 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.

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 !

0
Hurlemort 2 months 0 Answers 12 views 0

Leave an answer