Home > Software design >  when sent data via Ajax to a Controller in Laravel the data is null
when sent data via Ajax to a Controller in Laravel the data is null

Time:11-25

I have used Ajax to sent data to the controller, unfortunately when I retrieve data it's empty nothing is sent. although it does give me the data when I get it via JQuery before it's sent.

below is the code of Ajax -------------------

 $.ajax({
    url: $('form#add-user-form').attr('action'),
    method: $('form#add-user-form').attr('method'),
    data: form.serializeArray(),
    processData: false,
    dataType: 'json',
    contentType: false,
    beforeSend:function(){
            $(form).find('span.error-text').text('');
            alert('working'   "   "   user['fname']);
    },
    success:function(data){
        
        if (data.code == 0 ){
            $.each (data.error, function(prefix, value){
                alert(prefix   '   '   value[0]);
                $(form).find('span.' prefix '_error').text(value[0]);
            });
            alert('complete');
        }else {
            
            $(form)[0].reset();
            alert(data.msg)
        }

    }

 });

-----------------Laravel Controller method which receives the data ----------------

  public function store(Request $request)
{
 
       $validator = \Validator::make($request -> all(), ['fname' => 'required|min:5|max:25', 
                    'lname' => 'required|min:5|max:25',
                    'email' => 'required|email|unique:users', 
                    'pass' => 'required|min:8|max:20|', 
                    'confirm-pass' => 'required|min:8|max:20'
                    ]);

if (!$validator -> passes() ){
    return response()->json(['code'=> 0, 'error'=> $validator->errors()->toArray(), $request->fname]);
}else {
        $user = new users();
        $user -> name = $request -> fname ;
        $user -> email = $request -> email ;
        $user -> password = $request -> pass;
        $query = $user -> save();
        if ( !$query ){
            return response() -> json(['code'=> 0, 'msg' => 'something went wrong']);
        }else {
            return response() -> json(['code' => 1, 'msg' => 'users has been successfully added']);
        }
}

}

CodePudding user response:

I have found the answer, instead of using $.ajax method, I replaced it with $.post function of JQuery and everything is working perfect.

  • Related