JavaScript to use a different proxy link if the first one returns a 404 error

I have some JS that works as follows:
If the Word Count button is pressed, go to the Word Count function, if the status of the requested page is 200, then let the url be proxyURL, which is defined correctly in index.html and this as it stands works.

I have then added an else if statement to say if a 404 is returned, then go to the function “WordCountProxyBackup” function, which works the same way as the original, but instead of using “proxyURL”, it uses proxybackupURL, which is defined in index.html

I have intentionally broken by original proxyURL to try and test this, and a 404 is returned, but the button is not finding it’s way to the backup function to then find it’s way to the backup link, can someone help with this? The code is below.

   function Wordcount()
{
    $(".operation").attr('disabled', true);
    this.disabled = true;
    let xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var j = JSON.parse(this.response);
            document.getElementById('output').value = j.answer;
        }else if (this.readyState == 4 && this.status == 404) {
            document.getElementById('output').value = "Error Bad Pathway - Rerouting";
            WordcountProxyBackup();
        }
    };

    let url = proxyURL + "/?text=" + encodeURI(document.getElementById('content').value) + "&route=" + "wordcount";
    xhttp.open("GET",url);
    xhttp.send();
    $(".operation").attr('disabled', false);
}

function WordcountProxyBackup()
{
    $(".operation").attr('disabled', true);
    this.disabled = true;
    let xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var j = JSON.parse(this.response);
            document.getElementById('output').value = j.answer;
        }else if (this.readyState == 4 && this.status == 500) {
            document.getElementById('output').value = "Error Bad Pathway - Rerouting";
            WordcountProxyBackup2();
        }
    };

    let url = proxybackupURL + "/?text=" + encodeURI(document.getElementById('content').value) + "&route=" + "wordcount";
    xhttp.open("GET",url);
    xhttp.send();
    $(".operation").attr('disabled', false);
}

How to force an Iframe to reload its source every time a page is opened?

I tried to find a solution to my problem for a few hours and I can’t seem to find it so here is my problem…

I’m not into coding and I’m a complete noob in making websites so bear with me please, I’m trying

I’m using an iframe generator to display a “moving fluid script” that I uploaded to a directory on my website (it’s displayed at ex: mywebsite.com/fluid) and every time that I open that page that script always starts its thing from the start but when I implement it on a homepage with iframe it doesn’t load every time from the beginning like on the mywebsite.com/fluid

I’m sorry if I didn’t explain it correctly but I hope someone understands my problem…

Is there a better way to show content from that page to my homepage but that I still have the ability to use Elementor to add some stuff over that “fluid script” or a way to force iframe to always show the script from the start as its seen when I visit mywebsite.com/fluid?

Thanks!

sum input fields value if they have the same value

I’m getting stuck on the logic to use to accomplish this in javascript/jquery and could use some help if anyone had any ideas.

I have table which shows the per item cost of the products on an invoice.

The goal is to find all the products by their class(currently shirtcountrow and hoodiecountrow but there will be more later) and combine the ones that have the same value.

The table currently looks like this:

<table id="productmathtable">
<tr>    
<td>Shirt</td>       
<td><input class="shirtcountrow" type="text" value="4" style="width:60px"> x <input class="productpricerow" type="text" value="25" style="width:60px"> = </td>      
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="100" style="width:60px"></td>
</tr>
<tr>         
<td>Shirt</td>       
<td><input class="shirtcountrow" type="text" value="2" style="width:60px"> x <input class="productpricerow" type="text" value="25" style="width:60px"> = </td>       
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="50" style="width:60px"></td>       
</tr>
<tr>         
<td>Shirt</td>       
<td><input class="shirtcountrow" type="text" value="2" style="width:60px"> x     <input class="productpricerow" type="text" value="25" style="width:60px"> = </td>      
 <td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="50" style="width:60px"></td>     
 </tr><tr>       
<td>Hoodie</td>     
 <td><input class="hoodiecountrow" type="text" value="4" style="width:60px"> x <input class="productpricerow" type="text" value="35" style="width:60px"> = </td>         
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="140" style="width:60px"></td>      
</tr>
<tr>         
 <td>Hoodie</td>        
 <td><input class="hoodiecountrow" type="text" value="4" style="width:60px"> x <input class="productpricerow" type="text" value="35" style="width:60px"> = </td>         
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="140" style="width:60px"></td></tr>     
</table>

