Lluís Puig Ferrer
Lluís Puig Ferrer

Reputation: 1146

Laravel: Condition of controller inside Ajax call

First I will put the code here.

This is my ajax code:

//View para crear proyecto
$("#myFormProject").submit(function(e){
    e.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
        url:'/admin/projects/postUpload',
        type:'POST',
        data: formData,
        success: function(){
            $("#formcrearproyecto").fadeOut(1000);
            $("#formcreartraducciones").fadeIn(1000);
        },
        cache: false,
        contentType: false,
        processData: false
    });
    return false;
});

My controller function look like this:

public function storeProject(Request $request)
    {
    $clients = DB::table('clients')->orderBy('name','asc')->get();
    $projects = DB::table('projects')->get();
    $project = new Project();
    $project->slug = $request->input("slug");
    $project->order = DB::table('projects')
                  ->where('order', DB::raw("(select max(`order`) from projects)"))
                  ->first()
                  ->order + 1; 
    $project->public = 0;
    $imagen = getimagesize($request->file('pathheader'));
    $ancho = $imagen[0];
    $altura = $imagen[1];
    $maxancho = 1930;
    $minancho = 1910;
    $maxaltura = 822;
    $minaltura = 802;
    $imagen2 = getimagesize($request->file('pathhome'));
    $ancho2 = $imagen2[0];
    $altura2 = $imagen2[1];
    $maxancho2 = 778;
    $minancho2 = 358;
    $maxaltura2 = 355;
    $minaltura2 = 335;
    if ($ancho<$maxancho && $ancho>$minancho && $altura<$maxaltura && $altura>$minaltura &&
    $ancho2<$maxancho2 && $ancho2>$minancho2 && $altura2<$maxaltura2 && $altura2>$minaltura2){
    \Storage::disk('projects')->makeDirectory($project->slug);
    $project->pathheader = \Storage::disk('projects')->putFileAs($project->slug, $request->file('pathheader'),'header.jpg');
    $project->pathhome = \Storage::disk('projects')->putFileAs($project->slug, $request->file('pathhome'),'home.jpg');
    $project->save();
    File::put(resource_path('views/projects/').$project->slug.'.blade.php','');
    }
    else{
        Session::flash('warning','Las medidas de almenos una de las 2 imagenes no es la correcta.');
            return view('cms.public.views.projects.menu',['projects' => $projects, 'clients' => $clients]);
    }

}

The problem is when I submit a picture then don't enter in IF and go to ELSE equally make the fadeout and fadein.

How can I make a condition inside Ajax to check whether to enter in or not, and make fadeout and fadein or just show the session::flash?

Thanks a lot.

Upvotes: 0

Views: 1312

Answers (1)

Veshraj Joshi
Veshraj Joshi

Reputation: 3579

I think you can make use of json return type like below -

// this code is for backend
if($ancho2<$maxancho2 && $ancho2>$minancho2 && $altura2<$maxaltura2 && $altura2>$minaltura2)
{
  // your code here
   ......

   $project->save();
   File::put(resource_path('views/projects/').$project->slug.'.blade.php','');
   // returns json string to the client
   return json_encode(['stauts'=>'ok']);
}
else{
     $data = array('status' => 'error',
                   'warning' => 'Las medidas de almenos una de las 2 imagenes no es la correcta.');
      return json_encode($data);
}

Now you need to access this in client side in javascript..

 $("#myFormProject").submit(function(e){
    e.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
       url:'/admin/projects/postUpload',
       type:'POST',
       data: formData,
       success: function(responseText){
            // this will convert json string to json object
            $responseData = JSON.parse(responseText);
            if($responseData.status == 'ok')
            {
                 $("#formcrearproyecto").fadeOut(1000);
                 $("#formcreartraducciones").fadeIn(1000);
            }
            else if($responseData.status == 'error'){
                  alert('Handled error and the warning message is '+$responseData.warning);
             }
            else{
                alert('Error happened in backend,but not handled');
            }
       },
       cache: false,
       contentType: false,
        processData: false
    });
    return false;
});

Upvotes: 2

Related Questions