简体   繁体   中英

JS: Calling function on Submit

Hello everyone I'm still new to JS, so I want to ask about calling a function when form is submitted.

[update] Form

<div id="dashboard-side">

    <form id="report" class="form-horizontal" method="post" action="<?= site_url('api/load_report') ?>"> <!-- onsubmit="location.reload()" -->            
        <fieldset>
            <div class="control-group center_div">                    
                <label class="control-label">Sales Name</label>                    
                <div class="controls">
                    <input type="text" name="sales_name" class="form-control input-xlarge txt-up" value="<?php echo set_value('cust_name'); ?>" placeholder="Enter Customer Name" style="height: 30px;"/>                       
                </div>
            </div>

            <div class="control-group center_div">
                <div class="controls form-inline">
                    <input id="get_report" type="submit" class="btn btn-success btn-inline " value="Get Report" style="width:110px; margin-left: -155px;"/>
                </div>  
            </div>                
            <table border="1" width="100%" style="background-color: #dfe8f6;">
                <tr>
                    <td width="154px"><strong>Customer Name</strong></td><td width="128px"><strong>Activity</strong></td>
                    <td width="244px"><strong>Detail</strong></td><td width="141px"><strong>Start Time</strong></td>
                    <td width="142px"><strong>Finish Time</strong></td><td width="39px" style="text-align:center"><strong>Note</strong></td>
                    <td style="margin-left: 50px"><strong>Action</strong></td>   
                </tr>
            </table>
            <!------------------------------------------------------------------------------------->               
            <div id="xreport" class="table-hover" style="background-color: #EAF2F5"></div>


        </fieldset>
    </form>
    </div>

Controller

public function load_report() {

    $this->db->where('user_id', $this->input->post('sales_name'));

    $query = $this->db->get('activity');
    $result = $query->result_array();
    $this->output->set_output(json_encode($result));  }

JS

var load_report = function() {
    $.get('api/load_report', function(o){

        var output = '';            
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }            
        $("#xreport").html(output);
    }, 'json');
};

If I call the function on form load it works fine, but I want to call it on form submit, how to do that?

Here is what I tried

var load_report = function () {
    $("#report").submit(function(){
     $.get('api/load_report', function(o){            
        var output = '';            
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }            
        $("#xreport").html(output);
    }, 'json');
});
};

Instead of assigning the array into my #div, it shows the array data in the new blank tab like this: my current result so far

any help would be appreciated, thanks.

Update: New calling function

  var load_report = function () {
    $("#report").submit(function (evt) {
        evt.preventDefault();
        var url = $(this).attr('action');
        var postData = $(this).serialize();

        $.post(url, postData, function (o) {
            if (o.result == 1) {
                var output = '';
                Result.success('Clocked-in');
                for (var i = 0; i < o.length; i++) {
                    output += Template.dodo(o[i]); //this data[0] taken from array in api/load_report
                    console.log(output);
                    $("#xreport").html(output);
                }
            } else {
                Result.error(o.error);
                console.log(o.error);
            }
        }, 'json');
    });
};

with this new calling function I'm able to retrieve data from api/load_report without getting stuck on e.preventDefault or even open a new tab, I console.log and the result show correctly in the console, but it doesn't show on the div somehow.

my template.js (if needed)

this.dodo = function(obj){
    var output ='';                     
    output +='<table border=1, width=100%, style="margin-left: 0%"';
    output += '<tr>';
    output += '<td width=120px>' + obj.user_id + '</td>';
    output += '<td width=120px>' + obj.cust_name + '</td>';
    output += '<td width=100px>' + obj.act_type + '</td>';
    output += '<td width=190px>' + obj.act_detail + '</td>';
    output += '<td width=110px>' + obj.date_added + '</td>';
    output += '<td width=110px>' + obj.date_modified + '</td>';         
    output += '<td style="text-align:center" width=30px>' + obj.act_notes + '</td>';
    output += '</tr>';        
    output +='</table>';        
    output += '</div>';        
    return output;
};

Result (note, user_id = form.sales_name) result preview

You could alway do the following:

 function myFunction() { alert("Hello! I am an alert box! in a function"); } 
 <form> <input type="text" /> <input type="submit" value="submit" onclick="return myFunction();"/> </form> 

PS This question might be answered in this question already, add onclick function to a submit button

Try to prevent form to get submit by using preventDefault()

$("#report").submit(function(e){ //add param "e"
     e.preventDefault(); //to prevent form to submit
     //further code....
});

Ok just try

function mysubmit(){
     $.get('api/load_report', function(o){            
        var output = '';            
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }            
        $("#xreport").html(output);
    }, 'json');
}

as your script and

<form id="report" class="form-horizontal" onsubmit="event.preventDefault(); mysubmit();" method="post" action="<?= site_url('api/load_report') ?>">

as your form

First off, I would advise against using onclick or onsubmit directly on the dom like so.

<form onsubmit="myFunction();"></form>

The biggest reason for me is that it negatively impacts readability and sometimes even future maintenance of the project . It is nice to keep html and javascript separate unless you are using a framework that provides templating features/functionality such as angularjs.

Another big one is that you can only have one in-line event present and it is easy to accidentally overwrite, which can lead to confusing bugs.

The reason it is going to a new tab is because of the .submit() . This will call your function, but then proceed with internal jQuery event handling which includes refreshing the page. There are two solutions I see most viable here.

1st Solution:

Add a event.preventDefault(); at the start of your function to stop jQuery from refreshing your page.

$("#report").submit(function(e) {
      e.preventDefault();
 });

2nd Solution (Likely better):

You are making an ajax call with $.get(...) . You could add an event listener on a button (probably on the button used to submit the form) that fires your ajax call. Here is an example that assumes the submit button has the id of loadData .

$("#loadData").click(function(){
   $.get('api/load_report', function(o){            
      var output = '';            
      for (var i = 0; i < o.length; i++){
          output += Template.dodo(o[i]);
      }            
      $("#xreport").html(output);
  }, 'json');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM