0

Code from functions.php

function university_files()
{
   wp_localize_script('main-university-js', 'universityData', array(
        'root-url' => get_site_url()
    ));
};

add_action('wp_enqueue_scripts', 'university_files');

Code from JS

getResults() {
    $.getJSON(
      universityData.root_url +
        "/wp-json/wp/v2/posts?search=" +
        this.searchField.val(),
      (posts) => {
        this.resultsDiv.html(`
        <h2 class ="search-overlay__section-title">General Information</h2>
          ${
            posts.length
              ? `<ul class="link-list min-list">`
              : `No General Information Marched your search`
          }
            ${posts
              .map(
                (item) =>
                  `<li><a href="${item.link}">${item.title.rendered}</a></li>`
              )
              .join("")}
          ${posts.length ? `</ul>` : ""}
        
        `);
        this.isSpinnerVisible = false;
      }
    );
  }

Image from inspect element where the error can be seen

3
  • you shouldn't build your HTML out of strings in javascript, it's insecure. jQuery already provides methods of doing it by building nodes. Don't do this: jQuery( '<a href="' + url '">test</a>') it's dangerous, you should do jQuery( 'a', { href: url, text: 'test' } ) instead it's safer and avoids a lot of exploits and attacks
    – Tom J Nowell
    Commented Aug 7, 2022 at 18:52
  • This is new. I just started using jquery. Before I was relaying on plain js Commented Aug 10, 2022 at 15:18
  • it's the same problem if you try and do it with plain JS by joining together HTML strings, build your DOM nodes and append them rather than passing it a big HTML string and it'll be much harder to hack you. The browser will do a tonne of security stuff for you, like checking the URL is a valid URL and formatting everything properly for free
    – Tom J Nowell
    Commented Aug 11, 2022 at 9:09

1 Answer 1

2

Because you have:

universityData.root_url

But you localised:

'root-url' => get_site_url()

root_url != root-url

2
  • Thanks Tom. I really hate that after 3 years in wordpress and coding, I am still making syntax mistakes Commented Aug 10, 2022 at 15:16
  • happens to the best of us :) I once spent 2 days stuggling because I'd use {} instead of [] on a useState call
    – Tom J Nowell
    Commented Aug 11, 2022 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.