Home > OS >  Add a string at the end of my ajax url beforeSend
Add a string at the end of my ajax url beforeSend

Time:03-24

I don't know why I can't get this to work. I have a code to GET objects via Ajax:

Here is my code:


var $form = $(document).find('#my_form');
const $objectassemblepoint = $('#my_object_assemble_point');

     function convertFromDataToArray(formData) {
            let data = [];
            formData.forEach(function (obj) {
                if (obj.value) {
                    // break with price
                    if (['min_price', 'max_price'].includes(obj.name)) {
                        const dataValue = $form.find('input[name='   obj.name  ']').data(obj.name.substring(0, 3));
                        if (dataValue == parseInt(obj.value)) {
                            return;
                        }
                    }
                    data.push(obj);
                }
            });
            return data;
        }

     if ($form.length) {
            $(document).on('submit', '#my_form', function (event) {
                event.preventDefault();
                const $form = $(event.currentTarget);
                const formData = $form.serializeArray();
                let data = convertFromDataToArray(formData);
                let uriData = [];

                const $elPage = $objectassemblepoint.find('input[name=page]');
                if ($elPage.val()) {
                    data.push({name: 'page', value: $elPage.val()});
                }

                data.map(function (obj) {
                    uriData.push(encodeURIComponent(obj.name)   '='   obj.value);
                });

                var popStateUrl = $form.attr('action')   (uriData && uriData.length ? ('?'   uriData.join('&')) : '');

                var addThisToEnd = '&q=luxury';

                $.ajax({
                    url: $form.attr('action'), // Plainly: "https://mydomainname.com/joggers" from my actual form
                    type: 'GET',
                    data: data,
                    beforeSend: function () {
                        //Do stuffs before send
                    },
                    success: function (response) {
                        if (response.error === false) {
                            $objectstoadd.html(response.data);
                            
                            if (popStateUrl !== window.location.href) {
                                window.history.pushState(data, response.message, popStateUrl);
                            }
                        } else {
                            showError(response.message || 'Something went wrong!');
                        }
                    },
                    error: function (response) {
                        handleError(response);
                    },
                    complete: function () {
                        //Some things to do
                    }
                });
         }

With the above code, when the user selects a type of joggeres, the url from Ajax becomes:

https://mydomainname.com/joggers?min_price=0&max_price=100&thetype[]=1&_=[TIMESTAMP]

But I desire something like this rather:

https://mydomainname.com/joggers?min_price=0&max_price=100&thetype[]=1&q=luxury&_=[TIMESTAMP]

I have tried doing:

$.ajax({
                    url: $form.attr('action') addThisToEnd // Since I have a variable with the string as above,

But everything gets messy. Please I do not know much of Ajax. Please help.

CodePudding user response:

You don't provided your full script to understand your problem, but this It will show you if you forgot something in your script:

Edit: Function convertFromDataToArray you don't need it cause data is already is array

    var $form = $(document).find('#my_form');
    const $objectassemblepoint = $('#my_object_assemble_point');

    if ($form.length) {
        $(document).on('submit', '#my_form', function (event) {
            event.preventDefault();
            const $form = $(event.currentTarget);
            const data = $form.serializeArray();
            let uriData = [];

            const $elPage = $objectassemblepoint.find('input[name=page]');
            if ($elPage.val()) {
                data.push({ name: 'page', value: $elPage.val() });
            }

            data.map(function (obj) {
                uriData.push(encodeURIComponent(obj.name)   '='   obj.value);
            });

            var popStateUrl = $form.attr('action')   (uriData && uriData.length ? ('?'   uriData.join('&')) : '');


            var addThisToEnd = {name: 'q', value:'luxury'};
            data.push(addThisToEnd);

            console.log($form.attr('action')   '?'   $.param(data));


            $.ajax({
                url: $form.attr('action'), // Plainly: "https://mydomainname.com/joggers" from my actual form
                type: 'GET',
                data: data,
                beforeSend: function () {
                    //Do stuffs before send
                },
                success: function (response) {
                    if (response.error === false) {
                        $objectstoadd.html(response.data);

                        if (popStateUrl !== window.location.href) {
                            window.history.pushState(data, response.message, popStateUrl);
                        }
                    } else {
                        showError(response.message || 'Something went wrong!');
                    }
                },
                error: function (response) {
                    //handleError(response);
                },
                complete: function () {
                    //Some things to do
                }
            });
        });
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my_form" action="https://yourdomain.com/joggers">
        Min price: <input type="text" name="min_price" value="20"><br>
        Max price: <input type="text" name="max_price" value="100"><br>
        The Type: <input type="text" name="thetype" value="test"><br>
        <button type="submit">Submit</button>
    </form>

  • Related