Melannie
Melannie

Reputation: 44

Sweetalert success message appears even if there's an error

I'm trying to upload a form, if everything is correct it shows a sweetalert success message (this works fine), but if there's an error (Ex. image is too big) it should show the error. The problem is that when there's an error the success message appears an then the error is displayed.

Additional information: *The database works properly, if there are no error it inserts the new register otherwise it doesn't. *I'm using laravel 5.4.

My controller:

<?php

namespace App\Http\Controllers;

use Request;
use App\Programa;
use App;

class ProgramaController extends Controller{

  public function index(){
    return view('programa.create');
  }


  public function store(){

    $this->validate(request(), [

        'titulo' => 'required',
        'poster' => 'required|image|image_size:<=720',
    ]);

    $programa = new Programa;

    $programa->titulo = request('titulo');
    $name=request()->file('poster'). '.' . request()->file('poster')->getClientOriginalExtension();
    $programa->poster = request()->file('poster')->move('./uploads/', $name);

    $programa->save();

    return redirect('/');
  }

}

My Form

<form method="POST" action="/crearPrograma" enctype="multipart/form-data" onsubmit='exito(this.id)'>

    {{ csrf_field() }}

    <div class="form-control">

        <label for="titulo">Título</label>

        <input type="varchar" class="form-control" id="titulo" name="titulo" placeholder="DoQu" required>

    </div>

    <hr>

    <div class="form-control-file">

        <input type="file" class="form-control-file" id="poster" name="poster" aria-describedby="fileHelp" required accept="image/*" >

        <small id="fileHelp" class="form-text text-muted">Póster</small>

    </div>

    <hr>



    <button type="submit" class="btn btn-primary">Crear</button>

    @include("layouts.errors")

</form>

My js

<script>
  function exito(id){

    swal({
      title: "Guardado",
      text: "Se ha guardado correctamente",
      type: "success",
      timer: 2000,
      showConfirmButton: false
    });

  }
</script>

Upvotes: 0

Views: 1372

Answers (1)

Zolbayar
Zolbayar

Reputation: 936

Check your the file size in exito. To get it:

//filesize would be in bytes
var filesize = document.getElementById("poster").files[0].size; 

Then:

function exito(id){
  var filesize = document.getElementById("poster").files[0].size;

  if(filesize <= 1000000){
    swal({
      title: "Guardado",
      text: "Se ha guardado correctamente",
      type: "success",
      timer: 2000,
      showConfirmButton: false
    });
  }else{
    //show your error here
  }
}

Upvotes: 1

Related Questions