And I want it to look like this after a jquery/javascript function is preformed:

<table id="productmathtable">
<tr>    
<td>Shirt</td>       
<td><input class="shirtcountrow" type="text" value="8" style="width:60px"> x <input class="productpricerow" type="text" value="25" style="width:60px"> = </td>      
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="200" style="width:60px"></td>
</tr> 
<td>Hoodie</td>     
 <td><input class="hoodiecountrow" type="text" value="8" style="width:60px"> x <input class="productpricerow" type="text" value="35" style="width:60px"> = </td>         
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="280" style="width:60px"></td>      
</tr>   
</table>

I am pretty sure i need to change my html so it’s easier to identify each part that i want to change, but im not exactly sure how

Why doesnt my HTML load on my browser and how can i fix it?

i am currently working on an eCommerce website and I’ve got the HTML and CSS codes down. Right now, i am currently working on the JavaScript for the add to cart functionality.
i have an array of 48 objects of products.
const products = [
{
id: 0,
name: “product one”,
price: 3000,
instock: 10,
category: “first”,
description:
“lhjsdbf whaiudehwi hlawbdiw lawdhawiudh IWUEHiawb hjabd”,
imgsrc: “img/jeans.jpg”,
},..]
and as a result, the page doesn’t load on my browser. i have also decided to instead make 4 array of products objects but that messes with the add to cart functionality even though the page loads.
merging the 4 arrays into one doesn’t work either. gives the same problems as a single array would.

what can i do?

Please explain how does this JS piece of code work?

my javascript is rusty, and I am having trouble understanding the code is hosted at w3schools – https://www.w3schools.com/howto/howto_js_cascading_dropdown.asp. But the full code I will add below.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
var subjectObject = {
  "Front-end": {
    "HTML": ["Links", "Images", "Tables", "Lists"],
    "CSS": ["Borders", "Margins", "Backgrounds", "Float"],
    "JavaScript": ["Variables", "Operators", "Functions", "Conditions"]    
  },
  "Back-end": {
    "PHP": ["Variables", "Strings", "Arrays"],
    "SQL": ["SELECT", "UPDATE", "DELETE"]
  }
}
window.onload = function() {
  var subjectSel = document.getElementById("subject");
  var topicSel = document.getElementById("topic");
  var chapterSel = document.getElementById("chapter");
  for (var x in subjectObject) {
    subjectSel.options[subjectSel.options.length] = new Option(x, x);
  }
  subjectSel.onchange = function() {
    //empty Chapters- and Topics- dropdowns
    chapterSel.length = 1;
    topicSel.length = 1;
    //display correct values
    for (var y in subjectObject[this.value]) {
      topicSel.options[topicSel.options.length] = new Option(y, y);
    }
  }
  topicSel.onchange = function() {
    //empty Chapters dropdown
    chapterSel.length = 1;
    //display correct values
    var z = subjectObject[subjectSel.value][this.value];
    for (var i = 0; i < z.length; i++) {
      chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
    }
  }
}
</script>
</head>   
<body>

<h1>Cascading Dropdown Example</h1>

<form name="form1" id="form1" action="/action_page.php">
Subjects: <select name="subject" id="subject">
    <option value="" selected="selected">Select subject</option>
  </select>
  <br><br>
Topics: <select name="topic" id="topic">
    <option value="" selected="selected">Please select subject first</option>
  </select>
  <br><br>
Chapters: <select name="chapter" id="chapter">
    <option value="" selected="selected">Please select topic first</option>
  </select>
  <br><br>
  <input type="submit" value="Submit">  
</form>

</body>
</html>

How does this part of the code work?

