Home > Mobile >  form to target div with file upload
form to target div with file upload

Time:10-29

I currently have a form in which the results are returned into a targeted div. It works great. EXCEPT when my form includes an upload ( INPUT TYPE="FILE" NAME="PIC_UPLOAD" ), in which case it simply does not work. Any ideas on what I am missing? Here is the current (working) code

/* attach a submit handler to the form */
$("#testform").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get some values from elements on the page: */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post and put the results in a div */
  $.post(url, $("#testform").serialize(),
    function(data) {
      var content = data;
      $('#targetdiv').empty().append(content);

    }
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div id="the form">

  <form action="http://www.oil-soft.com/v3/testing/formtest_rec.mv" id="testform">

    <INPUT Type="hidden" NAME="func" VALUE="1004">
    <TEXTAREA NAME="NOTES" ROWS=4 COLS=34></TEXTAREA>
    <input type="submit" value="Submit">

</div>
<hr>
<div id="targetdiv"> results to go here </div>

CodePudding user response:

So, I was able to achieve POST'ing the form, with a file upload and target a div by switching to AJAX. See updated code:

<script>


    /* attach a submit handler to the form */
    $("#testform").submit(function(event) {

      /* stop form from submitting normally */
      event.preventDefault();

      var form_data = new FormData($('form')[0]);
        $.ajax({
            type: 'POST',
            url: 'url_to_file_to_process_upload.php',
            data: form_data,
            processData: false,
            contentType: false,
            dataType: "html",
            success: function (data) {
                $('#targetdiv').html(data);
            },
            error: function (xhr, status) {
                alert("Sorry, there was a problem!");
            },
            complete: function (xhr, status) {
                //$('#showresults').slideDown('slow')
            }
        });

    });

</script>

CodePudding user response:

I would suggest that you just use plain vanilla js instead of using jQuery...

Let HTML be the thing that describes how things should work and just make js a progressive enhancement. The site should work without js.
Often the best code is reusable code. so try writing your code a bit like

async function ajaxify (evt) {
  evt.preventDefault()
  const form = evt.target
  const fd = new FormData(form)
  const res = await fetch(form.action, { method: form.method, body: fd })
  const text = await res.text()
}

$("form").submit(ajaxify)

No specific js logic is necessary, works for more forms. easy to update, change and manipulate from HTML, and the js/css file can be more static hosted on some CDN

  • Related