Edama
Edama

Reputation: 15

how to call post after ajax done

I would like to call form submit button after done if ajax called.
My page has two button.
One is upload image by ajax.
Another one is submit button.


    function upload(data){
        console.log(upload start);
        $.ajax({
        type: "POST",
        url: "imagestore",
        data: data,
        timeout: 3000
        }).done(function(data){
            console.log('upload finish');
        }).faile(function(){
        });
    }
    
    function submit(){
        console.log('submit start');
        var form = document.createElement('form');
        form.setAttribute('method', 'post');
        form.setAttribute('action', '/nextpage');
        form.submit();
    }

If user use upload button just before submit button. console log is this.

upload start
submit start

Image is not store in server.

If user use upload button quite a while ago, it is no problem.

upload start
upload finish
submit start

how is the best way for waiting finish upload function.

Upvotes: 0

Views: 347

Answers (2)

steven7mwesigwa
steven7mwesigwa

Reputation: 6710

You could as well make your life easier by using a library that flawlessly handles the file upload(s) right before the other main form data is submitted.

Easy File Uploading With JavaScript | FilePond

Github filepond

Add the multiple attribute to a file input to create a multi-file drop area.

Limit the maximum amount of files with the data-max-files attribute. Drop an image and FilePond will render a quick preview. It'll also correct mobile photo orientation info.

A JavaScript library that can upload anything you throw at it, optimizes images for faster uploads, and offers a great, accessible, silky smooth user experience.

enter image description here

In a nutshell,

  1. Install filepond.
    npm install filepond
  2. Import the library into your project.
import "filepond/dist/filepond.min.css";
import * as FilePond from "filepond";

// Create a file(s) upload component.
const $filepond = $("#filepond-input");

FilePond.create($filepond.get(0), {
    multiple: false, // Change to <true> for multiple file uploads.
    name: "images", // The element 'name' sent to server.
    required: true,
})

// Define the server(backend) routes that will
// receive the respective requests sent by Filepond.
FilePond.setOptions({
    server: {

    /*This will be the 'server' route that will
    * receive/process the file(s).
    * This happens when a user uploads the file(s).
    * The request will include the 'images' request parameter
    * with  uploaded file(s) as it's value.
    * The 'server' route must respond/return with a unique identifier(s)
    * for the saved/processed file(s). i.e a file_id(s).
    * */
        process: {
            url: `/imagestore`,
            method: "POST",
            onerror: $error => console.log($error)
        },

    /*This will be the 'server' route that will
    *receive the request to delete the file(s).
    * It will essentially receive a 'request payload'
    * containing the unique file identifier(s) to be deleted
    * from the server.
    * This happens when a user clicks the ❌ icon in Filepond's
    * User interface.
    * You can use this unique file identifier(s) to pick out
    * the resource(file(s)) to be deleted on the server.
    * The 'server' route may respond/return with a success/error
    * response depending on how the deletion process goes.
    * */
        revert: {
            url: `/imagerevert`,
            method: "DELETE",
            onerror: $error => console.log($error)
        }
    }
});


// Handle main form submission.
// Equivalent to your submit function.
const $submitBtn = $("#submit-form-btn");
const $form = $("#form");

$submitBtn.click(function (e) {
    e.preventDefault();

    $.ajax({
        type: $form.attr("method"),
        url: $form.attr("action"),
        data: $form.serializeArray(),
        success: function ($response) {
            // Handle success. i.e show success message.
            // alert("Successful");
        },
        error: $error => console.log($error)
    });
});


  1. Define your regular HTML form.
<form id="form" method="POST" action="/nextpage">
    <input required type="file" id="filepond-input" name="images"/>
    <!--Other form elements here.-->
    <!--Other form elements here.-->
    <button type="submit" id="submit-form-btn" class="btn btn-primary">Submit</button>
</form>

The main form submit server route /nextpage in this case will receive the rest of the form input elements normally.

In addition, it will receive images in this case as a request parameter key and a request payload with the unique file identifier(s) previously sent by your process route /imagestore as the request parameter value(s).

You may then save the file path(s) to a database or do something with the file(s) depending on your use case.

Upvotes: 0

Wazeed
Wazeed

Reputation: 1280

It is unclear from the provided details, whether it is a single image file upload per form, or there is a chance of multiple image files. Below is one of the approach to process submit after the image(s) are uploaded successfully.

  • Change function upload(data) to return ajax promise.
function upload(data) {
    console.log('upload start');
    return $.ajax({
        type: "POST",
        url: "imagestore",
        data: data,
        timeout: 3000
    });
}
  • Define a function safeSubmit() which uploads unprocessed image file(s) one after another, and finally process form submit.
function safeSubmit() {
    var unprocessed_file_datas = [/* Array of unprocessed file uploads, get this from the form */];
    var processing_index = 0, processing_length = unprocessed_file_datas.length;
    if (processing_length > 0) {
        function safeUpload() {
            return upload(unprocessed_file_datas[processing_index]).then(() => {
                processing_index++;
                return processing_index < processing_length ? safeUpload() : 'all files uploaded';
            });
        }
        safeUpload()
            .then(function () { submit(); })
            .fail(function (error) { console.log(error); });
    } else {
        submit();
    }
}

Now use safeSubmit() function for submit action button of form.

Upvotes: 0

Related Questions