1

I have products listing page where all listed products have different form name and id using while loop as mentioned in below piece of code. I want to make so when user clicks on 'Add' button for particular product, then that specific product's form should be submitted using AJAX/jQuery.

product_listing.php

<script language="JavaScript" src="./product_listing.js"></script>
while loop to list products on page { 

    <form id="frm_add<?php print $rs_list->Fields("pkid"); ?>" name="frm_add<?php print $rs_list->Fields("pkid"); ?>" novalidate>
        <input type="hidden" name="hdn_prodpkid" id="hdn_prodpkid" value="<?php print $rs_list->Fields("pkid"); ?>">
        ... other variables...
        <button type="submit" name='btn_addtocart' id='btn_addtocart'>Add</button>
    </form>

end of while loop }

I want submitted form's ID so I can fetch input fields' values for that submitted form. But on every form submission I got last form's ID.

So how can I get unique (only submitted) form's ID on JS page? Please advise.

Below code works perfectly when there is a single form to submit. In that case, form id is predefined on both .php and .js pages.

product_listing.js

$(function() {

    $("#"+NEED_SUBMITTED_FORM_ID_HERE+" input, #"+NEED_SUBMITTED_FORM_ID_HERE+" select").jqBootstrapValidation({

        preventSubmit: true,
        submitError: function($form, event, errors) {
            ...other code...
        },
    
        submitSuccess: function($form, event) {
        event.preventDefault();
        var hdn_prodpkid = $("input#hdn_prodpkid").val();
        ... other variables...

            $.ajax({
                url: "./product_addtocart_p.php",
                type: "POST",
                data: {
                hdn_prodpkid: hdn_prodpkid,
                ... other variables...

            },
            cache: false,
            
            success: function(data) 
            {
                ...other code...
            }
        }
    });
});

-- UPDATED CODE --

product_listing.js

var id = '';
$(function() {
    $("form").submit(function() {
        var form = $(this);
        var id = form.attr('id');
        //alert(id + ' form submitted');

        $("#"+id+" input, #"+id+" select").jqBootstrapValidation({
        //alert(id + ' form submitted'); // Can't alert ID here
            submitSuccess: function($form, event) {
                event.preventDefault(); // prevent default submit behaviour
                var hdn_prodpkid = $("input#hdn_prodpkid").val();
                $.ajax({
                    url: "./product_addtocart_p.php",
                    type: "POST",
                    data: {
                        hdn_prodpkid: hdn_prodpkid
                    },
                    cache: false,
                }) // End of Ajax
            }, // End of submitSuccess
        }); // End of jqBootstrapValidation
    }); // End of form submit
}); // End of $(function()) 
K Ahir
  • 395
  • 1
  • 6
  • 21
  • How many forms you have in product_listing.php file? In the above code, there is only one form. – Lokesh Suman Jul 14 '20 at 06:15
  • I'm not sure I fully understand what the requirement but you can generate a random id with https://stackoverflow.com/a/6860916/863110 then you can add the id to the form using `input[type="hidden"]` and finally to submit the form using [ajaxForm](http://jquery.malsup.com/form/) – Mosh Feu Jul 14 '20 at 06:20
  • @LokeshSaini, it can be any number of forms and it depends on number of products. Currently I have just mentioned While Loop in my above code to keep code smaller. – K Ahir Jul 14 '20 at 06:41
  • @KAhir you are declaring `id` variable two times, Change `var id = form.attr('id');` to `id = form.attr('id');` because you had declared id variable previously. – Lokesh Suman Jul 15 '20 at 05:36
  • @KAhir If you can't get id inside the `jqBootstrapValidation` function, then I am sure your `jqBootstrapValidation` function is not working. – Lokesh Suman Jul 15 '20 at 05:40
  • @LokeshSaini, I made change of twice declaration of `var id`. If I am using this same code for single form then it works fine but not working for multiple forms. So not sure how to make sure that `jqBootstrapValidation` function is not working. Please advise. – K Ahir Jul 15 '20 at 06:20
  • You are using the `hdn_prodpkid` variable in your ajax, Check this variable's value for different products (form). Does this value is different or the same for all products (forms)? – Lokesh Suman Jul 15 '20 at 07:05
  • @LokeshSaini, yes each `hdn_prodpkid` value is different but I can't alert this value on JS page because my product listing page is just submitted itself. – K Ahir Jul 17 '20 at 06:31

3 Answers3

0

When a user clicks on Add (Add-to-cart) button that button's parent form will be submitted because you are using <button type="submit">Add</button>.

The type="submit" property is used for a form submission. If you have multiple forms then, use the jQuery to get submitted form elements like this-

$("form").submit(function(){
  var form = $(this);
  var id = form.attr('id');
  alert(id + ' form submitted');
});

When any form submitted from your product_listing.php file the above code will run and retrieves the Id of that submitted form.

After that, you can run your ajax for other calculation onproduct_listing.js file.

--Update--

try using the below example

$(document).ready(function() {

var id; //For global access

$("form").submit(function(){
  var form = $(this);
   id = form.attr('id');

  $("#"+id+" input, #"+id+" select").jqBootstrapValidation({

    preventSubmit: true,
    submitError: function($form, event, errors) {
        ...other code...
    },

    submitSuccess: function($form, event) {
    event.preventDefault();
    var hdn_prodpkid = $("input#hdn_prodpkid").val();
    ... other variables...

        $.ajax({
            url: "./product_addtocart_p.php",
            type: "POST",
            data: {
            hdn_prodpkid: hdn_prodpkid,
            ... other variables...

        },
        cache: false,

        success: function(data) 
        {
            ...other code...
        }
    }
  });
});
});

alert(id);

Now I have defined the id variable outside the function so you can access it outside the function.

Hope this will work...

--Update--

I am not able to reproduce your provided code so I only suggest you how to handle this problem. First, simplify your code and check which code is working or which code is not worked, after that, you have to check why this code is not working.

If possible simplify your code that could get you the hint why your code is not working. I have simplified your code If possible use the simplified code.

Thank you

Your product_listing.js

var id = '';
$(function() {
  $("form").submit(function(e) {
    e.preventDefault(); // prevent default submit behaviour
    var form = $(this);
    id = form.attr('id');
    var hdn_prodpkid = $("#id #hdn_prodpkid").val();
    $.ajax({
      url: "./product_addtocart_p.php",
      type: "POST",
      data: {
        hdn_prodpkid: hdn_prodpkid
      },
      cache: false,
    }) // End of Ajax
  }); // End of form submit
}); // End of $(function()) 
Lokesh Suman
  • 493
  • 5
  • 14
  • I am getting proper form ID on js page now but then I need to apply that form ID to shown in below code so I can get all hidden values passed for selected form. But I am not getting fetched form ID in this code - $("#"+id+" input, #"+id+" select").jqBootstrapValidation({ – K Ahir Jul 14 '20 at 08:20
  • @KAhir I have updated my answer now the code will run and retrieve the hidden values when the submit button is pressed. – Lokesh Suman Jul 14 '20 at 08:49
  • Hello, I tried your above provided code but if I alert form ID after this code then it is not alerting. $("#"+id+" input, #"+id+" select").jqBootstrapValidation({ ... Please advise. – K Ahir Jul 14 '20 at 09:08
  • Did you want to access the id outside the function? If yes then you have to declare the id variable globally in your js file. The id variable is declared inside the function so it can only accessible inside the function – Lokesh Suman Jul 14 '20 at 09:29
  • yes, I need it globally. So how can I declare it globally? Please let me know. Also in your above updated answer, will be available inside jqBootstrapValidation function? Please let me know. – K Ahir Jul 14 '20 at 09:37
  • @KAhir I have declared the id globally, check the updated answer – Lokesh Suman Jul 14 '20 at 09:45
  • Hello, I put all code as per your answer but for some reason I am not getting form ID inside jqBootstrapValidation function? Is it possible to send your my entire code so you can have a look? Please let me know. – K Ahir Jul 14 '20 at 10:07
  • Check the code carefully probably you are missing something. – Lokesh Suman Jul 14 '20 at 10:55
  • Hello, I checked entire code and also posted updated .JS page code in my initial question. Please have a look and reply. Ty – K Ahir Jul 14 '20 at 14:19
0

please find the changes hope this works

  1. first of all update, the code for the button the id is repeated that is invalid

  2. trigger the click event of the button by class

    <button class="submitButton" type="submit" name="btn_addtocart" id="btn_addtocart_" .$rs_list->Fields("pkid"); ?>>Add

    $(".submitButton").click(function () { var form = $(this).parent("form"); console.log(jQuery(form).attr("id")); });

user12398926
  • 45
  • 10
  • Ty for your reply but as I mentioned in my initial and updated question, I am getting unique form ID but there after I am not able to fetch that value here in this code `$("#"+id+" input, #"+id+" select").jqBootstrapValidation({` and after this. That's why further JS code is not executed. Please advise. – K Ahir Jul 17 '20 at 14:30
  • try var values = {}; jQuery.each($('#'+jQuery(form).attr("id")').serializeArray(), function(i, field) { values[field.name] = field.value; }); – user12398926 Aug 04 '20 at 10:21
0

Identifiers in HTML must be unique hence don't use id="hdn_prodpkid" as irrespective to number of elements with hdn_prodpkid id the following statement

var hdn_prodpkid = $("input#hdn_prodpkid").val();

will always return you the value of the first element.

I would recommend you not use the hidden element as you are not actually submitting the form to API instead using ajax() call.

Immediate solution(I would not recommend this approach) would be to use

var hdn_prodpkid = $form.find("input#hdn_prodpkid").val();

Use custom data-* attributes to persists arbitrary information with the form i.e. pkid which can be fetched using .data(key) method.

Assuming <input> and <select> are descendant of the form element, Use .find() to get the references afterward apply jqBootstrapValidation() method on them.

When submitting the form using jqBootstrapValidation() the submitSuccess($form, event) callback method gives the references of the <form> element which has the user attempted to submit (wrapped in jQuery) i.e.$form. It can be used to get the references of the desired descendant element or get the arbitrary data from the <form> element.

HTML

while () {
    <form data-id="<?php print $rs_list->Fields("pkid"); ?>" novalidate>
         <button type="submit">Add</button>
    </form> 
}

Script

$("form").submit(function() {
    var id= $(this).data('id'); //Example
    $(this).find('input, select') //Target the descendant
        .jqBootstrapValidation({
            submitSuccess: function($form, event) {
                //Perform the desired operation here to get the relvant data from thr form 
                
                event.preventDefault();                
                $.ajax({
                    url: "./product_addtocart_p.php",
                    type: "POST",
                    data: {
                        hdn_prodpkid: $form.data('id') //Get Arbitary data
                    },
                    cache: false,
                }) 
            }
    }); 
}); 
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Hello, I have nearly 20 variables which are passed when form submitted. I have mentioned only 1 variable in my question to keep it short and clean. So please advise accordingly. Ty – K Ahir Jul 19 '20 at 13:28
  • @KAhir, no of variables doesn't matter If it's arbitrary data then use data attributes else use HTML elements logic remains the same. Note _Identifiers in HTML must be unique_ if you want to target individually then use class selector `.class` with .`.find()`. An example of quantity `` can be targetted using `$form.find('.qty').val()` – Satpal Jul 19 '20 at 14:10