How to wrap an input file in a form using javascript?

I have a function:-

function resetInputFile(elem) {
    elem.wrap('<form>').closest('form').get(0).reset();
    elem.unwrap();
}

I call the function like this:-

resetInputFile(document.queryElement('#image'));

How can I convert the LOCs

elem.wrap('<form>').closest('form').get(0).reset();
elem.unwrap();

into pure javascript?

I want to implement the logic in ReactJS, but I don’t want to use jquery with ReactJS. So I need to do it with pure javascript.

how to properly replace hyphen with div elements in javascript

I have the following text stackoverflow-is-the-best-site-in-the-world by hyphen. I need to replace those hyphen and surround each text within div tags as per result sample below

<div class='cssx'>stackoverflow</div>
<div class='cssx'>is</div>
<div class='cssx'>the</div>
<div class='cssx'>best</div>
<div class='cssx'>in</div>
<div class='cssx'>the</div>
<div class='cssx'>world</div>

In PHP I can get it working as follow.

<?php
$str ="stackoverflow-is-the-best-site-in-the-world";
echo $output = str_replace('-', "<div class='cssx'></div>", $str);

?>

Here is my issue. I need to get it working with javascript. To this effect, I have leveraged solution here
source

but cannot get it to work.

here is the code so far.

const str ="stackoverflow-is-the-best-site-in-the-world";

var output = "<div class='cssx'>" + 
"text.replace(/-/g, "</div><div class='cssx'>", str)" +
 "</div>";

alert(output);

I am getting an error in dispatch sign up using CreateAsyncThunk, I could not dispatch it

enter image description here

I am working on integrating Redux into my project, specifically focusing on user authentication. Below is the code snippet for my authUserSlice. I am encountering an issue when trying to dispatch the signup action in a NextJS Component. Despite handling the promise with a try-catch block, I am facing difficulties.

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import authService from './authService';

interface Form {
  fullname: string;
  username: string;
  password: string;
  dateofbirth: string;
  status: string;
}

interface AuthState {
  user: Form | null;
  isError: boolean;
  isSuccess: boolean;
  isLoading: boolean;
  message: string;
}

const initialState: AuthState = {
  user: null,
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: '',
};

// Register user
export const signup = createAsyncThunk(
  'user/register',
  async (user: Form, thunkAPI) => {
    try {
      const response = await authService.signup(user);
      return response.data; 
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  }
);

export const authSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    resetAuthUser: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = '';
      state.user = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(signup.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(signup.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.user = action.payload;
      })
      .addCase(signup.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload as string;
        state.user = null;
      });
  },
});

export const { resetAuthUser } = authSlice.actions;
export default authSlice.reducer;

//This is my sample sign up form, i filled out the formData with sample data.

import React, { useState } from 'react';
import type { RootState } from '@/lib/store';
import { unwrapResult } from '@reduxjs/toolkit';
import { useSelector, useDispatch } from 'react-redux';
import { signup, resetAuthUser } from '@/lib/features/authUserSlice'; // Import reset action

interface Form {
  fullname: string,
  username: string;
  password: string;
  dateofbirth: string;
  status: string;
}

