0

I am trying to submit a dynamic amount of forms by pressing one button. The form has seperate submit buttons and updating the data works with that button.

I made a fixed button on the bottom of the page that I would like to be able to submit all forms. So you can adjust all the data in all the forms, press 1 button and update all the data in the database.

Like I said, the updating the database part works (for a single form).

So this is my current code:

<button id="saveall" style="position: fixed; bottom: 20px;">Opslaan</button>
<script>
$( "#saveall" ).click(function() {
    console.log("clicked");
    $("form.edit_form").each(function () {
        var form = $(this);
        var url = form.attr('action');

        $.ajax({
            type: "POST",
            url: url,
            data: form.serialize(), // serializes the form's elements.
            success: function(data)
            {
                console.log(data); // show response from the php script.
            }
        });
    });
});
</script>

This is what a form looks like:

<form class="edit_form" method="post" action="/collectie-manager-edit">
            <input type="hidden" name="UID" value="%UID%">
            <div>
                <label>Titel</label><br>
                <input type="text" name="titel" value="%titel%">
            </div>
            <div>
                <label>Merk</label><br>
                <input type="text" name="merk" value="%merk%">
            </div>
             <div>
                <label>Prijs</label><br>
                <input type="text" name="prijs" value="%prijs%">
            </div>
            <div>
                <label>Jurkcode</label><br>
                <input type="text" name="jurkcode" value="%jurkcode%">
            </div>
            <div>
                <label>Jurk Titel</label><br>
                <input type="text" name="Jurktitel" value="%Jurktitel%">
            </div>
            <div>
                <label>Youtube code</label><br>
                <input type="text" name="youtubecode" value="%youtubecode%">
            </div>
            <div>
                <label>Custom url</label><br>
                <input type="text" name="custom_url" value="%custom_url%">
            </div>
            <div>
                <label>Positie</label><br>
                <input type="text" name="positie" value="%positie%">
            </div>
            <input type="submit" name="change_item" value="opslaan">
        </form>

Current php code handeling the form submit (single):

if(isset($_POST['change_item'])){
        $result = $db->update(
            "collectie",
            ["UID" => $_POST['UID']],               // get
            ["titel" => $_POST['titel'],"merk" => $_POST['merk'],"prijs" => $_POST['prijs'],"jurkcode" => $_POST['jurkcode'],"Jurktitel" => $_POST['Jurktitel'],"youtubecode" => $_POST['youtubecode'],"custom_url" => $_POST['custom_url'], "positie" => $_POST['positie']]                            // getFuzzy
        );
    }

What happends currently?

It spits out all the html into the console and nothing happends in the .php The form handler is in the same php controller as the page. So the action points to the same page.

I have never used Ajax and I think its extremely confusing.

I can't find anything on the web that says I need different php for handling the ajax method. And seeing that I get 0 errors I am unsure of what to do to fix it.

ps: All the values that has %% in them are filled by the cms the page is build with. They are filled with values from the database.

Edit on why this question is different from the one that is linked.

That question asks how to dynamically post inputs not seperate forms. I have tried the answers in that question and they do not work.

A quote from the question:

I have a form with name orderproductForm and an undefined number of inputs.

I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm.

1 Answers1

0

Ok, I think I get it.

Use .serializeArray() instead of .serialize().

Example result with .serialize():

UID=5&titel=myTitel

Example result with .serializeArray():

[
    { name: 'UID', value: '5' },
    { name: 'titel', value: 'myTitel' }
]

Also, check if your submit button (change_item) is in your array, if that's not the case (and will not because that's an input button), you may add it in your serialized array, or update your PHP controller.

Be aware that with .serializeArray(), you will not be able to retrieve your input data with $_POST['input_name'], as indexes are integer (from 0 to your array length). Here's a function to convert your array:

let serialized = [
    {name: 'UID', value: '5'},
    {name: 'titel', value: 'myTitle'}
];

serialized = formatSerializedFormForAjax(serialized);

function formatSerializedFormForAjax(serialized) {
    let result = {};

    for (let i in serialized) {
        result[serialized[i].name] = serialized[i].value;
    }

    return result;
}

console.log(serialized);

If you use if in your code:

// form and url
let data = formatSerializedFormForAjax(form.serializedArray());

$.ajax({
   // ...
   data: data,
   // ...
});

Now you should be able to get your input values with $_POST['UID'].

