简体   繁体   中英

AJAX Post not sending form data

I have the following AJAX POST below, for some reason looking at my logging (server side) the request it's sending is is blank {} not JSON data is sent. I have exhausted all possible server side issues this is a client side issue with the script not sending data. why?

bootstrap-wizard.js found here -> GitHub

My page code overrides the script submit:

<script src="{{ STATIC_URL }}js/bootstrap-wizard.js"></script>
<script type="text/javascript">
   $(function() {

       var options = {width:1000};
       var wizard = $("#some-wizard").wizard(options);

        $("#open-wizard").click(function() {
        wizard.show();
    });


wizard.on("submit", function(wizard) {

        $.ajax({
                  url: '/api/v1/rewards/campaigns/',
                  type: 'POST',
                  contentType: 'application/json; charset=UTF-8',
                  data: $('#wizard').serialize(),
                  beforeSend: function (request) {

                      request.setRequestHeader("X-CSRFToken", $('input[name="csrfmiddlewaretoken"]').val());
                  },

                  success: function(data, textStatus) {
                        wizard.submitSuccess(); // displays the success card
                        wizard.hideButtons(); // hides the next and back buttons
                        wizard.updateProgressBar(0); // sets the progress meter to 0

                      console.log('success');

                  },
                  error: function(errorThrown){
                     // data = JSON.parse(errorThrown.responseText);

                       wizard.submitError(); // display the error card
                       wizard.hideButtons(); // hides the next and back buttons


                      console.log(errorThrown);
                  }
              });



  });



   });



</script>

This is my form:

<form action="" method="post" class="form-horizontal" id="wizard" enctype="application/json" >
{% csrf_token %}

<div class="wizard" id="some-wizard">
   <h1>{% trans "Setup Wizard" %}</h1>


   <div class="wizard-card" data-cardname="card1">
      <h3>{% trans "General" %}</h3>

       etc, etc <=== all my form fields here

   </div>

serialize() returns key/value formatted URL encoded data (x-www-form-urlencoded), not JSON. If your server side requires JSON then you need to change your data parameter:

$.ajax({
    ...
    data : JSON.stringify({ input_a : 'value a', input_b : 'value b' }),
    ...
});

See this question for how to convert a form into JSON automatically.

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