freej17
freej17

Reputation: 371

How can I call my validate function before sending my ajax when a button is clicked?

Hello everyone I have a table that's dynamically generated from database. This is the table.

I have all the code that works fine,but I only need proper timing of execution 1) Check if all mandatory fields are populated on button click, if not don't send ajax. 2) When all mandatory fields are populated on button click then call ajax and send proper values to c# and later to database.

First I need to check if all mandatory fields are filled in(check Mandatory column(yes or no values):

$(function () {
              $("#myButton").on("click", function () {
                  // Loop all span elements with target class
                  $(".IDMandatory").each(function (i, el) {
                      // Skip spans which text is actually a number
                      if (!isNaN($(el).text())) {
                          return;
                      }

                      // Get the value
                      var val = $(el).text().toUpperCase();
                      var isRequired = (val === "TRUE") ? true :
                                       (val === "FALSE") ? false : undefined;

                      // Mark the textbox with required attribute
                      if (isRequired) {
                          // Find the form element
                          var target = $(el).parents("tr").find("input,select");

                          if (target.val()) {
                              return;

                          }
                          // Mark it with required attribute
                          target.prop("required", true);

                          // Just some styling
                          target.css("border", "1px solid red");

                      }
                  });
              })
          });

If not don't call ajax and send values. If all fields are populated then call ajax to send values to c#. This is the ajax code that takes values from filed and table and send's it to c# WebMethod and later to database.

 $(function () {

            $('#myButton').on('click', function () {



                var ddl = $('#MainContent_ddlBusinessCenter').val()

                var myCollection = [];

                $('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
                    var row = $(e);
                    myCollection.push({
                        label: valuefromType(row.find(row.find('td:eq(1)').children())),
                        opis: valuefromType(row.find(row.find('td:eq(3)').children()))
                    });

                });

                console.log(myCollection);
                function valuefromType(control) {
                    var type = $(control).prop('nodeName').toLowerCase();


                    switch (type) {
                        case "input":
                            return $(control).val();
                        case "span":
                            return $(control).text();
                        case "select":
                            ('Selected text:' + $('option:selected', control).text());
                            return $('option:selected', control).text();
                    }
                }
                var lvl = $('#MainContent_txtProductConstruction').val()
                if (lvl.length > 0) {
                    $.ajax({
                        type: "POST",
                        url: "NewProductConstruction.aspx/GetCollection",
                        data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",

                        success: function (response) {
                            if (parseInt(response.d) > 0)
                                alert("Saved successfully.");
                            else
                                alert("This object already exists in the database!");
                            console.log(response);
                            location.reload(true);
                        },
                        error: function (response) {
                            alert("Not Saved!");
                            console.log(response);
                            location.reload(true);
                        }
                    });
                }
                else {
                    alert("Please fill in the Product Construction field!")
                }
            });

        });

I need code to execute first mandatory fields and when they are all filled in then call ajax part of the code! Can anyone please help ! If you need more explanation just ask ! Thanks in advance !

Update Liam helped allot me but ajax is not working on button click.

function validate() {

    // Loop all span elements with target class
    $(".IDMandatory").each(function (i, el) {
        // Skip spans which text is actually a number
        if (!isNaN($(el).text())) {
            return;
        }

        // Get the value
        var val = $(el).text().toUpperCase();
        var isRequired = (val === "TRUE") ? true :
                         (val === "FALSE") ? false : undefined;

        // Mark the textbox with required attribute
        if (isRequired) {
            // Find the form element
            var target = $(el).parents("tr").find("input,select");

            if (target.val()) {
                return;

            }
            // Mark it with required attribute
            target.prop("required", true);

            // Just some styling
            target.css("border", "1px solid red");

        }
    });
}



function sendAjax() {
    var ddl = $('#MainContent_ddlBusinessCenter').val()

    var myCollection = [];

    $('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
        var row = $(e);
        myCollection.push({
            label: valuefromType(row.find(row.find('td:eq(1)').children())),
            opis: valuefromType(row.find(row.find('td:eq(3)').children()))
        });

    });

    console.log(myCollection);
    function valuefromType(control) {
        var type = $(control).prop('nodeName').toLowerCase();


        switch (type) {
            case "input":
                return $(control).val();
            case "span":
                return $(control).text();
            case "select":
                ('Selected text:' + $('option:selected', control).text());
                return $('option:selected', control).text();
        }
    }
    var lvl = $('#MainContent_txtProductConstruction').val()
    if (lvl.length > 0) {
        $.ajax({
            type: "POST",
            url: "NewProductConstruction.aspx/GetCollection",
            data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (response) {
                if (parseInt(response.d) > 0)
                    alert("Saved successfully.");
                else
                    alert("This object already exists in the database!");
                console.log(response);
                location.reload(true);
            },
            error: function (response) {
                alert("Not Saved!");
                console.log(response);
                location.reload(true);
            }
        });
    }
    else {
        alert("Please fill in the Product Construction field!")
    }
}


$(function () {
    $('#myButton').on('click', function () {
        if (validate()){
            sendAjax();
        }
    })



});

Upvotes: 0

Views: 100

Answers (1)

Liam
Liam

Reputation: 29714

If you want to execute these in order why don't you just add one click handler that calls each function:

function validate(){
    // Loop all span elements with target class
    $(".IDMandatory").each(function (i, el) {
       // Skip spans which text is actually a number
      ....etc.
}

function sendAjax(){
   var ddl = $('#MainContent_ddlBusinessCenter').val()
   var myCollection = [];
   ..etc.
}

$(function () {
     $('#myButton').on('click', function () {
        validate();
        sendAjax();
     }
});

Seems it would make sense if your validate function actually returns true or false if your form was valid too. then you could:

$(function () {
     $('#myButton').on('click', function () {
        if (validate()){
           sendAjax();
        }
     }
});

I'm not really sure why your doing this:

// Mark it with required attribute
target.prop("required", true);

when you validate? If you just add this into your HTML it will handle required. adding it here seems a bit strange. I'm guessing your not actually submitting the form? It'd make more sense to add the validation message yourself rather than use this attribute.

Your codes not working because your not returning anything from your validate function. It's not 100% clear to me what is valid and what isn't so I can't alter this. But you need to add return true; for valid cases and return false;for invalid cases for the if statement if (validate()){ to work.

Upvotes: 1

Related Questions