When i submit FormData using Json/Ajax it is not going through [closed]

Im trying to add profile photo to my users but when im trying to click submit button it is not going through.

Here is my Json


function getUserFormData(form) {
    return  {
        action: "addUser",
        user: {
            user_id: User : null,
            email: form['email'].value,
            username: form['username'].value,
            password: Util.hash(form['password'].value),
            password_confirmation: Util.hash(form['password_confirmation'].value),
            profile_image: form['profile_image'].value
        }
    };
}

AS.Http.submituser = function (form, data, success, error, complete) {
    AS.Util.removeErrorMessages();

    var $submitBtn = $(form).find("button[type=submit]");
    var $fileupload = $(data).prop('profile_image');
    var formData = new FormData();
    formData.append('file', $fileupload);

    if ($submitBtn) {
        AS.Util.loadingButton($submitBtn, $submitBtn.data('loading-text') || $_lang.working);
    }

    $.ajax({
        url: "/Ajax.php",
        cache: false,
        contentType: false,
        processData: false,
        type: "POST",
        dataType: "json",
        data: data,
        success: function (response) {
            form.reset();

            if (typeof success === "function") {
                success(response);
            }
        },
        error: error || function (errorResponse) {
            AS.Util.showFormErrors(form, errorResponse);
        },
        complete: complete || function () {
            if ($submitBtn) {
                AS.Util.removeLoadingButton($submitBtn);
            }
        }
    });
};

Here is the Back End

    public function add(array $data)
    {
        if ($errors = $this->registrator->validateUser($data, false)) {
            ASResponse::validationError($errors);
        }
        // Handle secure profile image upload
        $files = $data['profile_image'];
        $targetDirectory = "../assets/img/usersprofile/";
        $imageFileType = strtolower(pathinfo($files["profile_image"]["name"], PATHINFO_EXTENSION));

        // Generate a unique image filename: complete_name_uniqueID.extension
        $username = $data['username'];
        $safeName = preg_replace('/[^A-Za-z0-9]/', '_', $username); // Remove special chars
        $uniqueID = uniqid();
        $imageName = "{$safeName}_{$uniqueID}.{$imageFileType}";
        $targetFile = $targetDirectory . $imageName;

        // Validate image file
        $validMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
        $check = getimagesize($files["profile_image"]["tmp_name"]);
        if ($check === false || !in_array($check['mime'], $validMimeTypes)) {
            throw new Exception("Invalid image file format.");
        }

        // Check file size (max 2MB)
        if ($files["profile_image"]["size"] > 2000000) {
            throw new Exception("File size exceeds the 2MB limit.");
        }

        // Restrict executable file uploads
        if (preg_match('/.(php|html|htm|js|exe|sh)$/i', $files["profile_image"]["name"])) {
            throw new Exception("Invalid file type.");
        }

        // Ensure upload directory is safe
        if (!is_dir($targetDirectory) && !mkdir($targetDirectory, 0755, true)) {
            throw new Exception("Failed to create upload directory.");
        }

        // Move uploaded file
        if (!move_uploaded_file($files["profile_image"]["tmp_name"], $targetFile)) {
            throw new Exception("Error uploading the image.");
        }

        $this->db->insert('users', [
            'email' => $data['email'],
            'username' => $data['username'],
            'password' => $this->hashPassword($data['password']),
            'profile_image' => $imageName
        ]);



        Response::success(["message" => trans("user_added_successfully")]);
    }

I tried to append file but unfortunately still nothing happen. i cant see what is error because it is not showing.

Permission of folder it read/writable.

I dont know if the code is right, could you please help me!

How to save Google OAuth user login data to MySQL database [closed]

I am implementing Google OAuth authentication in my PHP application, but the user profile data is not being inserted into my MySQL database. The authentication process works correctly, and I can retrieve the user data from Google, but the insertion into the database fails silently.

// init configuration
$clientID = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET';
$redirectUri = 'http://localhost/shop/home.php';

$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

    if (!isset($token['error'])) {
        $client->setAccessToken($token['access_token']);

        $google_oauth = new Google_Service_Oauth2($client);
        $google_account_info = $google_oauth->userinfo->get();

        $email    = $google_account_info->email;
        $fname    = $google_account_info->givenName;
        $lname    = $google_account_info->familyName;
        $password = password_hash($google_account_info->id, PASSWORD_BCRYPT);

        // check if user exists
        $stmt = $conn->prepare("SELECT id, fname, lname, email FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            // user exists
            $user = $result->fetch_assoc();
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['name']    = $user['fname'] . " " . $user['lname'];
            $_SESSION['email']   = $user['email'];
        } else {
            // insert new user
            $stmt = $conn->prepare("INSERT INTO users (fname, lname, email, mobile, password, status_status_id, gender_id) 
                                    VALUES (?, ?, ?, ?, ?, ?, ?)");
            $mobile = "0712345678"; 
            $status = 4; 
            $gender = 1;
            $stmt->bind_param("ssssssi", $fname, $lname, $email, $mobile, $password, $status, $gender);

            if ($stmt->execute()) {
                $userId = $stmt->insert_id;
                $_SESSION['user_id'] = $userId;
                $_SESSION['name']    = $fname . " " . $lname;
                $_SESSION['email']   = $email;
            } else {
                die("Insert failed: " . $stmt->error);
            }
        }

        header("Location: home.php");
        exit;
    } else {
        die("Error fetching token: " . $token['error']);
    }
}

The OAuth flow completes successfully, and I can see that Google returns the user data correctly. However, when a new user tries to log in, the data is not inserted into the database. The script does not throw any errors, and it redirects to home.php, but the user record is not created.

PhpStorm adding script to my GET responses [closed]

I’m responding to a GET request with JSON data (Content-Type
application/json; charset=utf-8), but it keeps tacking on this random script to every response and I cannot get rid of it no matter what I do:

37 requests
720.83 kB / 707.49 kB transferred
Finish: 602 ms
DOMContentLoaded: 214 ms
load: 476 ms
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 503 of the JSON data

{"expected_data":"values"}<script>
(function() {
  var ws = new WebSocket('ws://' + window.location.host + 
             '/jb-server-page?reloadMode=RELOAD_ON_SAVE&'+
             'referrer=' + encodeURIComponent(window.location.pathname));
  ws.onmessage = function (msg) {
      if (msg.data === 'reload') {
          window.location.reload();
      }
      if (msg.data.startsWith('update-css ')) {
          var messageId = msg.data.substring(11);
          var links = document.getElementsByTagName('link');
          for (var i = 0; i < links.length; i++) {
              var link = links[i];
              if (link.rel !== 'stylesheet') continue;
              var clonedLink = link.cloneNode(true);
              var newHref = link.href.replace(/(&|?)jbUpdateLinksId=d+/, "$1jbUpdateLinksId=" + messageId);
              if (newHref !== link.href) {
                clonedLink.href = newHref;
              }
              else {
                var indexOfQuest = newHref.indexOf('?');
                if (indexOfQuest >= 0) {
                  // to support ?foo#hash 
                  clonedLink.href = newHref.substring(0, indexOfQuest + 1) + 'jbUpdateLinksId=' + messageId + '&' + 
                                    newHref.substring(indexOfQuest + 1);
                }
                else {
                  clonedLink.href += '?' + 'jbUpdateLinksId=' + messageId;
                }
              }
              link.replaceWith(clonedLink);
          }
      }
  };
})();
</script>

Does anyone know where this script is coming from and how I can disable it? I’ve also tried disabling the debugger in both my browser and in PhpStorm.

I’ve searched high and low and I know it has something to do with “live edit”, but I cannot find any options to enable/disable it no matter where I look.

How to embed a link to the home page in a custom WordPress block

I’m developing a custom WordPress block using the block.json + edit.js + save.js pattern (Block API v2).
I’m not using registerBlockType() directly in JS nor the old PHP-only approach, but relying on block.json to register editorScript, viewScript etc.

I need to pass a dynamic homepage url into both my edit and save components, but wp_localize_script doesn’t seem to work with the file-based editorScript entry in block.json.

How can I correctly inject a homepage url into my edit.js/save.js when using the block.json workflow?

Scoping Tailwind CSS Classes Per Section in Modular PHP Projects

I need to implement some kind of class scoping in Tailwind CSS. Each section of my site is in a different .php file (for example, hero.php, about.php, etc.). What I want is for Tailwind to generate separate CSS files for each section – for example, hero.css and about.css. The styles should be scoped using data-css=”hero” and data-css=”about”. So, in hero.php, I would use something like <section data-css=”hero” …>, and it should only apply styles from the hero section. Using tailwind v4 cli.

CSS: [data-css="Hero_test_hero_sekce"]
PHP: <section data-css="Hero_test_hero_sekce" class="relative h-screen bg-cover bg-center bg-no-repeat flex items-center">

Indexnow does not recognise urlList

I am trying to implement Indexnow to one of my sites but when I run it I get the response:

{“code”:”InvalidRequestParameters”,”message”:”Invalid request”,”details”:[{“target”:”request.urlList”,”message”:”The urlList field is required.”}]}

This is my (shortened) code:

$urls = array();
if (date('Y-m-d', filemtime('../index.php')) = date('Y-m-d',now())) {array_push($urls,'https://'.$_SERVER['SERVER_NAME'].'/');}
if (date('Y-m-d', filemtime('../credits.php')) = $date('Y-m-d',now())) {array_push($urls,'https://'.$_SERVER['SERVER_NAME'].'/credits');}

$post = array(
    'host' => $_SERVER['SERVER_NAME'],
    'key' => 'key',
    'keylocation' => 'https://'.$_SERVER['SERVER_NAME'].'/key.txt',
    'urlList' => $urls
);

unset($urls);

$cp = curl_init('https://api.indexnow.org/indexnow');
curl_setopt ($cp, CURLOPT_HTTPHEADER, Array("application/json; charset=utf-8"));
curl_setopt($cp, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cp, CURLOPT_POST, 1);
curl_setopt($cp, CURLOPT_POSTFIELDS, json_encode($post, JSON_UNESCAPED_UNICODE));

// execute!
$cp_response = curl_exec($cp);

When I do “echo json_encode($post);” I get:

{"host":"www.host.dk","key":"key","keylocation":"https://www.host.dk/key.txt","urlList":["https://www.host.dk/","https://www.host.dk/credits"]}

So what am I missing? Why is it not seeing the urlList array?

php mail script not sending mail [duplicate]

When I use the script below, no message gets sent. The failure message also doesn’t appear. I just get a blank screen. If I remove the $_POST, everything works. I double-checked the name of the form element coming over from the other page, so there is no typo there. I also noticed that the message fails if I add a variable for the mail header (but I do get the failure message in the else statemnt for that one…)

Thanks in advance!

<?php
    $to = "[email protected]";
    $subject = "Test Email from PHP";
    $message = "This is a test email sent using the PHP mail() function. From: " 
    $from = $_POST['subAdd'];
    $message = $message . $from

    if (mail($to, $subject, $message)){
      header("Location: http://practice.bkjdesignspa.com");
    }
    else{
      echo "Message failed";
    }

?>

global scopes for get , all and paginate function in laravel

I write a trait in laravel named prioritiable and I add a global scope to the query to sort the query result based on priority value

The problem is the scope add the order by SQL clause to all SELECT, DELETE , UPDATE , INSERT
but I want to just to have the scope on select

so I did this

trait Prioritiable
{
    protected static function bootPrioritiable(): void
    {
        static::retrieved(function ($model) {
            $model->addGlobalScope(OrderByPriorityScope::class);
        });
    }

}

The problem solved for first, find , firstOrFail , findOrFail but the scope does not work for get , all , paginate, since I think these three functions do not fire the retrieved event

the A_I says use $builder->getQuery()->type == ‘select’ in the scope apply function but the type does not exists and throws error

or do something like this

    public function apply(Builder $builder, Model $model)
    {
        $query = $builder->getQuery();

        // Apply only for SELECT queries that aren't aggregates
        if ($query->columns !== null && $query->aggregate === null) {
            $builder->orderBy('priority');
        }
    }

which not work fine

is there a difference between elements created dynamically with JavaScript and elements in HTML

take the code below:

    contentsDiv.innerHTML = container.outerHTML;

    if(contentsDiv.firstChild === container) console.log('true');

in this code, contentsDiv is a div created in my html file while container is a div with class=’container’ created with JavaScript. Then i insert container into contentsDiv. But when i check to see if the contentsDiv’s firstChild is equal to container (which it is in the DOM) it doesnt console.log(‘true’)

I tried

    console.log(typeof(contentsDiv.firstChild))
    console.log(typeof(container))

both returned to be an object but somehow they don’t resolve to be equal when i use ‘==’ or ‘===’

DragEnter event not firing reliably when mouse enters the drop zone

If you look at the SSCCE below you’ll see that when files are dragged from outside my drop-zone, the CSS attribute –fade-time is modified and the target begins to pulsate so the user knows it’s time to drop their bundle. The problem is that it doesn’t seem to be 100% reliable with the dragEnter event not always firing.

I can try deferring the event till the “container” element and then checking target.id=”div1″. Or maybe a “Once only” event dragOver to do what dragEnter used to do?

