Safaricom M-Pesa Mini-Apps [closed]

My question is rather addressed to Kenyan developers or anyone who has ever developed a mini-app. So safaricom enforces a structure and you are expected to manipulate DOM on axml using javascript. styling also uses ascss. I have only used xml on building android UI and I honestly have no Idea how to go about it.

Who has ever done anything close to that to help me understand how axml works with javascript? please drop any documentations, references or even github code to enhance my undestanding.

Adding array to json and post ajax cart

I’ve basically got an ajax call where I’m adding multiple products to cart via one event.

The products are added to an array like this

let crossSellSelected = false
    const crossSellElements = productFormContainer?.querySelectorAll('.crossSell__Item.selected');
    let crossSell
    let crossSellArray = new Array();

    if (crossSellElements) {
      crossSellSelected = true
      crossSellElements.forEach(crossSellElement => {
          const selectedCrossSell = crossSellElement.querySelector('.crossSell__Swatch.selected .crossSell__Radio').value
              crossSell = {
                  id: selectedCrossSell,
                  quantity: 1
                  
           }
           crossSellArray.push(crossSell)
      })
  }

They are then converted to json and added in an ajax call like this

const response = await fetch(
      `${window.themeVariables.routes.cartAddUrl}.js?sections=mini-cart`,
      {
        body: JSON.stringify({
          items: crossSellSelected
            ? [crossSellArray, product]
            : [product],
          attributes: {
            _ttp: getCookie("_ttp"),
            ttclid: getCookie("ttclid"),
          },
        }),
        method: "POST",
        headers: {
          "X-Requested-With": "XMLHttpRequest",
          "Content-Type": "application/json",
        },
      },
    );

But the post method fails in this case. However if I change it to

const response = await fetch(
          `${window.themeVariables.routes.cartAddUrl}.js?sections=mini-cart`,
          {
            body: JSON.stringify({
              items: crossSellSelected
                ? [crossSellArray[0], product]
                : [product],
              attributes: {
                _ttp: getCookie("_ttp"),
                ttclid: getCookie("ttclid"),
              },
            }),
            method: "POST",
            headers: {
              "X-Requested-With": "XMLHttpRequest",
              "Content-Type": "application/json",
            },
          },
        );

it works. So it looks to me the issue is that it is an array but I’m not really sure why that is an issue and how to fix it. Any help would be greatly appreciated

How can I create nested dynamic form elements?

I want the select-option and input-text fields to be added once when I click on the Add button.

I’ve already achieved this. That’s okay.

When I click on the Add Serv button, the input-text field in the relevant line needs to be added.

Now, every time I click, it assigns a field to each line. Once I click, there are 2 “Services” fields per row. When I click twice, there are 3 “Services” fields in each line.

When I click on the Remove Serv button, it deletes one row from each row, showing a similar behavior. How can I ensure that these operations occur for the relevant row?

add serv and remove serv are not working properly.

keyValueFA = new FormArray([this.newKeyValueFG]);
  keyServFA = new FormArray([this.newServFG]);

  propertyFG = new FormGroup({
    keyValue: this.keyValueFA,
    //serv:this.keyServFA
  });


  get newKeyValueFG(): FormGroup {
    return new FormGroup({
      prof: new FormControl(null),
      //serv: new FormControl(null),
    });
  }

  get newServFG(): FormGroup {
    return new FormGroup({
      serv: new FormControl(null),
    });
  }



  get keyValueArrayFGControls(): FormGroup[] {
    return this.keyValueFA.controls as FormGroup[];
  }
  get keyValueArrayFGControlss(): FormGroup[] {
    return this.keyServFA.controls as FormGroup[];
  }
  addNewKeyValueFG(): void {
    this.keyValueFA.push(this.newKeyValueFG);
  }


  addNewServFG(): void {
    this.keyServFA.push(this.newServFG);
  }

  removeNewKeyValueFG(index: number): void {
    this.keyValueFA.removeAt(index);
  }
  removeNewServFG(index: number): void {
    this.keyServFA.removeAt(index);
  }
