0

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

Syns
  • 127
  • 13

4 Answers4

0

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>

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

Riz-waan
  • 603
  • 3
  • 13
0

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....
});
RonyLoud
  • 2,408
  • 2
  • 20
  • 25
Ikhsan
  • 51
  • 1
  • 11
  • done, but it still load a new blank page with the array result. – Syns Nov 24 '17 at 04:10
  • update: after I declared the var load_report function on the construct, now the form not submitted (with e.preventDefault), but the result won't show. – Syns Nov 24 '17 at 04:15
  • try to remove your property method and action on your
    tag. so it would be just
    – Ikhsan Nov 24 '17 at 07:03
0

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

vichu
  • 353
  • 2
  • 10
  • I tried that, but the form won't pass the data, there's no form-data in the debugger. but if I remove this event.preventDefault(); , the data showing in new tab not in the div, same as before. :( – Syns Nov 24 '17 at 06:30
0

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');
}
pidizzle
  • 720
  • 6
  • 12
  • I try both solution but it still load the new blank page with array result instead on the div. – Syns Nov 24 '17 at 04:09
  • update: I declare the var load_report function on the construct, now the form not submitted (with e.preventDefault), but the result won't show. – Syns Nov 24 '17 at 04:14
  • @Syns Make sure you are making the request to the server. Also, what does `Template.dodo()` do? – pidizzle Nov 24 '17 at 04:17
  • Template.dodo() is just a js table template for the result array. yep I put the variable into the input textbox but it does nothing when I submitted. I put the e.preventDefault right after $("#report").click(function(), but if I remove it it shows the result even in the new page. – Syns Nov 24 '17 at 04:22
  • @Syns Are there any errors in your debugger? Also did you make sure to add `e` as a parameter in click(function(`e`){? Do yo know how to look at your network traffic with your browser debugger? Also is `#report` a button? – pidizzle Nov 24 '17 at 04:24
  • I check the console, network and didn't see any error, but in the network when form submitted(load_report), I don't see any form data posted, only (General, Response header, Request header). – Syns Nov 24 '17 at 04:32
  • @Syns Ok. You don't need to have the `$("#report").click` part wrapped by the load_report function. The `$('#report').click` part will fire when you click on the html element with the id `report`. – pidizzle Nov 24 '17 at 04:35
  • @Syns Keep in mind that this method does not even require for there to be form tags in the html, I would just replace them with a `div`. Also change the `$.get()` to a `$.post()`. More info about `.post()` [here](https://api.jquery.com/jquery.post/) – pidizzle Nov 24 '17 at 04:44
  • Alright I remove the `$("#report").click` part, but still won't fire unless the e.preventDefault removed otherwise it showing in the new page again, it's there something wrong with my e.preventDefault?. I don't quite get it with jquery.post, sorry :( . – Syns Nov 24 '17 at 06:28
  • @Syns No worries! Update your answer with your new code so I can see better whats going on. You could even but your code in a jsfiddle if you wanted. – pidizzle Nov 24 '17 at 06:50
  • I create new calling function above, please check it :) – Syns Nov 24 '17 at 07:08
  • Ok cool. Could you add another picture of the data you get back from the api? – pidizzle Nov 24 '17 at 07:22
  • Instead of `$("xreport").html()`, use `$("xreport").append(output)`. – pidizzle Nov 24 '17 at 07:43
  • done, still same. a correction from what I stated earlier: actually `console.log(output)` is not showing anything in the console tab, it's only on network tab that show correctly (just like in the picture). – Syns Nov 24 '17 at 07:54
  • `console.log` the argument `o` in the `$.post` callback and let me know if it returns the data. – pidizzle Nov 24 '17 at 08:00
  • In your loop you need to replace `o.length` and `o[i]` with `o.data.length` and `o.data[i]` – pidizzle Nov 24 '17 at 08:19
  • yaaayy that's it, finally it's working now, I wish I can upvote this answer but not enough rep sorry. anyway thank you so much :) – Syns Nov 24 '17 at 08:23
  • @Syns Yes! Great. Glad to help! You should be able to make this the accepted answer, which would be nice. – pidizzle Nov 24 '17 at 08:25