Any ideas on how to make the behaviour deterministic would be great.

document.addEventListener("DOMContentLoaded", (e) => {
  document.addEventListener('drop', function(e) {
    e.preventDefault()
  })
  document.addEventListener('dragenter', function(e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = "none"
  })
  document.addEventListener('dragover', function(e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = "none"
  })

  const dropZone = document.getElementById("container")
  dropZone.addEventListener("dragenter", (e) => {
    console.log("In enter " + dropZone)
    e.dataTransfer.dropEffect = "copy"
    e.preventDefault()
    e.stopPropagation()
    document.getElementById("div2").style.setProperty("--fade-time", "2.0s")
  })
  dropZone.addEventListener("dragover", (e) => {
    console.log("In over " + dropZone)
    e.dataTransfer.dropEffect = "copy"
    e.preventDefault()
    e.stopPropagation()
  })
  dropZone.addEventListener("dragleave", (e) => {
    console.log("In leave")
    e.dataTransfer.dropEffect = "none"
    e.preventDefault();
    document.getElementById("div2").style.removeProperty("--fade-time")
  })
  dropZone.addEventListener("drop", catchFiles)
})

function catchFiles(e) {
  e.preventDefault();
  document.getElementById("div2").style.removeProperty("--fade-time")
  console.log("File(s) dropped");

  let fileHolder = new FormData()
  let fileCount = 0

  if (e.dataTransfer.items) {
    // Use DataTransferItemList interface to access the file(s)
    [...e.dataTransfer.items].forEach((item, i) => {
      // If dropped items aren't files, reject them
      if (item.kind === "file") {
        const file = item.getAsFile()
        console.log(`… file[${i}].name = ${file.name}`)
        fileHolder.append("file" + i, file, file.name)
        fileCount++
      }
    });
  } else {
    // Use DataTransfer interface to access the file(s)
    [...e.dataTransfer.files].forEach((file, i) => {
      console.log(`… file[${i}].name = ${file.name}`);
      fileHolder.append("file" + i, file, file.name)
      fileCount++
    });
  }
  if (fileCount == 0) {
    alert("Zero files received")
    return
  }
  alert("got " + fileCount + " files")
  return
  const abortControl = new AbortController();
  const signal = abortControl.signal;
  const fetchOpts = {
    signal: signal,
    method: 'POST',
    body: fileHolder,
    cache: "no-cache"
  };
  const response = fetch("https://localhost:7196/upload/PostFormData", fetchOpts).catch(
    err => {
      console.log("Upload failed: " + err.message);
      return
    });
  if (signal.aborted) {
    alert("Cancelled")
    return
  }

}
#container {
  position: relative;
  display: flex;
  width: 120px;
  height: 120px;
  padding: 10px;
  border: 1px solid black;
}

#div1 {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: lightblue;
  cursor: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 300 300'><path fill='%23FFF' stroke='%23E50024' stroke-width='50' d='M150 25 a125 125 0 1 0 2 0z m 2 100 a25 25 0 1 1-2 0z'/></svg>"), auto;
}

#div2 {
  --fade-time: 0;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0%;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 300 300'><path fill='%23FFF' stroke='%23E50024' stroke-width='50' d='M150 25 a125 125 0 1 0 2 0z m 2 100 a25 25 0 1 1-2 0z'/></svg>");
  animation: pulseImage var(--fade-time) infinite;
}

body>p {
  color: red;
}

div>p {
  font-weight: bold;
}

@keyframes pulseImage {
  from {
    opacity: 0;
  }

  to {
    opacity: 0.7;
  }
}
<h1>File Drop Upload Example</h1>

<p>Drag your file(s) into the Drop Zone</p>

<div id="container">
  <div id="div1">
    <p>File Drop Zone</p>
  </div>
  <div id="div2"></div>
</div>

Video camera freezes when switching from rear to front with Twilio Video in Chrome for Android

Problem Details
I’m developing a video chat app using JavaScript and the Twilio Video SDK. I’ve implemented a feature to allow mobile users to switch between the front and rear cameras.

The problem is as follows:

  • The camera switching functionality works perfectly on iPhone.
  • On Android (using Chrome), the first switch (from the front to the rear camera) works correctly.
  • However, when trying to switch again, from the rear to the front camera, the local video freezes (shows the last frame) or goes black.
  • Interestingly, if I minimize the Chrome browser and reopen it, the front camera activates and the video displays correctly.

