Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Ajax request in pug template?

I would like to send Ajax request in pug template file.

form#payment-form()
  section
    label(for="amount")
      input#amount(name="amount" type="tel" min="1" placeholder="Amount"                         value="10")
script(src="scripts/jquery.js")
script.
  (function () {
    var amount = $('#amount').val();
     $.ajax({
      type: "POST",
      url: "/posturl",
      data: {'amount':amount},
      success: function(){},
      dataType: 'json'
    });
  })()

But it doesn't work, how to do it? I want to know how to send ajax request in embeded javascript of pug file

like image 204
Nomura Nori Avatar asked Feb 05 '23 22:02

Nomura Nori


1 Answers

To me there seems to be two issues

  1. You have put unnecessary tabs in your function under (function (){
  2. You need to use document.ready to ensure that HTML content is ready. You can avoid this if you don't really care for DOM once you have the response

check a working example below

doctype html
html
  head
    script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js')
    script.
      $(document).ready(function(){
      $.ajax({url: "demo_test.txt", success: function(result){
      $("#div1").html(result);
      }});
      });
  body
    #div1
      h2 Let jQuery AJAX Change This Text
like image 79
S4beR Avatar answered Feb 07 '23 11:02

S4beR