const SignUp = () => {
  const [formData, setFormData] = useState<Form>({
    fullname: 'Dummy Name',
    username: 'Dummy122',
    password: 'Dummy1234',
    dateofbirth: '',
    status: ''
  });

  const { username, password } = formData;
  const count = useSelector((state: RootState) => state.counter.value);
  const dispatch = useDispatch();

  const onSubmit = async () => {
  

    dispatch(signup(formData))

  };

I tried changing the type, i thought it would resolve the problem and still getting the same error.

Stored Procedure [closed]

Can you please help me to identify the back up tables,views in the database and write a procedure to keep latest 3 backup tables in the database and rest of the backup should be drop/delete.

Thanks & Regards,
Uday

I need to solution for this

I want to Access Meta Quest 3 ‘s Storage Anywhere

I want to Access Meta Quest 3 ‘s Storage Anywhere..

I’ve tried below methods, but still I can’t recall my .obj file

1.
**private string GetExternalStoragePath()**
    {
AndroidJavaClass environment = new AndroidJavaClass("android.os.Environment");
AndroidJavaObject picturesDirectory = environment.CallStatic<AndroidJavaObject>("getExternalStoragePublicDirectory", "Pictures");
return picturesDirectory.Call<string>("toString");
}
filePath = GetExternalStoragePath();

2.
filePath = "/sdcard/Pictures";

3.
filePath = Application.persistentDataPath;



Loading(filePath, fileName_TargetTool);

I’ve also add code to xml file below

  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />    <!--add permission to Access Pictures folder-->
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
  <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />

And I got runtime Permission Also

Is there any route to solve this problem…?
It works on Quset Pro but not works on Quset 3

But Every above path invoked

UnauthorizedAccessException: “filepath/ target.obj” Access to the path is denied.

Troubleshooting 403 Forbidden Error when Uploading PDFs via AJAX in a Spring Boot Application

I am facing an issue with uploading PDFs via AJAX in my Spring Boot application. Most PDFs are successfully uploaded, but for 1-2 specific PDFs, I encounter a 403 Forbidden error with the message POST https://develop.abc.in/parseResume 403 (Forbidden). The PDFs seem fine to me, and I’m struggling to identify the root cause of the problem. I have included the relevant code snippet for reference. Any insights or suggestions on what might be causing this issue would be greatly appreciated.

        // ajax call for Individual add  candidate resume /
        function submitIndividualSharedFileInviteCandidate() {
            var data = new FormData();
            var files = $('#individual')[0].files
            data.append('file',files[0]);
            if (!validateIndividualResumeUpload()) {
                return false;
            }else{     
                if(dummyData == "DummyData"){
                    currentactivity_dummyData = "btn_shareEmployee_uploadIndResume";
                    deleteDummyData();
                    removeDummyData="removeDummyData";
                    }
              }     


            // var data = new FormData(formdata);
            var csrf = $("input[name='_csrf']").attr("value")

            $.ajax({
                headers : {
                    "X-CSRF-TOKEN" : csrf
                },
                enctype : 'multipart/form-data',
                processData : false, // Important!
                contentType : false,
                cache : false, //this is my servlet
                crossDomain: true, // Set this option
                data : data,
                type : "POST",
                url : "./parseResume",

                success : function(result) {
                    if (result.status == "Done") {
                        current_employee_id = result.data.employeeId;
                        $('#myModal').modal('hide');
                        // $('#candidatesBlock1').empty();

                        
                    }
                    $(".tab-slider--navresumedetails li:nth-child(2)").trigger('click')
                    $(".tab-slider--navresumedetails li:nth-child(1)").css('pointer-events', 'none');
                    // $(".add_candidate_form_parent").css('height', '698px');
                    $(".add_candidate_form_parent").css('overflow', 'auto');
                    
                    getSupplierEmail()
                    
                    var obj = result.data;
                    unparsed_resumes_list = obj;
                    current_employee_id = obj.employeeId;
                    $('#userId_unparesedResume').val(obj.employeeId);
                    unparsedBulkSharedResumePreview(obj);
                    $('#btn_save_unparsedSharedBulkResumes').html('Save');

                    
                    if (result.status == "error") {
                        $('#myModal').modal('hide');
                        
                    }
                },
                error : function(result) {
                    console.log(result);
                }
            });
            }

pdf image

Sending data from AJAX to php script via button click

So cut things short im trying to create a pop up update panel on my to-do website using an html button. Now I already have a login-register system and it displays different tables for each user via queries with mysql.

Now these update buttons contain ‘TaskId’ values created when the task are generated via queries and these id will be used to query data to display on the pop-up panel. I wanted to use AJAX to pass that data, that when you click on the button, it pops up the panel then after it sends the value(which is the taskID) to the php script ‘dashboard.php’. However, the php script cant seem to recceive it.

So to diagnose it, I logged the value on the javascript file, and it was able to display the value of the TaskId. I checked the network in the dev tools and it was sending. I checked the names and syntaxes. However it still didnt work. NOTE: the files are on the same folder.

Heres the code for Task generation in the tables (dashboard.php)

                <?php
                    //CHECKS IF USER HAS ANY ONGOING TASK, 
                    $todoQuery = "SELECT * FROM todo_tbl where user_id = '$userID'";
                    $toDo = mysqli_query($conn, $todoQuery);
                    if (mysqli_num_rows($toDo) > 0) {
                        while ($row = mysqli_fetch_assoc($toDo)) {
                            // Gets each row 
                            $taskId = $row['task_id'];
                            $taskName = $row['task_name'];
                            $taskDate= $row['due_date'];
                            $taskStatus = $row['task_status'];

                            echo "<tr>";
                            echo   "<td> $taskName</td>";
                            echo   "<td> $taskDate </td>";
                            echo   "<td> $taskStatus </td>";
                            echo  "<td><button class='updateBtn' value='$taskId'>Update</button></td>";
                            echo  "<td><button class='deleteBtn' value='$taskId'>Delete</button></td>";
                            echo "</tr>";
                        }
                    }
                
                ?>

Javascript Code(dashboard.js):

//using JQUERY

$(document).ready(function() {

  //Reveal Update Panel and AJAX request
      $('.updateBtn').click(function() {
        var updTaskId = $(this).val();
        console.log(updTaskId);
        $.ajax({
            url: 'http://localhost/try/to_do_Website/dashboard.php',
            method: 'POST',
            data: { updTaskId: updTaskId },
            success: function(response) {
                // Handle the response and perform any necessary actions
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error:', error);
            }
        });
});

and finally heres the code in the same file that supposed to receive the data(dashboard.php):

             <!--retrieves task id from ajax request above and displays it on the input boxes-->
                    <?PHP
                        if (isset($_POST['updTaskId'])) {
                          $updTaskId= $_POST['updTaskId'];
                          echo $updTaskId;
                          $viewQuery = "SELECT * FROM todo_tbl where task_id = '$updTaskId'";
                          $view = mysqli_query($conn, $viewQuery);
                                $row = mysqli_fetch_assoc($view);
                                $updtaskName = $row['task_name'];
                                $updtaskDate = $row['due_date'];
                                $updtaskStatus = $row['task_status'];
                                var_dump($row);
                        }
                     ?>

How to avoid duplicate code in JavaScript

I am using jQuery to handle something. It relates to many class or id having a prefix ‘receive’ in its name. Now I want to duplicate those function, but with the prefix ‘send’. It looks like this

function onSelectAddress() {
    $('#receive-address').on('click', function() {
        $('#receive-dropdown').show();
        $('#receive-address').addClass('box-click');
    });
    $('#send-address').on('click', function() {
        $('#send-dropdown').show();
        $('#send-address').addClass('box-click');
    });
}

I don’t want to copy paste and change ‘receive’ to ‘send’ line by line. Is there an way to handle this problem.

Thank you all.

Getting latitude and logitude of a user based on location

<script type="text/javascript">



        function getLocation() {
            debugger
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
            } else {
                alert("Geolocation is not supported by this browser.");
            }
        }

        function showPosition(position) {
            debugger
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;

            // Send the location data to the server using AJAX
            $.ajax({
                type: "POST",
                url: "Login.aspx/SaveLocation",
                data: JSON.stringify({ latitude: latitude, longitude: longitude }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    console.log("Location saved successfully:", response);
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.error("Error saving location:", textStatus, errorThrown);
                    console.log("Response Text:", xhr.responseText);
                }
            });


        }

    </script>


<script>
 getLocation();
</script>
public static  string Latitude;
       public static  string Longitude;


[WebMethod]
       public static void SaveLocation(string latitude, string longitude)
       {
           Latitude = latitude;
           Longitude = longitude;
       }

This is my ajax script for getting user latitude and logitude based on location it is working properly in my localhost but in my beta application unable to get the values pls help me to fix it any other suggestion pls thanks in advance

im calling it by webmethod

Access specific key values on each array using javascript

I like to access/extract specific key values of “serviceCode” the array, how could i do that.

    var x = {


    "0": "{"carrierCode":"ups","serviceCode":"ups_ground","packageTypeCode":"ups_custom_package","currency":"USD","totalAmount":"28.66","baseAmount":"20.19","surcharges":[{"description":"Fuel Surcharge Ground","amount":"3.28"},{"description":"Residential Ground","amount":"2.01"},{"description":"Delivery Confirmation Signature","amount":"3.18"}],"zone":"8","quotedWeight":"25","quotedWeightType":"Actual"}",
        "1": "{"carrierCode":"ups","serviceCode":"ups_second_day_air","packageTypeCode":"ups_custom_package","currency":"USD","totalAmount":"69.72","baseAmount":"54.94","surcharges":[{"description":"Fuel Surcharge - Domestic Air","amount":"9.55"},{"description":"Residential Express","amount":"2.05"},{"description":"Delivery Confirmation Signature","amount":"3.18"}],"zone":"208","quotedWeight":"25","quotedWeightType":"Actual"}",
        "2": "{"carrierCode":"ups","serviceCode":"ups_next_day_air","packageTypeCode":"ups_custom_package","currency":"USD","totalAmount":"76.62","baseAmount":"60.85","surcharges":[{"description":"Fuel Surcharge - Domestic Air","amount":"10.54"},{"description":"Residential Express","amount":"2.05"},{"description":"Delivery Confirmation Signature","amount":"3.18"}],"zone":"108","quotedWeight":"25","quotedWeightType":"Actual"}"
    };

const me = Object.create(x);

var arr = [];
$.each( me, function( index, value){
    arr.push(value);
    
});

console.log(arr.carrierCode);

It always return undefined

Unable to access api response on error with Next.js and RTK queries

I have a Next.js app, in which I’m using RTK queries for data fetching. In my app, I am able to access the response data when the request is successful, but when I am sending an error code like 403 with some message in the response data, I am not able to access it.

What I am trying to achieve is to display the error message that is sent by the endpoint in the client.

Am I missing something to configure on the server or client?


const errorLogger =
  ({ dispatch }) =>
  (next) =>
  (action) => {
    console.log('Action', action);
    return next(action);
  };

const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false
    }).concat([Api.middleware, errorLogger])
});