This appears to be an issue related to how Chrome on Android releases the rear camera resource before activating the front camera.

My current code performs the following steps to switch cameras:

  1. Get the list of available cameras (video input).
  2. Click the change button to select the device ID of the next camera.
  3. Create a new local video track (LocalVideoTrack) with the new device ID.
  4. UnpublishTrack and stop (track.stop()) the old video track.
  5. Publish the new video track.
  6. Replace the video element in the DOM with the new one.

Below is the relevant code snippet that handles this logic:

Plugin.prototype.checkDevices = function () {
        var that = this;
        var constraints = {
            audio: true,
            video: true
        };
        navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
            that.userStream = stream;
            var nstream = null;
            if (that.options.auto_recording === 4) {
                const tracks = stream.getAudioTracks();
                nstream = new MediaStream();
                nstream.addTrack(tracks[0]);
            } else {
                nstream = stream;
            }
            if (!that.setUpRTCRecorder('own', that.getVideoFrom(false), false, nstream, false)) {
                that.setUpStatRecording();
            }
            navigator.mediaDevices.enumerateDevices().then(function (mediaDevices) {
                var count = 1;
                const select = document.getElementById('video-switch-select');
                that.cameraSelected = 0;
                mediaDevices.forEach(mediaDevice => {
                    if (mediaDevice.kind === 'videoinput') {
                        count++;
                        that.cameras.push({
                            id: mediaDevice.deviceId,
                            label: mediaDevice.label || `Camara ${count}`
                        });
                    }
                });
                if (that.cameras.length > 1) {
                    $(".video-switch-button").on('click', function () {
                        that.cameraSelected++;
                        if (that.cameraSelected >= that.cameras.length) {
                            that.cameraSelected = 0;
                        }
                        console.log("Switching to camera", that.cameraSelected);
                        var toswitch = that.cameras[that.cameraSelected];
                        Twilio.Video.createLocalVideoTrack({
                            deviceId: {exact: toswitch.id}
                        }).then(function (localVideoTrack) {
                            console.log("Adding track", localVideoTrack);
                        const publications = Array.from(that.activeRoom.localParticipant.videoTracks.values());
                            for (var i in publications) {
                                var track = publications[i].track;
                                console.log("Unpublishing track", track);
                                that.activeRoom.localParticipant.unpublishTrack(track);
                                track.stop();
                        }
                            that.activeRoom.localParticipant.publishTrack(localVideoTrack);
                            $('#local-media').html("");
                            document.getElementById('local-media').appendChild(localVideoTrack.attach());
                            if (that.chatOn) {
                                $('#local-media > video').addClass('local-media-oncall-video-chat');
                                $('.user-placeholder').addClass('placeholder-oncall-video-chat');
                            } else {
                                $('#local-media > video').addClass('local-media-oncall-video');
                                $('.user-placeholder').addClass('placeholder-oncall-video');
                            }

                        }).catch(error => {
                            console.error("Error al crear la nueva pista de video:", error);
                            alert("Error al cambiar de cámara: " + error.message);
                    });
                    });
                }
            });
            that.initCB();
        }).catch(function (error) {
            alert('getUserMedia() error: ', error.message);
        });
    };

I’m looking for a solution that allows me to seamlessly switch between the rear and front cameras in Chrome on Android without the video freezing or getting the Could not start video source error.

How to detect mouse over canvas

I’m using a userscript that overrides CanvasRenderingContext2D.prototype.drawImage to replace a specific image (oldimg.png) with a custom image (newimg.png) when it is rendered on a canvas. I would like to detect when the user’s mouse hovers over the area where the new image is drawn and trigger an alert(“hello world”). Since the image is drawn on the canvas (not a regular DOM element), what’s the best way to detect hover interactions with that specific image region? I have tried many tradition routes to select DOM elements but they have not worked due to the new image being drawn on a canvas.

(function() {
    'use strict';

    var coinImageWhite = new Image(500, 500);
    coinImageWhite.src = 'https://agma.io/skins/newimg.png'
    var coinImageBlack = new Image(500, 500);
    coinImageBlack.src = 'https://agma.io/skins/newimg.png'

    var rawSettings = localStorage.getItem('settings');
    var settings = JSON.parse(rawSettings);

    var originalDrawImage = CanvasRenderingContext2D.prototype.drawImage;
    CanvasRenderingContext2D.prototype.drawImage = function (image, sourceX, sourceY, sourceWidth, sourceHeight, targetX, targetY, targetWidth, targetHeight) {
        if ((image.src != undefined)) {

            if (image.src == 'https://agma.io/skins/oldimg.png' || image.src == 'https://agma.io/skins/oldimg.png') {

                if (settings.sDark) {
                    arguments[0] = coinImageBlack;
                    console.log("yo");
                } else {
                arguments[0] = coinImageWhite;
                    console.log("yo");
                }
            }
        }

        return originalDrawImage.apply(this, arguments);
    }

    console.log('Script loaded');
})();

