简体   繁体   中英

Sending data from ajax to controller action

I create ajax request where I added images using FormData. It's look:

function handleForm(e) {
    var data = new FormData();
    for(var i=0, len=storedFiles.length; i<len; i++) {
        data.append('files['+i+']', storedFiles[i]);
    }
   $.ajax({
       url:'site/images',
       type:'POST',
       processData: false,
       contentType:false,
       data:data,
       success: function (response) {
           console.log(response);
       }
   })
}

and handling when

 $("#myForm").on("submit", handleForm);

myForm is id of all my form. This form go to action site/form but for ajax request I create site/image action where I can get images. I want to send both of them when form is sending. But problem is when I'm trying to put my images to site/form action, I need to put it then because site/form handle different logic(saving form_id from Form model to Images model, attaching that images to mail and else). How can I solve it? I know how get images when form send request to one action, and I of course can get them from UploadedFile::getInstances() with model and model attribute. But now I havent model and else.

Try This

var storedFiles= $("#upload");
if (storedFiles.get(0) != undefined) {
            for (i = 0; i < storedFiles.get(0).files.length; i++) {
                data.append("files['+i+']", storedFiles.get(0).files[i]);
            }
        }

I am not sure that my concept is that what you mean.. but I think You should first save images in action site/image to images models and save it with special filed - temporary ID, which will be the same for both actions and models (form model and images model). The temporary ID should be generated when form is rendered. Then after succesfull save images and then succesfull save form model you should replace temporary ID in images models to proper ID related to saved form model. If form model will be invalid and cannot be saved, you should delete images models with tmp ID and repeat whole process.

Try multipart/form-data as content type when constructing the AJAX request.

What you asked for is a bit wrong, AJAX calls are non-blocking, you can send them at the same time, but you don't know which one will get faster on the server, if your site/form relies on site/image , then submit data to site/image first, after the custom logic is applied (images being uploaded on the server and such) and the execution is successful, submit the data meant to serve site/form on success , otherwise, spit an error.

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