Home > other >  Ajax and Json Search
Ajax and Json Search

Time:11-12

We found this code online and we are trying to make it work with our project but need help with one small part...

    function ajsearch () {
      var data = new FormData();
      data.append("search", document.getElementById("search").value);
      data.append("ajax", 1);
      fetch("2-search.php", { method:"POST", body:data })
      .then(res => res.json()).then((results) => {
        var wrapper = document.getElementById("results");
        if (results.length > 0) {
          wrapper.innerHTML = "";
          for (let res of results) {
            let line = document.createElement("div");
            line.innerHTML = `<a href='<?= $baseurl ?>/listings/${res["state"]}/${res["slug"]}'>${res["city_name"]}, ${res["state_name"]}</a>`;
           wrapper.appendChild(line);
          }
        } else { wrapper.innerHTML = "No city or town found request it be added by using our <a href='<?= $baseurl ?>/contact'><strong>contact form</strong></a>"; }
      });
      return false;
    }

Now the problem is we need this

${res["state"]}

To be all lower case and add a hyphon - where there is a space so it looks like this new-york...

Any help would be appreciated.

CodePudding user response:

You could use split function in order to replace spaces with -, so you can try

{res["state"]}.split(' ').join('-')

and can use the toLowerCase to basically make your string lowercase, so it should be

${res["state"]}.split(' ').join('-').toLowerCase()

CodePudding user response:

We got it we just modified your original code to the following ${res["state"].split(' ').join('-').toLowerCase()} instead of this ${res["state"]}.split(' ').join('-').toLowerCase()

  • Related