<form [formGroup]="propertyFG">
                <div formArrayName="keyValue" *ngFor="let fg of keyValueArrayFGControls; let i = index">
                  <div [formGroup]="fg">
             
                      <div class="col-4">


                        <select formControlName="prof" width="100%" class="form-control">
        
                          <option *ngFor="let l of professions;" [value]="l._id">
                            {{getProfessionNameByLang(l.name)}}
                          </option>
                        </select>
        
        
                      </div>



                      <div *ngFor="let sr of keyValueArrayFGControlss; let j = index" class="col-4">
                      <div [formGroup]="sr">
                       
                        <input type="text" formControlName="serv" [id]="'myDiv-' + i+ j" placeholder="Hizmet" />

                        <button (click)="removeNewServFG(j)">Remove Serv</button>


                        </div>



                  
                  </div>
                  <button (click)="removeNewKeyValueFG(i)">Remove</button>
                  <button (click)="addNewServFG()">Add Serv</button>


                </div>


                
             
               </div>




                <button (click)="addNewKeyValueFG()">Add</button>
              </form>

enter image description here

enter image description here

using object containing arrays want to update the quantity of calling array of object product by adding 1

let products = [
{id: 1, price: 100, discount: 0.10},
{id: 2, price: 200, discount: 0.10},

     {id: 3, price: 300, discount: 0.10},
     {id: 4, price: 400, discount: 0.10},
     {id: 5, price: 500, discount: 0.05},
    ];
    let cart = [];
    function addToCart(cart, product) {
        let total = 0
        let qty = 0
        // qty = cart.qty
        //  qty = product.qty
         product.qty = ++qty
         product.total = product.price-(product.price*product.discount) + total
        return product
        }
    
        let product = products[3];
        cart = addToCart(cart, product);
         console.log(cart);

I want to update the value of quantity by 1 every time it call and update price too according to the quantity
but this each time it call just value of quantity is 1your text/*`

JQuery XDSoft datetimepicker plugin keyboard accebility issue (I am not able to select date with keyboard)

I am using this plugin https://xdsoft.net/jqplugins/datetimepicker/

I can select date and time with mouse but my requirement is that select date and time with keyboard(key like tab, arrow).

Please solve the issue.

jQuery(document).ready(function () {
‘use strict’;

$(document).ready(function() {
$(‘#filter-date’).datetimepicker();

$(‘#filter-date’).keydown(function(e) {
const input = $(this);
const currentValue = input.val();
const newDate = new Date(currentValue);

if (e.keyCode === 37) { // Left Arrow
newDate.setDate(newDate.getDate() – 1);
} else if (e.keyCode === 39) { // Right Arrow
newDate.setDate(newDate.getDate() + 1);
}

// Update the input field with the new date value
input.val(newDate.toISOString());
});
});

});

What are the best ways that we can made maximum SEO friendly web app in React JS [closed]

What are the most effective strategies and techniques to develop a web application in React JS that is highly optimized for search engine visibility, also known as SEO?

Creating a web application that is SEO-friendly in React JS involves a comprehensive set of practices aimed at making the app’s content easily discoverable, understandable, and appealing to search engines like Google, Bing, and others. SEO is vital for driving organic traffic and ensuring that your web app reaches its intended audience. To achieve maximum SEO-friendliness?

Can anyone describe best alternative solution/options

i am trying send email using emailjs in my firebase cloud function but email is not getting send

code is compiled successfully and not getting any runtime error but email is not getting send , please guide me if this email service in not for server side then which one i should use ..?


const functions =require("firebase-functions")
const admin = require("firebase-admin");
const cron = require('node-cron');
const emailjs =require("@emailjs/browser")
require("dotenv").config();

admin.initializeApp();

exports.printUser=functions.https.onRequest(async(req,res)=>{
    try {
        // Fetch the list of users from Firebase, assuming you have a 'users' collection
        const usersSnapshot = await admin.firestore().collection('vendors').get();
        const tempArray=[];
       usersSnapshot.docs.forEach((doc)=>
       {
           if(doc.data().lastPromoAdded)
           {
            tempArray.push(doc.data().email)
           }
       })
        // Loop through each user and send an email
        usersSnapshot.forEach((userDoc) => {
          const userData = userDoc.data();
          const userEmail = userData.email;
          if(userData.lastPromoAdded!==undefined){}
  
          
        });
        emailjs
        .send(
          process.env.EMAIL_JS_MY_EMAIL_S_ID,
          process.env.EMAIL_JS_MY_EMAIL_T_ID,
          {
            user_name: "iftekhar",
            message: "hello user by iftekhar",
            user_email: "[email protected]",
          },
          process.env.EMAIL_JS_MY_EMAIL_PB_KEY
        )
        .then(
          (result) => {
            return res.send(result.text)
          },
          (error) => {
              return res.send(error.text)
          }
        );

        return res.json({data:tempArray});
      } catch (error) {
        console.error('Error sending emails:', error);
        return null;
      }
})

here is my code
not receiving email, neither receiving nor getting any error

Javascript Unexpected identifier Function on array element after running same script again

I have a simple script that finds every link on page and changes href and onclick properties. For some reason I need to run this script every 5 seconds.

function changeLinks() {
        let links = document.getElementsByTagName("a");

        for (let i = 0; i < links.length; i++) {
            links[i].href = links[i].href.replace("/current", "/target");

            if (links[i].onclick != null) {
                let linkOnClickFunction = links[i].onclick.toString();
                linkOnClickFunction = linkOnClickFunction.slice(linkOnClickFunction.indexOf("{") + 1, linkOnClickFunction.lastIndexOf("}"));
                linkOnClickFunction = linkOnClickFunction.replace("/current", "/target");

                links[i].setAttribute("onclick", linkOnClickFunction);
            }
        }
}
setInterval(changeLinks, 5000);

The script works fine the first time. However on second execution I get error Unexpected identifier 'Function' at links[i].onclick

How does the ‘createApplication()’ function work in ExpressJS source code?

I am trying to understand line by line how the Express library works. So what I understand is when we import and call ‘express()’ function in our codebase, execution control would go to the ExpressJS liberary and look for the default export (in its Index.js).

Index.js

/*!
 * express
 * Copyright(c) 2009-2013 TJ Holowaychuk
 * Copyright(c) 2013 Roman Shtylman
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict';

module.exports = require('./lib/express');

Here, the execution control would go to ‘./lib/express’ and look for its default export.

./lib/express.js

/*!
 * express
 * Copyright(c) 2009-2013 TJ Holowaychuk
 * Copyright(c) 2013 Roman Shtylman
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict';

/**
 * Module dependencies.
 */

