“Laravel Display Validasi Kesalahan Ajax” Kode Jawaban

Laravel Display Validasi Kesalahan Ajax

// php
public function store(Request $request)
{
  	$validator = Validator::make( $request->all(),[
            'first_name' => 'string',
            'last_name' => 'string',
            'phone_number' => ['string', 'max:14'],
            'email' => 'email'
      ]);
        
      if($validator->fails())
        {
            $response = "<div class='alert alert-danger'><ul>";
            foreach($validator->errors()->all() as $error)
            {
              $response .= "<li> {$error}</li>";  
            }
            $response .= "</ul></div>";
            return response()->json([
                'message' => $response
            ], 201);
        }
  
  // no errors
  //continue with your logic
}

// javascript (jQuery)
$.ajax({
  url: 'your_backend_url',
  type: 'POST/PUT',
  data: request_data, // maybe $(this).serializeArray()
  beforeSend: () => {
    // any stuff that you would like to do before sending the request,maybe showing a loader
  },
  success: (response, responseText, xhr) => {
     if(xhr.status === 201)
      {
        // put errors in some element above or below the form
        return $(".errors").html(response.message)
      }
    // clear previous errors
    $(".errors").html("");
    // success stuff here
    }
});
Usher Godwin

Laravel Return Validasi Kesalahan Ajax

public function testAjax(Request $request)
  {
    $name = $request->input('name');
    $validator = Validator::make($request->all(), ['name' => 'required']);

    if ($validator->fails()){
        $errors = $validator->errors();
        echo $errors;
    }
    else{
      echo "welcome ". $name;
    }

  }
Motionless Manx

Jawaban yang mirip dengan “Laravel Display Validasi Kesalahan Ajax”

Pertanyaan yang mirip dengan “Laravel Display Validasi Kesalahan Ajax”

Lebih banyak jawaban terkait untuk “Laravel Display Validasi Kesalahan Ajax” di PHP

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya