Fatal error and use of undefined constant in child theme unless I redefine it

Child theme functions.php:

// Init. require_once( WPBF_CHILD_THEME_DIR . '/inc/init-child.php'); 

In the parent theme functions.php, the constant is defined:

define( 'WPBF_CHILD_THEME_DIR', get_stylesheet_directory() ); 

If I include the same constant definition in the child theme like the above, then the require_once works and /inc/init-child.php file is loaded.

However I get a notice stating that the constant is already defined in the parent theme’s functions.php (correct!).

But if I remove this from the child theme’s functions.php, then I get the following:-

Warning: Use of undefined constant WPBF_CHILD_THEME_DIR - assumed 'WPBF_CHILD_THEME_DIR' (this will throw an Error in a future version of PHP) in /var/www/vhosts/xxx/subdomains/xxx/httpdocs/wp-content/themes/page-builder-framework-child/functions.php on line 42  Warning: require_once(WPBF_CHILD_THEME_DIR/inc/init-child.php): failed to open stream: No such file or directory in /var/www/vhosts/xxx/subdomains/xxx/httpdocs/wp-content/themes/page-builder-framework-child/functions.php on line 42  Fatal error: require_once(): Failed opening required 'WPBF_CHILD_THEME_DIR/inc/init-child.php' (include_path='.:/opt/plesk/php/7.3/share/pear') in /var/www/vhosts/xxx/subdomains/xxx/httpdocs/wp-content/themes/page-builder-framework-child/functions.php on line 42 

So why can I only load the file via the child theme if I redefine the constant even though it is going to show me a notice to state it is already defined…?

The same constant is already in use in the very same child theme functions.php file further up as well like:

// Textdomain. load_child_theme_textdomain( 'page-builder-framework-child', WPBF_CHILD_THEME_DIR . '/languages' ); 

I am assuming there should be a correct way to load the file needed without having to repeat constant definitions?

WP Ajax Function Always Returning undefined

What is the deal here?

JS FUNCTION ‘custom.js’

function validate() {     var email = jQuery("#billingemail").val();      if (isValidEmailAddress(email)) {         jQuery.ajax({             type: 'POST',             url: ajaxurl,             data: {"action": "custome_ajax_email_check", "guestemail": email },             success: function(data){                 data = jQuery.parseJSON(data);                 if(data.result) {                     alert('Email Exists');                     return false;                 } else {                     alert('Email Does Exists');                     return true;                 }             }         });     } else {         return false;     } } 

JS ON CLICK ‘custom.js’

 $  ('#mwb_logincoupon').on('click', '#validateguestemail', function (e) {         e.preventDefault();         validateemail = validate();          

PHP AJAX

add_action( 'wp_ajax_custome_ajax_email_check', 'custome_ajax_email_check' ); add_action('wp_ajax_nopriv_custome_ajax_email_check', 'custome_ajax_email_check');  function custome_ajax_email_check(){     $  email = $  _POST['guestemail'];      // do check     if ( email_exists($  email) ) {         $  response->result = true;     }     else {         $  response->result = false;     }      echo( json_encode( $  response));     wp_die(); } 

debugging the script the JS code goes into the success function, so far as even triggering off the alert('Email Exists').. but the return statement in the functon is never retrieved thus making validateemail always return undefined. Why?

error (Undefined index) and (Cannot modify header information – headers already)

Error:

Notice: Undefined index: link_type in /home/golchind/public_html/wp-content/themes/golchindl/functions.php on line 40

Notice: Trying to get property of non-object in /home/golchind/public_html/wp-content/themes/golchindl/functions.php on line 58

Warning: Cannot modify header information – headers already sent by (output started at /home/golchind/public_html/wp-content/themes/golchindl/functions.php:40) in /home/golchind/public_html/wp-admin/admin-header.php on line 9

help :

line 40

$ type = $ _POST[‘link_type’];

line 58

update_post_meta($ post->ID,”_oscar_data”,json_encode(array(“episodes”=>$ episodes,”links”=>$ links,”type”=>$ type), JSON_UNESCAPED_UNICODE));

function oscar_meta_box_js(){     wp_enqueue_style( 'oscar_box_style',get_bloginfo('template_url')."/css/admin_meta_box.css");     wp_enqueue_script( 'oscar_box', get_bloginfo('template_url'). '/js/meta_boxes.js', array('jquery'),'1.0',true); } add_action( 'admin_enqueue_scripts', 'oscar_meta_box_js');   function oscar_meta_save(){     global $  post,$  meta_args,$  meta_dls;     $  type = $  _POST['link_type'];     $  episodes = array();     $  links = array();     if($  type == "serial"){         for($  i=0;$  i<count($  _POST['ep_name']);$  i++){             $  episodes[] = array("name"=>$  _POST['ep_name'][$  i],"quality"=>$  _POST['ep_quality'][$  i],"medium_size"=>$  _POST['ep_med'][$  i]);         }         for($  i=0;$  i<count($  _POST['link']);$  i++){             $  links[] = array("name"=>$  _POST['name'][$  i],"link"=>$  _POST['link'][$  i],"subtitle"=>$  _POST['subtitle'][$  i],"screenshot"=>$  _POST['screenshot'][$  i],"episode"=>$  _POST['episode'][$  i]);         }     } else if($  type == "movie") {         for($  i=0;$  i<count($  _POST['movie_title']);$  i++){             $  episodes[] = array("name"=>$  _POST['movie_title'][$  i]);         }         for($  i=0;$  i<count($  _POST['mlink']);$  i++){             $  links[] = array("name"=>$  _POST['mname'][$  i],"link"=>$  _POST['mlink'][$  i],"subtitle"=>$  _POST['msubtitle'][$  i],"screenshot"=>$  _POST['mscreenshot'][$  i],"episode"=>$  _POST['mtitle'][$  i]);         }     }     update_post_meta($  post->ID,"_oscar_data",json_encode(array("episodes"=>$  episodes,"links"=>$  links,"type"=>$  type), JSON_UNESCAPED_UNICODE)); }        function oscar_download(){     global $  post;     ?> <script> var $   = jQuery; $  (function(){     var data = '<?=get_post_meta($  post->ID,"_oscar_data",true);?>';     if(data != ""){         data = JSON.parse(data);         var type = data['type'];         data['episodes'].forEach(function(e){             if(type == "serial")                 add_ep(e['name'],e['quality'],e['medium_size'])             else                 add_title(e['name']);         });         data['links'].forEach(function(e){             if(type == "serial")                 add_link(e['name'],e['link'],e['subtitle'],e['screenshot'],e['episode'])             else                 add_mlink(e['name'],e['link'],e['subtitle'],e['screenshot'],e['episode'])         });         if(data['type']){           $  ("#link_type").val(data['type']);     }     }     normalize_links()     normalize_mlinks() }); </script> <?php if ('series' == get_post_type()) { ?> <div id="serial" class="content">     <div class="side_inp_keeper">         <input id="title_serial" type="text" placeholder="عنوان فصل">         <input id="quality_serial" type="text" placeholder="کیفیت">         <input id="med_serial" type="text" placeholder="میانگین حجم هم قسمت">         <button id="add_ep" class="button">افزودن</button>     </div>     <div id="episodes">      </div>     <hr>     <div class="links" style="display:none;">             <div class="side_inp_keeper">                 <select id="ep"></select>                 <input type="text" id="name" placeholder="عنوان لینک">                 <input type="text" id="link" placeholder="لینک دانلود">                 <input type="text" id="subtitle" placeholder="زیر نویس">                 <input type="text" id="screenshot" placeholder="نمونه کیفیت">                 <button id="add_link" class="button">افزودن</button>             </div>             <div id="links">              </div>         </div> </div> <?php } else if ('movies' == get_post_type()) { ?> <div id="movie" class="content">     <div class="side_inp_keeper">         <input type="text" name="movie_title" id="movie_title" placeholder="عنوان (مثال : زبان اصلی)"><button id="add_link_title" class="button">افزودن</button>     </div>     <div id="titles">      </div>     <hr>     <div class="mlinks">         <div class="side_inp_keeper">                     <select id="titl"></select>                     <input type="text" id="mname" placeholder="عنوان لینک">                     <input type="text" id="mlink" placeholder="لینک دانلود">                     <input type="text" id="msubtitle" placeholder="زیر نویس">                     <input type="text" id="mscreenshot" placeholder="نمونه کیفیت">                     <button id="add_mlink" class="button">افزودن</button>         </div>         <div id="mlinks">          </div>     </div> </div> <?php } ?> <input type="hidden" name="link_type" id="link_type" value="serial">     <?php }    function oscar_meta_boxes() {     add_meta_box( 'oscar_download',"باکس دانلود", 'oscar_download', array('movies', 'series'), 'normal', 'high' ); } add_action("save_post","oscar_meta_save"); add_action( 'add_meta_boxes', 'oscar_meta_boxes' ); 

Conditionally returning a constant if function returns Undefined

Often times functions might return Undefined in Mathematica, e.g. when the Volume@RegionIntersection is called for 2 objects which have no overlapping volume. A simple If statement checking if the return has been indeed Undefined does not seem to work. For example, a=Undefined; If[a == Undefined, Print["yes"]] ends up printing the command itself.

  • How can we check if a variable (or a function return) such as a has been assigned as Undefined and assign a different value to it in that case?

SPServices.SPAutocomplete cannot read property ‘find’ of undefined

I have created a SharePoint page and inserted text box using content editor web part with title of FilterTextBox

<input type="text" title="FilterTextBox"/> 

and I have inserted below script using Script Editor web part

<script language="javascript" type="text/javascript">     $  (document).ready(function() {         $  ().SPServices.SPAutocomplete({              sourceList: "Country",             sourceColumn: "Title",             columnName: "FilterTextBox",             ignoreCase: true,             numChars: 3,             slideDownSpeed: 1000,             debug: true         });     }); </script> 

but I get the following error when page load

Uncaught TypeError: Cannot read property ‘find’ of undefined

what might be wrong with my code ? thanks .

Call to undefined relationship [sub_category] on model [App\Sub_Category]

Estoy intentado hacer una llamada por get para obtener todas mis “subcategorias”, me surge el error: Call to undefined relationship [sub_category] on model [App\Sub_Category].

Estoy en duda ya que no se si el error es 100% de la base de datos o de la consulta.

Por favor si alguien pudiera ayudarme lo agradecería

Clase

public function store(Request $  request) {     // Recoger los datos     $  json = $  request->input('json', null);     $  params = json_decode($  json);     $  params_array = json_decode($  json, true);     if (!empty($  params_array)) {          $  jwtAuth = new JwtAuth();         $  token = $  request->header('Authorization', null);         $  user = $  jwtAuth->checkToken($  token, true);          // Validar los datos         $  validate = \Validator::make($  params_array, [                     'name' => 'required'         ]);         //Guardar los datos         if ($  validate->fails()) {             $  data = [                 'code' => 400,                 'status' => 'error',                 'message' => 'Envia el nombre'             ];         } else {             $  sub_category = new Sub_Category();             $  sub_category->name = $  params_array['name'];             $  sub_category->category_id = $  params->category_id;             $  sub_category->save();              $  data = [                 'code' => 200,                 'status' => 'success',                 'sub_category' => $  sub_category             ];         }     } else {         $  data = [             'code' => 400,             'status' => 'error',             'mensage' => 'No has enviado ninguna sub_categoria'         ];     }      // Devolcer Sub_Categoria     return response()->json($  data, $  data['code']); } 

Modelo

class Sub_Category extends Model {     // Referencia a la base de datos     protected $  table = 'sub_categories';      // Unos a muchos     public function give_posts(){         return $  this->hasMany('App\Post');     }      // Relación Muchos a uno     public function category(){         return $  this->belongsTo('App\Category', 'category_id');     } 

Base de datos

El objetivo es poder obtener cualquier dato para poder modificar lo posteriormente, aquí dejo las 2 talabas que se tiene que relacionar.

CREATE TABLE categories( id                  int(255) auto_increment not null, name                varchar(255)  NOT NULL, created_at           datetime DEFAULT NULL, updated_at           datetime DEFAULT NULL, CONSTRAINT  pk_users PRIMARY KEY(id) )ENGINE=InnoDb;  CREATE TABLE sub_categories( id                  int(255) auto_increment not null, name                varchar(50)  NOT NULL, category_id         int(255) NOT NULL, created_at           datetime DEFAULT NULL, updated_at           datetime DEFAULT NULL, CONSTRAINT  pk_users PRIMARY KEY(id), CONSTRAINT  fk_post_category FOREIGN KEY(category_id) REFERENCES categories(id) )ENGINE=InnoDb; 

SPHttpClient undefined error: Using React JS to add item in SharePoint list

I’m trying to add an item in SharePoint Online list using SPFx solution where I’m using React JS to perform the action.

Below is the copied code, when debugging it says that:

“VM242:1 Uncaught TypeError: Cannot read property ‘spHttpClient’ of undefined”

Please have a look at the below code and let me know if I’m missing out on any thing.

I’m just trying to add an item in list called test.

function _alertClicked(): void {   alert('Clicked');   //Custom   const body: string = JSON.stringify({     'Title': `Item $  {new Date()}`   });   this.context.SPHttpClient.post(`$  {this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('test')/items`,     SPHttpClient.configurations.v1,     {       headers: {         'Accept': 'application/json;odata=nometadata',         'Content-type': 'application/json;odata=nometadata',         'odata-version': ''       },       body: body     })     .then((Response: SPHttpClientResponse): Promise<IListItem> => {       return Response.json();     })     .then((item: IListItem): void => {       this.updateStatus(`Item 'Test' Successfully Created`);     }, (error: any): void => {       this.updateStatus('Error' + error);     });  } 

Note: I’m using fabric controls on the page.

No puedo acceder a las propiedades de un Objeto da “UNDEFINED” como resultado el console.log(objeto.propiedad)

Al realizar una consulta utilizando Express y Mongoose, y utilizando console.log para revisar el resultado del siguiente codigo:

const consults = await Consult.find({ user: req.user.id }).populate('patient', 'patient_name patient_phone');      console.log(typeof(consults));     console.log(consults);     console.log(consults._id);     console.log(consults.c_motive);     console.log(consults.c_amount);     console.log(consults.c_cDate); 

Obtengo el siguiente resultado de los console.log()

console.log(typeof(consults)); Resultado//

object 

console.log(consults); Resultado//

[ { _id: 5d9f483c1cb2710408aeaf20,     c_note:      'Se presento con un dolor de estomago recurrente, y diarrea.',     c_prescription: 'Tinidazol',     c_motive: 'Dolor de estomago recurrente',     c_amount: 200,     c_recurrent: 'New',     c_cDate: 2019-10-10T15:03:24.144Z,     user: 5d9574bcc31c0e10c83fcb3b,     patient:      { _id: 5d9f47811cb2710408aeaf1f,        patient_name: 'Miguel Marroquin',        patient_phone: '40009374' },     c_status: 'PAID',     __v: 0 } ] 

console.log(consults._id); Resultado//

undefined 

console.log(consults.c_motive); Resultado//

undefined 

console.log(consults.c_amount); Resultado//

undefined 

console.log(consults.c_cDate); Resultado//

 undefined 

Como logro acceder a las propiedades del objeto para trabajar con ellas?

Undefined Variable $db en php

I have been trying to delete a product in the database trough a button in my php file, however, in the same file I am able to show the products in a table. When I click the button an error pops up saying ‘undefined variable $ db’. In adittion I am trying to show each products´s IDs but for some reason I can only show the first and the second ID and then the 3rd product ID is 2 which is the 2nd products ID.

I have been trying to echo some random stuff to know in whay point does my page breaks down.

Estoy tratando de eliminar un producto de mi base de datos a traves de un boton en mi php, sin embargo, en el mismo archivo soy capaz de traer los productos de la base de datos.

Cuando clickeo el boton me lleva a otra pagina y me dice un error que la variable $ db no esta definida. Ademas cuando trato de mostrar el Id de cada producto, por alguna razon solo puedo mostrar correctamente el id del 1er y 2do producto, despues el 3er producto tiene el id del 2do (los nombres igual los muestra bien).

Estuve tratando de hacer echo de cosas random para ver hasta que punto llega mi codigo.

<?php       $  db = new mysqli("localhost", "root", "", "buffet");      $  sql_comida = "SELECT * FROM Producto where idCategoria = 1";     $  comidas = $  db->query($  sql_comida);     if(isset($  _GET['delete']) && !empty($  _GET['delete'])){         $  delete_id = (int)$  _GET['idProducto'];         $  sql = "DELETE FROM Producto WHERE idProducto = '$  delete_id'";         $  db->query($  sql);         header('Location: productos_admin.php');     }  ?>  <table class="table table-bordered table-striped table-auto table-condensed">     <thead>         <th>Producto</th>         <th>Precio</th>         <th>Stock</th>         <th> </th>     </thead>     <tbody>     <?php while($  auxiliar = $  comidas->FETCH_ASSOC()): ?>         <?php $  comida = new Productos($  auxiliar["idProducto"], $  auxiliar["Nombre"], $  auxiliar["Precio"], $  auxiliar["Stock"], $  auxiliar["RutaImagen"])?>             <tr>                 <?php $  comida->mostrarInformacionTabla(); ?>                     <td>                         <a href= "productos_admin.php?delete=<?= $  comida->getIdProducto();?>" >                             <button type='button' data-toggle="modal">                                 <i class="fa fa-trash-o" aria-hidden="true">                                     <form action="includes/vistaAdmin/productos_admin.php" method="get">                                         <input type="hidden" name="idProducto" id="idProducto" value="<?php echo $  comida->getIdProducto() ?>"/>                                     </form>                                 </i>                             </button>                           </a>                     </td>                 </tr>             <?php endwhile; ?>               </tbody>     </table>