var bodyParser = require('body-parser')
var EventEmitter = require('events').EventEmitter;
var mixin = require('merge-descriptors');
var proto = require('./application');
var Route = require('./router/route');
var Router = require('./router');
var req = require('./request');
var res = require('./response');

/**
 * Expose `createApplication()`.
 */

exports = module.exports = createApplication;

/**
 * Create an express application.
 *
 * @return {Function}
 * @api public
 */

function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };

  mixin(app, EventEmitter.prototype, false);
  mixin(app, proto, false);

  // expose the prototype that will get set on requests
  app.request = Object.create(req, {
    app: { configurable: true, enumerable: true, writable: true, value: app }
  })

  // expose the prototype that will get set on responses
  app.response = Object.create(res, {
    app: { configurable: true, enumerable: true, writable: true, value: app }
  })

  app.init();
  return app;
}

/**
 * Expose the prototypes.
 */

exports.application = proto;
exports.request = req;
exports.response = res;

/**
 * Expose constructors.
 */

exports.Route = Route;
exports.Router = Router;

/**
 * Expose middleware
 */

exports.json = bodyParser.json
exports.query = require('./middleware/query');
exports.raw = bodyParser.raw
exports.static = require('serve-static');
exports.text = bodyParser.text
exports.urlencoded = bodyParser.urlencoded

/**
 * Replace removed middleware with an appropriate error message.
 */

var removedMiddlewares = [
  'bodyParser',
  'compress',
  'cookieSession',
  'session',
  'logger',
  'cookieParser',
  'favicon',
  'responseTime',
  'errorHandler',
  'timeout',
  'methodOverride',
  'vhost',
  'csrf',
  'directory',
  'limit',
  'multipart',
  'staticCache'
]

removedMiddlewares.forEach(function (name) {
  Object.defineProperty(exports, name, {
    get: function () {
      throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.');
    },
    configurable: true
  });
});

The default export here seems to be ‘createApplication()’ factory function.

var app = function(req, res, next) {
    app.handle(req, res, next);
  };

But what I do not understand is how we are calling the ‘app.handle()’ method when we have just freshly declared ‘app’ a line above. It should have no properties/methods right? How does it then work?

I tried to debug it line by line using VS Code, but it just skips all the breakpoints I put in the library.

PHP Yii2 REST POST / Missing required parameters

Thank you very much for your help.

I am using Yii2. I want to use a REST POST request to send a list of words to the server, the server will translate the words and send back their translation.

When I send the POST request, I get this message in the browser JavaScript console:
name “Bad Request”
message “Missing required parameters: words”
code 0
status 400
type “yiiwebBadRequestHttpException”

I noticed that $_POST is empty “array(0)”.
I am running PHP using this command: php yii serve.

This is the view:

