Home > Net >  Processing formData from alpine js form
Processing formData from alpine js form

Time:10-31

I have the following html

<div  x-data="pageState()" x-init="mounted()">
<form method="post" enctype="multipart/form-data" @submit.prevent="postFormData()">
<div ><label>First Name</label><input x-model="form.firstname" name="firstname" type="text" required  /></div>
<div ><label>Second Name</label><input x-model="form.secondname" name="secondname" type="text" required /></div>
<div ><label>Images</label><input  name="images" type="file" x-on:change="selectFile($event)" accept="image/png, image/jpg, image/jpeg" multiple required /></div>
<button >Submit Form Data</button>
</form>
</div>

and alpine js code

<script>
function pageState(){
           return {
               form: {
                    firstname: '',
                    secondname: '',
                },

                selectFile(event) {
                this.form.images = event.target.files[0];
                 },
            

                postFormData(){
                  
                  //Create an instance of FormData
                const data = new FormData()
                let url = 'http://localhost:8000/alpine_form'
                
                // Append the form object data by mapping through them
                Object.keys(this.form).map((key, index) => {
                    data.append(key, this.form[key])
                });

                
                fetch(url, {
                        method: 'POST',
                        /**
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        */
                        body: data
                    })
                    .then(response => {
                        console.log(response);
                    })
                    .finally(() => {
                        
                    });
                    
                    
                /**
                axios.post('https://eot1ip4i6xwine.m.pipedream.net', {
                    firstname: this.firstname,
                    secondname: this.secondname
                  })
                  .then(function (response) {
                    console.log(response);
                  })
                  .catch(function (error) {
                    console.log(error);
                  });
                  */
                },
                
                mounted(){
                this.$watch('form.firstname', (value, oldValue) => this.form.firstname = value);
                this.$watch('form.firstname', (value, oldValue) => console.log(value, oldValue));
                console.log('mounted');
                }
           }
       }

</script>

In the backend i have this laravel code

public function alpine_form(Request $request){
        
        header('Access-Control-Allow-Origin: *');

        header('Access-Control-Allow-Methods: GET, POST');

        header("Access-Control-Allow-Headers: X-Requested-With");

        
        $data = $request->all();
        $firstname = $data['firstname'];
        $secondname = $data['secondname'];
        $images = $data['images'];
        $ai = '';
        
        $uploaded_images_array = [];
         
            //images
        
        if($request->hasfile('images'))
            {
        
            foreach($request->file('images') as $fil)
            {
                $nam = mt_rand().uniqid().'.'.$fil->extension();
                $fil->move(public_path().'/uploads/', $nam);  
                $uploaded_images_array[] = $nam;  
            }
            
        
        $ai = json_encode($uploaded_images_array);
    
            DB::table('form')->insert(
             array(
                    'firstname'     => $firstname, 
                    'secondname'   => $secondname,
                    'images'   =>  $ai
             )
        );
        
            }
            
        

    
    }

I am able to receive firstname and secondname but he images array is always empty when i insert the data into the database. Am i acquiring the images posted correctly?

CodePudding user response:

I appended my images like this

postFormData(){
                  
                  //Create an instance of FormData
                const data = new FormData()
                data.append('firstname', this.form.firstname);
                data.append('secondname', this.form.secondname);
                
                let input_file = document.querySelector('input[type="file"]')

                Array.from(input_file.files).forEach((f) => {
                    data.append('images[]', f)
                })

                let url = 'http://localhost:8000/alpine_form'

                
                fetch(url, {
                        method: 'POST',
                        /**
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        */
                        body: data
                    })
                    .then(response => {
                        console.log(response);
                    })
                    .finally(() => {
                        
                    });
                    
            
                },

and no other modification was necessary.

  • Related