0

I'm simply trying to read a one line .txt file to a variable. I later want to show that variable in the webpage.

My folder structure:

NewsAlerts
    index.html
    assets
        searchterms.txt
        js
            newsalerts.js [THIS is the .js that runs the code below]
        css
            style.css

My searchterms.txt is solely comprised of:

Chicago AND Illinois OR (Summer AND Winter)

so I am simply expecting my javascript variable to hold that string.

Code:

var search_terms = $(".text").load("assets/searchterms.txt");

$("#terms_submission").on("click", function(){
    $("#terms_list").add("<span>" + search_terms);
    alert(search_terms.valueOf());
});

jQuery does seem to be loading something, if I add alert(search_terms), I get [object Object]. But doing search_terms.text() returns "" so maybe it's correctly creating an Object variable ...but with nothing in it.

BruceWayne
  • 22,923
  • 15
  • 65
  • 110
  • don't use `.load` - use `$.get` – Daniel A. White Aug 06 '18 at 16:47
  • 3
    Docs never say .load() will assign loaded value to a variable. "When a successful response is detected, .load() sets the HTML contents of the matched element to the returned data" – marekful Aug 06 '18 at 16:49
  • If you're not sure what an object looks like use `console.dir(object)` instead of `alert(object)`. – zfrisch Aug 06 '18 at 16:54
  • @DanielA.White - Doing `var search_terms = $(".text").get("assets/searchterms.txt");` returns `undefined`. – BruceWayne Aug 06 '18 at 16:55
  • @DanielA.White - Also just trying `var search_terms = $.get("assets/searchterms.txt")` returns `> Object // undefined` where the `//` means new line. – BruceWayne Aug 06 '18 at 17:16
  • 1
    Possible duplicate of ["Cross origin requests are only supported for HTTP." error when loading a local file](https://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local) – BruceWayne Aug 06 '18 at 18:17

1 Answers1

0

It seems to have to do with the cross origin requests. The way to solve that, at least locally, is to start a local server from the News Alerts folder.

Instructions for Windows:

  1. Open the command prompt and change the directory to the top folder of the project.
  2. Start a local server with python -m http.server [note this is Python 3]
  3. Navigate to http://localhost:8000/
  4. The script will now run.

FWIW the final script I'm using is:

$.get(TXT, function(data){
    alert(data);
    $("new_search_terms").attr("placeholder", data);
});
BruceWayne
  • 22,923
  • 15
  • 65
  • 110