<?php

use yiihelpersHtml;
use yiiwidgetsDetailView;
use yiiwidgetsActiveForm;
use appassetsTranslationAsset;

/** @var yiiwebView $this */
/** @var appmodelsBook $book */
/** @var appmodelsBookSection $section */

$this->title = $section->title;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Section'), 'url' => ['book']];
$this->params['breadcrumbs'][] = $this->title;
yiiwebYiiAsset::register($this);
?>
<div class="translate-section">

    <h1><?= Html::encode($this->title) ?></h1>

    <?= DetailView::widget([
        'model' => $book,
        'attributes' => [
            'id',
            'name',
        ],
    ]) ?>
    <?= DetailView::widget([
        'model' => $section,
        'attributes' => [
            'title',
        ],
    ]) ?>
    <div>
        <?php $form = ActiveForm::begin(); ?>
        <table>
            <tr>
                <td><textarea id="words"></textarea></td>
                <td><textarea id="first-translation"></textarea></td>
                <td><textarea id="second-translation"></textarea></td>
            </tr>
        </table>
        <button id="translate" type="button">Translate</button>

        <div class="form-group">
            <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
        </div>

        <?php ActiveForm::end(); ?>

    </div>
    <?php TranslationAsset::register($this) ?>
</div>

JavaScript

window.onload = (event) => {
    document.querySelector("#translate").addEventListener("click", translate)
}

function translate() {
    const textarea = document.getElementById("words");
    const words = textarea.value.replace(/rn/g, "n").split("n");
    post('http://localhost:8080/index.php/rest-translation/translate', words)
}


async function request(url, params = {}, method = 'GET') {
    let vsUrl = url
    let options = {
        method
    }

    //options.headers = { 'Content-type': 'application/json; charset=UTF-8' }
    if (method === 'GET') {
        vsUrl += '?' + (new URLSearchParams(params)).toString()
    } else {
        options.body = JSON.stringify(params)
    }

    //return fetch(vsUrl, options).then(response => response.json())
    const response = await fetch(vsUrl, options)
    if (response.ok) {
        response.json()
    }
}

const get = (url, params) => request(url, params, 'GET')
const post = (url, params) => request(url, params, 'POST')

This is the REST controller:

<?php

namespace appcontrollers;

use appmodelsTranslation;
use yiirestActiveController;

class RestTranslationController extends ActiveController
{
    public $modelClass = 'appmodelsTranslation';

    public function actionTranslate($words)
    {
        return  Translation::translate($words);
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        // remove authentication filter
        $auth = $behaviors['authenticator'];
        unset($behaviors['authenticator']);

        // add CORS filter
        $behaviors['corsFilter'] = [
            'class' => yiifiltersCors::class,
        ];

        // re-add authentication filter
        $behaviors['authenticator'] = $auth;
        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }
}

This is the model:

<?php

namespace appmodels;

use Yii;

/**
 * This is the model class for table "translation".
 *
 * @property int $id
 * @property int $sourceEntryId
 * @property string $languageId
 * @property string $typeId
 * @property int $translationEntryId
 */
class Translation extends yiidbActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'translation';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['sourceEntryId', 'languageId', 'typeId', 'translationEntryId'], 'required'],
            [['sourceEntryId', 'translationEntryId'], 'integer'],
            [['languageId', 'typeId'], 'string', 'max' => 10],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'sourceEntryId' => Yii::t('app', 'Source Entry ID'),
            'languageId' => Yii::t('app', 'Language ID'),
            'typeId' => Yii::t('app', 'Type ID'),
            'translationEntryId' => Yii::t('app', 'Translation Entry ID'),
        ];
    }

    public static function translate($words)
    {
        //<TO DO>:Find and return the translation.
    }

    /**
     * {@inheritdoc}
     * @return TranslationQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new TranslationQuery(get_called_class());
    }
}

config/web.php

<?php

$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'xxxxxxxx',
            'parsers' => [
                'application/json' => 'yiiwebJsonParser',
            ]
        ],
        /*'response' => [
            'format' => yiiwebResponse::FORMAT_JSON,
            'charset' => 'UTF-8',
            // ...
        ],*/
        'cache' => [
            'class' => 'yiicachingFileCache',
        ],
        'user' => [
            'identityClass' => 'appmodelsUser',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => yiisymfonymailerMailer::class,
            'viewPath' => '@app/mail',
            // send all mails to a file by default.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yiilogFileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,
        
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => true,
            'enableStrictParsing' => false
        ]
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yiidebugModule',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yiigiiModule',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];
}