Convert Alpine.js on-click to Datastar data-on*

I have some links on my site which currently uses alpine.js to trigger a function that scrolls to a div on the page and I wish to convert this to use Datastar.js

This is what is currently in the base.html file and the javascript file.

base.html
<div class="flex h-full items-end py-4 gap-x-14 text-white uppercase text-xs font-medium">
    <div><a href="#" x-on:click.prevent="scrollToId('contact')">Contact Us</a></div>
    <div><a href="#" x-on:click.prevent="scrollToId('about')">About us</a></div>
    <div><a href="#" x-on:click.prevent="scrollToId('services')">Services</a></div>
    <div><a href="#" x-on:click.prevent="scrollToId('products')">Products</a></div> </div>

The javascript function is as follows and is imported into index.js then ran through webpack.

export default () => ({
    scrollToId(id) {
        // This is used for the navigation links in the header and footer
        const element = document.getElementById(id);
        if (element) {
            element.scrollIntoView({behavior: 'smooth' });
        }
    },
});

I have tried to convert this to Datastar data-on-click and run the ‘scrollToId’ function but it errors out saying it can’t find the function.

<div><a href="#" data-on-click__prevent="scrollToId('contact')">Contact Us</a></div>
127.0.0.1/:10  GET http://127.0.0.1:8000/assets/components/smoothScroll.js net::ERR_ABORTED 404 (Not Found)
init_embed.js:285 Search endpoint requested!
backend.js:2 Alpine Devtools: waiting for init request...
datastar.js:8 Uncaught datastar runtime error: ExecuteExpression
More info: https://data-star.dev/errors/runtime/execute_expression?metadata=%7B%22plugin%22%3A%7B%22name%22%3A%22on%22%2C%22type%22%3A%22attribute%22%7D%2C%22element%22%3A%7B%22id%22%3A%22%22%2C%22tag%22%3A%22A%22%7D%2C%22expression%22%3A%7B%22rawKey%22%3A%22onClick__prevent%22%2C%22key%22%3A%22click%22%2C%22value%22%3A%22scrollToId%28%27contact%27%29%22%2C%22fnContent%22%3A%22scrollToId%28%27contact%27%29%22%7D%2C%22error%22%3A%22scrollToId+is+not+defined%22%7D
Context: {
  "plugin": {
    "name": "on",
    "type": "attribute"
  },
  "element": {
    "id": "",
    "tag": "A"
  },
  "expression": {
    "rawKey": "onClick__prevent",
    "key": "click",
    "value": "scrollToId('contact')",
    "fnContent": "scrollToId('contact')"
  },
  "error": "scrollToId is not defined"
}
    at pt (webpack://website/./assets/datastar.js?:8:1275)
    at Number.mt (webpack://website/./assets/datastar.js?:10:330)
    at On.e.runtimeErr.error (webpack://website/./assets/datastar.js?:11:876)
    at HTMLAnchorElement.c (webpack://website/./assets/datastar.js?:11:9090)
pt @ datastar.js:8
mt @ datastar.js:10
On.e.runtimeErr.error @ datastar.js:11
c @ datastar.js:11

I really can’t find anything in relation to doing this.

Apologies in advanced if I am missing something simple.

useEffect with const Dependency Parameters React Question?

I have this code in React:

const EditPost = ({
  posts, handleEdit, editBody, setEditBody, editTitle, setEditTitle
}) => {
    const { id } = useParams();
    const post = posts.find(post => (post.id).toString() === id);

    useEffect(() => {
        if (post) {
            setEditTitle(post.title);
            setEditBody(post.body);
        }
    }, [post, setEditTitle, setEditBody])

    return (
        <div> nothing here yet... </div>
    )
}

This example is from a youtube.com video. Why did the author put post, setEditTitle, and setEditBody variables in the dependency array? What effect does that have? Why bother even having useEffect() even at all?

This is from React JS Full Course for Beginners | Complete All-in-One Tutorial | 9 Hours
You can see the same code from:
Ch 19: Axios API Requests
6:29:42

Thanks!