This is how i am sending the request

const usersApi = Api.injectEndpoints({
  endpoints: (build) => ({
    createUser: build.mutation({
      query: (arg) => {
        return { url: paths.registerUser, body: arg, method: API_METHODS.POST };
      },
      forceRefetch: () => true
    }),
  }),
  overrideExisting: true
});

This is what gets logged with RTK queries

{
"type": "api/executeMutation/rejected",
"payload": {
"status": "FETCH_ERROR",
"error": "TypeError: Failed to fetch"
},
"meta": {
"baseQueryMeta": {
"request": {}
},
"RTK_autoBatch": true,
"arg": {
"type": "mutation",
"endpointName": "createUser",
"originalArgs": {
“email”:”[email protected]”
"name": "admin55",
"isActive": true,
"password": "Password@123",
"company_name": "",
"organization_id": 1,
"address": "",
"bank_account": "",
"type": "admin",
"role_id": 2
},
"track": true
},
"requestId": "KMeIQgnpwBiGKg-89OEXk",
"rejectedWithValue": true,
"requestStatus": "rejected",
"aborted": false,
"condition": false
},
"error": {
"message": "Rejected"
}
}

what actually is sent by the endpoint


{
"status":403,
"data":{
"status":403
"message":"display this error in the client"
}

When I tried the same with Axios, I wasn’t able to access the payload with it either.

{
"message": "Network Error",
"name": "AxiosError",
"stack": "AxiosError: Network Errorn at XMLHttpRequest.handleError (webpack-
internal:///./node_modules/axios/lib/adapters/xhr.js:172:14)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"method": "post",
"url": "https://dev-dispatch.bookmyride.eu:81/api/users/register",

Javascript PopUp when user quit the current page

Good evening everyone !

On the following website https://en.nomorigine.com/, i’m trying to create a popup which appear only when the user quit the current page. I already implemented the code for the popup, but i don’t know how to initiate it with Javascript when the user leave the page.

Thank you in advance for your help.

Here is my code, and i tried with the unload function from jQuery. But no success. Another method ?

<script>
(function(){
var expireKey = 'newsletter';      // Name of the localStorage timestamp.
var popupId   = '#get-newsletter'; // ID of the popup to display.

function maybeShowPopup() {

    // Check, if the popup was displayed already today.
    if ( window.localStorage ) {
        var nextPopup = localStorage.getItem( expireKey );

        if (nextPopup > new Date()) {
            return;
        }

        var expires = new Date();
        expires = expires.setHours(expires.getHours() + 24);
        localStorage.setItem( expireKey, expires );
    }
        
    DiviPopup.openPopup( popupId );
}

// Attach the scroll listener to the window.
jQuery(window).on('unload', maybeShowPopup );
})()
</script>

How to use Forge library and pfx file to sign plain text?

    const pkcs12 = forge.pkcs12;
    const pkcs12Der = arrayBufferToString(pfxData)
    const p12Asn1 = forge.asn1.fromDer(pkcs12Der);
    const p12 = pkcs12.pkcs12FromAsn1(p12Asn1, password);
    const certBags = p12.getBags({ bagType: forge.pki.oids.certBag });
    const cert = certBags[forge.pki.oids.certBag][0].cert;
    const keyBags = p12.getBags({ bagType: forge.pki.oids.pkcs8ShroudedKeyBag });
    const key = keyBags[forge.pki.oids.pkcs8ShroudedKeyBag][0].key;

    const signer = forge.pki.createSigner({
       md: forge.md.sha256.create(),
       rsaOptions: {
       key: forge.pki.privateKeyToPem(key),
     },
    });
    
    signer.certificates = [cert];
    
    signer.update(text);
    const signature = signer.sign();
    
    console.log(signature);

enter image description here

‘pfxData’ is the binary data of the pfx file.
‘password’ is password of the pfx file.
‘text’ is the text to be signed.
Which method should be used for signing?