Skip to content

add match function#848

Open
tszyuloveyou wants to merge 15 commits intotighten:2.xfrom
tszyuloveyou:2.x
Open

add match function#848
tszyuloveyou wants to merge 15 commits intotighten:2.xfrom
tszyuloveyou:2.x

Conversation

@tszyuloveyou
Copy link

@tszyuloveyou tszyuloveyou commented Jun 1, 2025

https://github.com/Mensa-Hong-Kong/New-Official-Website/pull/110/files#diff-8459b0aa95c878f3fcec2452a009295922ccd4a2c79d32cf02171c0c1c7ba41c
On my project, I using axios to submit form, than I need get the item id on the callback, so, I want to add match function to easly get the id from response.request.responseURL

and than, laravel also has same function on php
https://stackoverflow.com/questions/40690202/previous-route-name-in-laravel-5-1-5-8

@tszyuloveyou
Copy link
Author

on my project, the changed code is word, now

@bakerkretzmar bakerkretzmar self-assigned this Jun 2, 2025
@bakerkretzmar
Copy link
Collaborator

Can you share an example of some code showing how you would use this?

@tszyuloveyou
Copy link
Author

tszyuloveyou commented Jun 2, 2025

Can you share an example of some code showing how you would use this?

sure, I have been updated the readme

I also can demo a sample example

This is my project submit form helper: resources/js/submitForm.js

const token = document.querySelector("meta[name='csrf-token']").getAttribute("content");

function failHandle(error, callback) {
    switch(error.status) {
        case 401:
            alert('Unauthorized, please login first');
            window.location = route('login');
            break;
        case 403:
            alert('Sorry, you have no permission');
            break;
        case 419:
            alert('Cross-site request forgery alert, may be the domain is not mensa.org.hk, or you hold on this page longer than the CSRF token lifetime');
            break;
        case 500:
            alert('Unexpected error, please contact I.T.');
            break;
        case 503:
            alert('Database connect fail, please try again later, or contact I.T.');
            break;
        default:
            if(error.response.data.message) {
                alert(error.response.data.message);
            }
            break;
    }
    callback(error);
}

export function post(action, successCallback, failCallback, method="POST", data = {}) {
    data['_token'] = token;
    if(method.toUpperCase() != 'POST') {
        data['_method'] = method;
    }
    axios.post(action, data).then(function (response) {
        successCallback(response);
    }).catch(function(error) {
        failHandle(error, failCallback)}
    );
}

export function get(action, successCallback, failCallback, parameters = {}) {
    axios.get(action, {params: parameters}).then(function (response) {
        successCallback(response);
    }).catch(function(error) {
        failHandle(error, failCallback)}
    );
}

and than I set resources/js to alias @
I try to use svelte component to demo ajax control candidate status

<script>
import { post } from "@/submitForm";

let submitting = $state(false);

let {candidates: initCandidates} = $props();
const candidates = $state([]);

for (const data of initCandidates) {
    candidates.push(data);
}

function getIndex(id) {
    return candidates.findIndex(
        function(element) {
            return element.id == id;
        }
    );
}

function updatePresentSuccessCallback(response) {
    alert(response.data.success);
    let location = new URL(response.request.responseURL);
    let id = route().match(location.host + location.pathname, 'PUT').params.candidate;
    candidates[getIndex(id)]['is_present'] = response.data.is_present;
    submitting = false;
}

function updatePresentFailCallback(error) {
    if(error.status == 422) {
      alert(error.data.errors.status);
    }
    submitting = false;
}

function updateStatus(id, status) {
    if(! submitting) {
        let submitAt = Date.now();
        submitting = 'updateAction'+submitAt;
        if(submitting == 'updateAction'+submitAt) {
            post(
                route(
                    'admin.tests.candidate.present.update',
                    {
                        test: route().params.test,
                        candidate: id,
                    }
                ),
                updatePresentSuccessCallback,
                updatePresentFailCallback,
                'put',
                {status: status}
            );
        }
    }
}
</script>
<h1>Candidate List</h1>
<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Is Present</th>
        </tr>
    </thead>
    <tbody>
        {#each candidates as candidate, index{
            <tr>
                <th>{candidate.id}</th>
                <td>{candidate.name}</td>
                <td>
                    <button onclick:{() => updateStatus(candidate.id, ! candidate.is_present)} class={[
                        'btn', {
                            'btn-success' => candidate.is_present,
                            'btn-danger' => ! candidate.is_present,
                        }
                    ]} disabled="{submittibg}">{candidate.is_present ? 'Present' : 'Absent'}</button>
                </td>
            </tr>
        {/each}
    </tbody>
</table>

because too many page need to use ajax, if each page witre one time submit form logic too duplicate, and not each also has id, so, add id params and callback pass id is not good idea, so, I think use route match to get route params may be better.

you also can see my project:

  1. https://github.com/Mensa-Hong-Kong/New-Official-Website/pull/110/files#diff-8459b0aa95c878f3fcec2452a009295922ccd4a2c79d32cf02171c0c1c7ba41c
    this page has OtherPaymentGateway.svelte updateNameSuccessCallback and updateNameFailCallback function using the route().match(......) function
  2. https://github.com/Mensa-Hong-Kong/New-Official-Website/pull/111/files#diff-8459b0aa95c878f3fcec2452a009295922ccd4a2c79d32cf02171c0c1c7ba41c
    this page has OtherPaymentGateway.svelte updateActionSuccessCallback function using the route().match(......) function
  3. https://github.com/Mensa-Hong-Kong/New-Official-Website/pull/112/files#diff-8459b0aa95c878f3fcec2452a009295922ccd4a2c79d32cf02171c0c1c7ba41c
    this page show submit form no id pass to callbace(not for demo using the route().match(......), just show for why cannot on submitForm.js request id param and pass id to callback)

@tszyuloveyou
Copy link
Author

tszyuloveyou commented Dec 22, 2025

@bakerkretzmar May I know why cannot marge my PR without conflicts.

  1. You can see the file change, I just changed "_unresolve" method name of Router.js to "match" because _{method} build to disk file will rename to unexpected sample function(e.g.: a(), b(), c()...) and let matchUrl method from only can support GET http method to support other by avg that if default only is "GET", is have no affect origin exist method, I think it is save changing.
  2. I have add the unit test to mark sure it is work.
  3. I have updated the readme to let other developer know that has "method" can use.
  4. I has been reply for your question for why we need it because on OOP, we may let the form submitting by ajax to mark a class than we will using callback method. On the callback method, we cannot easily to get parameter from url, if each callback add one regex to get parameter from url or add the exist on url data to response that is very stupid. When we are already matchUrl amd _unresolve method that I have no idea why we not make the best use of resources.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants