1

I want to submit my form via Ajax. I have done it before but for some reason whenever I click submit it will always submit the form and refresh the page. I made a test function just to console log once submit button is pressed but that doesn't even work.

Once I can get the console log working without page refreshing then I can do the Ajax myself since I know how.

Here is my form (keep in mind Im only going to post one input here just for an example).

function submit_form(e) {
    e.preventDefault();
    console.log('working');
    return false;
};


   {!! form_open('myaccount/product_coupon/add',['id' => 'product_coupon_form', 'onsubmit'=> 'submit_form']) !!}

 Username <input type="text" name="username" class="form-control">

 <input type="submit" class="btn btn-primary" id="submit">

 </form>

I have also tried in javascript calling it by $('#submit').click(function()... but that still did nothing

Gilbert
  • 64
  • 7

1 Answers1

1

1st: be sure you include jquery

2nd: wrap your code in $(document).ready(function(){ //code here })

3rd: you can use form submit instead of submit button click

$(document).ready(function(){
     $('#product_coupon_form').on('submit' , function(e){
          submit_form(e);
     })
});
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • It works! Thank you! Do you know why mine didn't work when I called it? why do I need to call document ready before it – Gilbert Jun 15 '17 at 06:27
  • 1
    @Gilbert read https://stackoverflow.com/questions/6691454/why-wrap-code-into-document-ready and https://stackoverflow.com/questions/30894981/how-important-it-is-to-wrap-jquery-code-in-document-ready-function .. summery of all of this .. is the * the objects wouldn't exist because the DOM isn't loaded.* but with `$(document).ready(function(){` its check for document is loaded first – Mohamed-Yousef Jun 15 '17 at 06:30