Kévin Bibollet
  • 3,573
  • 1
  • 15
  • 33
  • Thanks for your answer. The code I have above with your change just logs me the whole html of the page instead of just an array. So not sure if the intitial code is correct. – Robbert Cognito Mar 11 '19 at 08:58
  • What if you log `form.serialize()` and the `url` variable before sending the AJAX? – Kévin Bibollet Mar 11 '19 at 09:01
  • That seemed to work and no change_item is not in the array. – Robbert Cognito Mar 11 '19 at 09:06
  • Can you give us the content of the `console.log()`? If `change_item` is not in your array, so `isset($_POST['change_item'])` will never be `true`. ;) You may have to add it manually before sending your request. – Kévin Bibollet Mar 11 '19 at 09:11
  • But even if I for example add a die(); when $_POST['UID'] isset. It still does not get triggered when I use the ajax submit. Even when it logs Success! for all 16 forms that are on the page – Robbert Cognito Mar 11 '19 at 09:11
  • The contents of an array example: 0: {name: "UID", value: "1234"} 1: {name: "titel", value: "This is a title"} 2: {name: "merk", value: "Brand"} 3: {name: "prijs", value: "1249"} 4: {name: "jurkcode", value: "Set 405"} 5: {name: "Jurktitel", value: "jurktitel"} 6: {name: "youtubecode", value: ""} 7: {name: "custom_url", value: "custom-url-page"} 8: {name: "positie", value: "1234"} – Robbert Cognito Mar 11 '19 at 09:15
  • "But even if I for example add a die(); when $_POST['UID'] isset. It still does not get triggered when I use the ajax submit." I am not sure to really understand that point. In your current PHP, your database will update if `isset($_POST['change_item'])` is `true`. As it is not the case, `$db->update()` will not be executed. But the fact that your AJAX executes your `success` callback is not linked, that's just because there is actually no error. – Kévin Bibollet Mar 11 '19 at 09:36
  • What I meant is, that if I add: if(isset($_POST['UID'])){ die($_POST['UID']); } to the php controller (outside of the if isset($_POST['change_item']) and it still does not die when I press the save all button. It may not have the change_item post data but it should have the UID that is in the form. But its almost like the ajax does not even reach the php file. – Robbert Cognito Mar 11 '19 at 09:46
  • Because `$_POST['UID']` does not exist. But `$_POST[0]` does. (with `$POST[0]['name']` is equal to `UID`). – Kévin Bibollet Mar 11 '19 at 09:48
  • I didnt think of that. But it still does not die when I filter on that. I am now starting to think, either the cms is blocking something or the ajax is not pointing to the right location. – Robbert Cognito Mar 11 '19 at 09:53
  • I edited my post with a possible solution. Tell me if it works – Kévin Bibollet Mar 11 '19 at 10:07
  • I edited it in. It puts out 16 success's but still unable to catch anything in my php file. – Robbert Cognito Mar 11 '19 at 10:18
  • I updated my `formatSerializedFormForAjax` function, it initialized `result` as an array instead of an object. I tried in a local test project (simple html form with ajax, and a `var_dump($_POST)` in my PHP, and I can access my data.) – Kévin Bibollet Mar 11 '19 at 10:36
  • I am honestly at a loss. I have the exact same code, the ajax gives me a succes every single time and no matter where I send the damn ajax call nothing happends. NO error or anything. – Robbert Cognito Mar 11 '19 at 10:46
  • Weiiiird... Can you give me the content of `var_dump($_POST)` placed at the right start of your `collectie-manager-edit` controller method? – Kévin Bibollet Mar 11 '19 at 10:53
  • Its all the data that is needed to generate the results of the page. There is nothing in there from the ajax post tho. – Robbert Cognito Mar 12 '19 at 20:42
  • I have not any solution left right now... What is the CMS you are using? – Kévin Bibollet Mar 13 '19 at 07:49
  • Its a custom PHP CMS. I guess there is no way for me to use ajax. The cms will not allow it. :( – Robbert Cognito Mar 13 '19 at 07:53
  • Is there any way to ask the developer(s) about that? – Kévin Bibollet Mar 13 '19 at 07:55
  • The cms was created some time ago by programmers who do not work here anymore. So that is not possible. I guess ill have to find a different way. Thanks for your effort tho :) – Robbert Cognito Mar 13 '19 at 07:57
  • No problem. You could search in the source code and may find some hints. ;) – Kévin Bibollet Mar 13 '19 at 07:59