return $config;

My environment:
PHP 8.1.2-1ubuntu2.14 (cli) (built: Aug 18 2023 11:41:11) (NTS)
Zend Engine v4.1.2
with Zend OPcache v8.1.2-1ubuntu2.14
with Xdebug v3.2.1
Yii2 (2.0.48.1)

Thank you very much for your help.

I googled for a solution, but I didn’t find a anything.

CSS not applied for the HTML Element

In my web application, I’m trying to add a card to the view using JavaScript to a section.
This is the card I’m using to apply to mine –> https://uiverse.io/JohnnyCSilva/ugly-stingray-77

I made a few changes because when I used the CSS to my view, it mixed with current CSS styles and showed the card a different view. So I added special tag to that css.

$.ajax({
  url: '@Url.Action("getStaffMembers", "Home")',
  type: 'GET',
  dataType: 'json',
  success: function(data) {
    if (data.Success) {
      var staffList = data.StaffList;
      var staffListDiv = $('#staffListDiv');

      for (var i = 0; i < staffList.length; i++) {
        var staffCard = $('<div>').addClass('col-md-3 col-sm-6 mb-4 card special-section card');

        // Add a data attribute to store Staff ID
        staffCard.data('staff-id', staffList[i].ID);

        var imgDiv = $('<div>').addClass('img');
        var textDiv = $('<div>').addClass('textBox');
        var textContent = $('<div>').addClass('textContent');
        var staffName = $('<p>').addClass('h1').text(staffList[i].Staff_Name);

        textContent.append(staffName);
        textDiv.append(textContent);

        staffCard.append(imgDiv, textDiv);
        staffListDiv.append(staffCard);


      }
    } else {
      console.log('Error fetching staff members');
    }
  },
  error: function() {
    console.log('Error fetching staff members');
  }
});
.special-section .card {
  width: 100%;
  max-width: 290px;
  height: 70px;
  background: #353535;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: left;
  backdrop-filter: blur(10px);
  transition: 0.5s ease-in-out;
}

.special-section .card:hover>.img {
  cursor: pointer;
  transform: scale(1.05);
}

.special-section .img {
  width: 50px;
  height: 50px;
  margin-left: 10px;
  border-radius: 10px;
  background: linear-gradient(#d7cfcf, #9198e5);
}

.special-section.card:hover>.img {
  transition: 0.5s ease-in-out;
  background: linear-gradient(#9198e5, #712020);
}

.special-section .textBox {
  width: calc(100% - 90px);
  margin-left: 10px;
  color: white;
  font-family: 'Poppins' sans-serif;
}

.special-section.textContent {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.special-section .span {
  font-size: 10px;
}

.special-section.h1 {
  font-size: 16px;
  font-weight: bold;
}

.special-section .p {
  font-size: 12px;
  font-weight: lighter;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section2" class="section text-center">
  <h2 style="margin-top: 40px;">Select the Staff Member</h2>
  <div class="row justify-content-center" id="staffListDiv" style="margin-top: 200px;">
    <!-- Staff cards will be dynamically generated here -->
  </div>
</div>

The thing is when the dynamically cards are generated into the view, the css not applied. Need to know how to fix this?

Why does async code mess up my dataloader in a graphql resolver?

I have a dataloader that I’m using to batch requests to a service to get my user’s addresses.
The loader doesn’t batch requests correctly when the parent resolver uses async code.
Here’s a general idea of what my code looks like:

// User.ts 
import Demographic from './Demographic'

export type User { 
 name: 'User', 
 description: 'User',
 ...
 fields: () => {
  someField: ...
  demographicInformation: {
     type: Demographic,
     resolve: async (source, args, context) => {
      // removing the following line causes the loader in Demographics.ts to batch properly
      const [hasViewPermissions, hasAuthForDemographics] = await Promise.all([getViewPermissions(), getAuthForDemographics()])
      if (hasAuth && hasAuthForDemographics){ return source}
      else { return null } 
     
     }

 } 

}
...
//Demographics.ts
export type Demographics { 
 name: 'somename', 
 description: '',
 fields: {
    name: // ...
    address: {
     type: Address, 
     resolve:  async (source, args, context) => {
       return myloaders.addressloader.load(myid)
     }

   }
}

I’m aware that the dataloader docs say that “DataLoader will coalesce all individual loads which occur within a single frame of execution (a single tick of the event loop)”, however I don’t fully understand why using an async/await messes that up if that’s done in the parent resolver (User in my case).
And, I need to have the parent check the auth using some form of async code, is there a way to still make these auth calls at the parent level and also use the dataloader effectively?

I’ve seen this issue noted in Github as well, but I don’t think any workaround (such as adding the async calls to the loader) will work for me.

I am trying to send array of objects from front-end javascript to my method in asp.net web forms. Error: https://localhost:44396/Input.aspx/UpdateData

I have three inputs, app name, from date and to date. I add those into a table which creates array of objects. Then try to send this array using ajax to the method in aspx.cs file in web forms. But I get the error.

Javascript Code:

document.addEventListener("DOMContentLoaded", function () { console.log("DOMContentLoaded event fired"); var updateBtnClick = document.getElementById("<%= updateBtn.ClientID %>"); //"ContentPlaceHolder1_updateBtn" if (updateBtnClick) { console.log("Update button element found"); updateBtnClick.addEventListener('click', function (e) { e.preventDefault(); console.log("Update button is clicked"); var jsonData = JSON.stringify(tableData); console.log(jsonData); $.ajax({ url: "Input.aspx/UpdateData", type: "POST", data: jsonData, contentType: "application/json", success: function (response) { console.log("Data sent to the backend successfully"); }, error: function (error) { console.error("Error sending data to the backend: " + JSON.stringify(error)); } }); }); } else { console.log("Update button element not found"); } });

aspx.cs:

[WebMethod] public static string UpdateData(List<Downtime> jsonData) { if (jsonData != null && jsonData.Count > 0) { string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); foreach (var item in jsonData) { string dropdownValue = item.App_name; DateTime fromDate = item.From_date; DateTime toDate = item.To_date; string sqlQuery = "UPDATE DowntimeApplications SET From_date = @FromDate, To_date = @ToDate where App_name = @name"; using (SqlCommand command = new SqlCommand(sqlQuery, conn)) { command.Parameters.AddWithValue("@FromDate", fromDate); command.Parameters.AddWithValue("@ToDate", toDate); command.Parameters.AddWithValue("@name", dropdownValue); command.ExecuteNonQuery(); } } HttpContext.Current.Response.ContentType = "application/json"; var response = new { success = true, message = "Data updated successfully" }; return JsonConvert.SerializeObject(response); } } var noDataResponse = new { success = false, message = "No data to update" }; HttpContext.Current.Response.ContentType = "application/json"; return JsonConvert.SerializeObject(noDataResponse); }

Fuzz Testing / Random Testing a website for any client side javascript errors

Folks,

We are primarily backend folks, and needed some guidance on some website testing to capture some errors.

We have a website (https://www.letsdata.io/) and we are currently updating it (some pages) with next-js generated html, javascript and css.

We’ve not spend any time on writing the next-js recommended tests /use their frameworks, we’ve primarily done manual testing to make sure that the website looks okay on web, tablet and mobile in chrome.

Every once in a while, when we are testing, we see javascript errors on the console.

I wanted to ask if there was any testing framework that I could point to my website that could do random / fuzz / exploratory testing of the website, not so much as to whether the page is rendering correctly, but more around capturing browser javascript errors, traces around network calls (what network calls are being made) etc. to help us find and fix any bugs.

If I were to build this, I was thinking of loading the website in some browser, capture console errors / network traces, then follow links on the page one by one and capture their traces / console errors etc.

I see frameworks for cross browser testing (not what we are looking for), load testing (not testing performance) and these frameworks require you to define a test rather than random fuzz testing.

Is there a simple test framework for fuzz / random / exploratory testing websites? (Is this even the right kind of testing to be running or are we approaching this incorrectly?)

Thanks

error: crypto.createHash is not a function

I’m using crypto for password encryption but when I try to call the function. I’m getting the following error.
Warning of crypto.createHash method
You can find the following code:

import crypto from 'crypto';

export const encrypt = (text: string) => {
    const algorithm = 'aes256';
    const key = createHash('sha256')
        .update(String(reactApp))
        .digest('base64')
        .substr(0, 32);
 // some calculation
    return encrypted;
};

I’ve tried to use crypto-browserify but it’s showing some more errors as you can see below.
crypto-browserify error

When I run the given command as it suggests, it shows me another error which says the repository doesn’t exist. Moreover, it show me this error too.
polyfill

I’ve tried to add this code in the webpack.config.ts file too.

const path = require('path');

module.exports = {
    resolve: {
        fallback: {
            crypto: 'crypto-browserify',
        },
    },
};