for (var x in subjectObject) {
    subjectSel.options[subjectSel.options.length] = new Option(x, x);
  }
  subjectSel.onchange = function() {
    //empty Chapters- and Topics- dropdowns
    chapterSel.length = 1;
    topicSel.length = 1;
    //display correct values
    for (var y in subjectObject[this.value]) {
      topicSel.options[topicSel.options.length] = new Option(y, y);
    }
  }
  topicSel.onchange = function() {
    //empty Chapters dropdown
    chapterSel.length = 1;
    //display correct values
    var z = subjectObject[subjectSel.value][this.value];
    for (var i = 0; i < z.length; i++) {
      chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
    }
  }

Im not understanding completely how the code works. Please correct me where I falter.

  • var subjectSel = document.getElementById("subject"); this gets the value of the option that is currently selected in the dropdown right?
  • im not sure what this means for (var x in subjectObject) { subjectSel.options[subjectSel.options.length] = new Option(x, x);. is it counting the number of options in the dropdown? what is new Option(x, x)?
  • subjectSel.onchange basically says if the 1st dropdown changes then do the following code. does chapterSel.length = 1; select the 1st option in the 2nd dropdown being what is already in the html – please select subject first?
  • for (var y in subjectObject[this.value]) { topicSel.options[topicSel.options.length] = new Option(y, y); } . What happens here? similar to the first dropdown, is it counting the number of the options in the dropdown?

Im not sure at what point or how it is determined which piece of information in the subjectobject object is put into which dropdown. how is the following 3 lines associated:

for (var x in subjectObject) {
 for (var y in subjectObject[this.value]) {
var z = subjectObject[subjectSel.value][this.value];
    for (var i = 0; i < z.length; i++) {

I can guess that it is linked to the object subjectobject, and I can see that “this.value” is getting nested further and further to select the relevant values. can you explain further how it is picking the value of the array and not the id, i.e. html,css, javascript, and not 0,1,2?

thanks in advance for your help

Develop Advanced HTML5 Player

How I can develop an customize HTML5 player With autoplay videos without any library , I sarched about this and develop one Like this by my edite https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/cross_browser_video_player
but I need to build more advinced one Like Youtube Player and other website , I want more experiences and advice To make an resolution Choice ex : ( 144 – 240 – 720 – 1080 ) ; and more 🙂

Node MySQL Geosearch

I am trying to search a MySQL database based on the north, south, east, and west bounds of a map. I am using Nodejs with express. When I use postman or enter the url in with the LAT and LON for the search it will work just fine. The issue comes when I try to build the URL sting form the front-end. I get back and empty JSON object.

app.get('/search', (req, res) => {
  try {
    connection.query(`SELECT * FROM photos WHERE lat BETWEEN '${req.query.north}' and '${req.query.south}' and lng BETWEEN '${req.query.west}' and '${req.query.east}'`, function (error, results, fields) {
      if (error) throw error;
      //console.log(results);
      res.send(results);
    });
  }
  catch (exception_var) {
    console.log("Error");
  }
})

This is the front-end client

async function mysearch() {
    myFeatureGroup.clearLayers();
    const mapEast = map.getBounds().getEast().toString();
    const mapWest = map.getBounds().getWest().toString();
    const mapNorth = map.getBounds().getNorth().toString();
    const mapSouth = map.getBounds().getSouth().toString();
   
    // http://127.0.0.1:3000/search?north=42.06254817666338&south=43.002638523957906&east=-89.55780029296875&west=-91.41448974609375
    // http://127.0.0.1:3000/search?north=${mapNorth}&south=${mapSouth}&east=${mapEast}&west=${mapWest}

    fetch(`http://127.0.0.1:3000/search?north=${mapNorth}&south=${mapSouth}&east=${mapEast}&west=${mapWest}`)
        .then(response => response.json())
        .then(data => {
            console.log(data);
        });
}

why the data obtained is data from a few days ago using cheerio?

I have a problem when using cheerio to retrieve news headline data. the case is that when I took the headline, the data obtained was data from 4 days ago. How can I get the latest data from the website? I’ve tried clearing cache and cookies, but it’s not working

this is my code

'use strict';
require('colors');

const request = require('request');
const cheerio = require('cheerio');
let url = 'https://prokalteng.jawapos.com/index-berita/';

request(url, function (err, res, body) {
   if (err && res.statusCode !== 200) throw err;

   let $ = cheerio.load(body);
   $('div.td_block_wrap.td_flex_block_1.tdi_74.td_with_ajax_pagination.td-pb-border-top.td_block_template_1.td_flex_block div[id=tdi_74] div div div.td-module-meta-info h3.entry-title.td-module-title').each((i, value) => {
       $(value).find('a').each((j, data) => {
           return process.stdout.write($(data).text() + 't');
       });
       process.stdout.write('n');
   });
});

this is the result and that data from 4 days ago
the result and data from 4 days ago

this is latest data
latest data

How do I get a specific key value from JSON object

This is my first time using any kind of APIs, and I’m just starting out in JS. I want to get the status of a server within a server hosting panel, to do this I need to log in (API/Core/Login), get a the value of a key called sessionID, then send that value to /API/Core/GetUpdates to get a response. When trying to pass the sessionID to GetUpdates, it sends undefined instead of the sessionID, I’m guessing I’m doing something wrong when trying to reference the key value. Here’s my code:

var loginurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/Login";

var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", loginurl);

loginRequest.setRequestHeader("Accept", "text/javascript");
loginRequest.setRequestHeader("Content-Type", "application/json");

loginRequest.onreadystatechange = function() {
  if (loginRequest.readyState === 4) {
    console.log(loginRequest.status);
    console.log(loginRequest.responseText);
  }
};

var logindata = '{"username":"API", "password":"password", "token":"", "rememberMe":"true"}';

loginRequest.send(logindata);

var statusurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/GetUpdates";

var statusreq = new XMLHttpRequest();
statusreq.open("POST", statusurl);

statusreq.setRequestHeader("Accept", "text/javascript");
statusreq.setRequestHeader("Content-Type", "application/json");

statusreq.onreadystatechange = function() {
  if (statusreq.readyState === 4) {
    console.log(statusreq.status);
    console.log(statusreq.responseText);
  }
};

var statusdata = `{"SESSIONID":"${loginRequest.responseText.sessionID}"}`; // Line I'm having problems with

statusreq.send(statusdata);

console.log(loginRequest.responseText.sessionID)

Here’s the response of /API/Core/Login

{"success":true,"permissions":[],"sessionID":"1d212b7a-a54d-4e91-abde-9e1f7b0e03f2","rememberMeToken":"5df7cf99-15f5-4e01-b804-6e33a65bd6d8","userInfo":{"ID":"034f33ba-3bca-47c7-922a-7a0e7bebd3fd","Username":"API","IsTwoFactorEnabled":false,"Disabled":false,"LastLogin":"/Date(1639944571884)/","GravatarHash":"8a5da52ed126447d359e70c05721a8aa","IsLDAPUser":false},"result":10}

Any help would be greatly appreciated, I’ve been stuck on this for awhile.

JQuery TablEdit add editable column dropdown option from database

I have a problem with TableEdit

This is in the documentation I read:

// Example #2
columns: {
    // Column used to identify table row.
    // [column_index, input_name]
    identifier: [0, 'id'],
    // Columns to transform in editable cells.
    // [[column_index, input_name], [column_index, input_name, select_options]]
    editable: [[1, 'car'], [2, 'color', '{"1": "Red", "2": "Green", "3": "Blue"}']]
}

In the editable key, the second array contains a json-like string that renders as a dropdown list when I press the edit button.

My question is, how do I make that json-like string dynamically?

I have an ajax request that returns a list of departments. I want to pass those departments into that editable column.

Change website when redirecting from another page

I have a main page that redirects to another page called example.com

the code of the main page is:

 <! DOCTYPE html>
 <html>
 <body>

 <h2> Redirect to a Webpage </h2>
 <p> The replace () method replaces the current document with a new one: </p>

 <button onclick = "myFunction ()"> Replace document </button>

 <script>
 function myFunction () {
   location.replace ("https://www.example.com")
 }
 </script>

 </body>
 </html>

example.com shows “Original Webpage” if you enter directly
the code for example.com is:

 <! DOCTYPE html>
 <html>
 <body>

 <h2> Original Webpage </h2>
 </body>
 </html>

I want that when redirecting from the main page to example.com, example.com shows “modified page”.
then you should change <h2> Original Webpage </h2> from main page before entering example.com

React and Laravel with Sanctum authentication setup can’t read cookie?

I currently have a React Application spawned via CRA running on http://paulsamazinglocalhost.com:3000

package json as follows:

"start": "HOST=paulsamazinglocalhost.com PORT=3000 react-scripts start",

I’m currently (trying) to talk to a Laravel API running on port 8000 specifically

http://api.paulsamazinglocalhost.com:8000

spawned via laravel as follows:

php artisan serve --port 8000 --host api.paulsamazinglocalhost.com

Now, “what does the Laravel CORS configuration look like” well here it is in all its glory:

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

and “what about the sanctum configuration in your environment file?” here you go:

SESSION_DRIVER=cookie
SESSION_DOMAIN=.paulsamazinglocalhost.com:8000
SANCTUM_STATEFUL_DOMAINS=paulsamazinglocalhost.com:3000

What about the API Kernel:

 'api' => [
            FruitcakeCorsHandleCors::class,
            LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

So to clarify, the api runs on http://api.paulsamazinglocalhost.com (Laravel)
and the React app on http://paulsamazinglocalhost.com

To get the party started, and to try and actually authenticated against my POS API – I hit this first (via FETCH – not AXIOS) – I’m using React Toolkit Query, so here is the request:

GET: http://api.paulsamazinglocalhost.com:8000/api/sanctum/csrf-cookie

my next request is:

Route::post('/auth/login', 'AppHttpControllersApiAuthController@login');

This currently returns a 419 expired message. We sounds to me like we haven’t set something on the request, you know like some beautiful XSRF cookie token or something.

See here: https://laravel.com/docs/8.x/sanctum#spa-authenticating

The documentation states:

This token should then be passed in an X-XSRF-TOKEN header on subsequent requests.

well, yes that’s great, my problem appears to be reading it, becomes the response is completely empty, and I therefore assume that I need to read a cookie, see my lump of react toolkit query code below.

Currently I can’t read any cookies to add them to any subsequent request. Presumably because of some cross domain cookie problem? Not sure.

var getCookies = function(){
  var pairs = document.cookie.split(";");
  console.log(document.cookie)
  var cookies = {};
  for (var i=0; i<pairs.length; i++){
    var pair = pairs[i].split("=");
    cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
    console.log(pair);

  }
  return cookies;
}


// Define a service using a base URL and expected endpoints
export const authApi = createApi({
  reducerPath: 'authApi',
  baseQuery: fetchBaseQuery({ 
    baseUrl: Endpoint.URL + 'auth',
    prepareHeaders: (headers, { getState }) => {
      // By default, if we have a token in the store, let's use that for authenticated requests
      var myCookies = getCookies();
      const cookieToken = Cookies.get('XSRF-TOKEN');
      const token = cookieToken || (getState() as RootState).authApi.token;
      if (token) {
        alert(cookieToken);
        headers.set('X-XSRF-TOKEN', `${token || cookieToken}`)
      }
      return headers;
    },
 }),

Long story short. Can’t read cookies from a sanctum pre auth request, not sure why, any detail on how to authenticate using Sanctum and React Toolkit Query appreciated.

Cannot Install Appcelerator CLI or SDK

I am trying to install Appcelerator CLI and SDK, but I get errors all the time. I´m using Windows.
When I do npm install appcelerator -g, in cmd, (run as admin) I get:

npm WARN deprecated [email protected]: this library is no longer supported
npm WARN deprecated [email protected]: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142

changed 122 packages, and audited 123 packages in 9s

4 packages are looking for funding
run `npm fund` for details

2 high severity vulnerabilities

To address all issues (including breaking changes), run:
npm audit fix --force

Run `npm audit` for details.

And, when I run appc, in cmd (run as admin) I get program.allowUnknownOption is not a function.

When I install the extension in VSCode, as detailed on VSCode official marketplace and Titanium WebSite, and the click “Install Tooling”, this Titanium SDK Titanium Updates: Installing Titanium SDK: 10.1.1.GA (1/1) simply doesn´t install.

Please, someone help me install the CLI and the Titanium SDK. (I know I have to use it in VSCode).