1

I want to send post request with ajax to controller in laravel. The ajax request send two input arguments and I want controller to find the column in the database with the first argument and then to set the name attribute with the second input argument. But I have this error message Creating default object from empty value

Ajax function:

$('#saveUserProfile').on('click', function () {

                var $finduser = $('input[name=findUser]').val();  
                var $name = $('input[name=userprofilename]').val();


                    $.ajax({
                        type:"POST",
                        url:'/code/task1/public/updateUser',
                        data: {
                             'name' : $name,
                             'finduser' : $finduser,
                            // 'email' : $email,
                         },
                        success:function(data){

                            $("#input1").val(data[0].name);

                        }

                    });
         }); 

and the function in my controller

public function updateUser(Request $request){

        $return_array = array();

        $findUserInput = $request->get('finduser');

        $user = User::where('name',$findUserInput) -> first();

        $user->name = $request->get('name');

        $user->save();

        $data =  DB::select("SELECT * FROM users where name='$findUserInput'");


        if(count($data) > 0){
            foreach($data as $da){
                $return_array[] = $da;
            } 
        }

        return $return_array;

    }

Update: I also make ajax function and controller for finding user which is working good.

ajax function:

$('#buttonFindUser').on('click', function () {
                  var $name = $('input[name=findUser]').val();

                    $.ajax({
                        type:"GET",
                        url:'/code/task1/public/findUser',
                        data: {
                             'name' : $name,
                         },
                        success:function(data){


                            $("#input1").val(data[0].name);
                            $("#input2").val(data[0].email);
                            $("#input3").val(data[0].created_at);

                        }

                    });
         });

Function in my controller:

public function findUser(Request $request){

        $return_array = array();

        $findUserInput = $request->get('name');

        $data =  DB::select("SELECT * FROM users where name='$findUserInput'");


        if(count($data) > 0){
            foreach($data as $da){
                $return_array[] = $da;
            } 
        }

        return $return_array;

    }

Any ideas?

Devmasta
  • 513
  • 2
  • 14
  • 38

3 Answers3

1

But I have this error message Creating default object from empty value

What's happening is that you are trying to save a user that doesn't exist. You need to check if the $user is null or not in your controller. Right now, the user couldn't be found with the provided name so $user becomes null.

So, you can modify your code to do a null check on $user like so:

public function updateUser(Request $request){

    $return_array = array();

    $findUserInput = $request->get('finduser');

    $user = User::where('name',$findUserInput) -> first();

    if(!$user)
        return response()->json(['status'=>false,'Description' => 'User could not be found.']);

    $user->name = $request->get('name');

    $user->save();

    $data =  DB::select("SELECT * FROM users where name='$findUserInput'");


    if(count($data) > 0){
        foreach($data as $da){
            $return_array[] = $da;
        } 
    }

    return $return_array;

}

Here's the null check:

if(!$user)
    return response()->json(['status'=>false,'Description' => 'User could not be found.']);

When we don't have a valid user, we just reply back with a json response stating that it couldn't be found.

Update:

Seeing as your input is not being retrieved in the controller, you need to make some changes in JS:

First, you are doing a post request and I cannot see a CSRF token. To add it, follow this answer: https://stackoverflow.com/a/37582060/6270112

So, your data will now become:

data: '_token=' + $('#token').val() + '&name=' + $name + '&finduser=' + $finduser

Also, as aleksejjj mentioned, you need to fix your jquery selectors as well. So, your existing selectors:

var $finduser = $('input[name=findUser]').val();  
var $name = $('input[name=userprofilename]').val();

will become:

var $finduser = $('input[name^="findUser"]').val();  
var $name = $('input[name^="userprofilename"]').val();

Next, in your controller you need to replace $request->get(...) with $request->input(...).

$findUserInput = $request->get('finduser');

will become

$findUserInput = $request->input('finduser');

and repeat the same with the name field as well.

Community
  • 1
  • 1
bytesarelife
  • 404
  • 3
  • 10
  • Yes I'm getting back the json response User could not be found, but the user with that input already exist in the database...thats the problem – Devmasta Oct 25 '16 at 12:16
  • Can you do a `dd($request->get('finduser'));` and post the results? – bytesarelife Oct 25 '16 at 12:17
  • @epowah Check your jQuery selectors. You need `$('input[name="findUser"]').val()` – aleksejjj Oct 25 '16 at 12:25
  • Also, have you disabled CSRF token verification? Because, I can see you are sending a post request. – bytesarelife Oct 25 '16 at 12:26
  • @bytesarelife Wow errors number will soon exceed the number of lines of code:) – aleksejjj Oct 25 '16 at 12:29
  • @aleksejjj i check twice the jquery selectors and everything is okey, I don't know whats the mistake – Devmasta Oct 25 '16 at 12:33
  • @bytesarelife how to disable CSRF token verification? – Devmasta Oct 25 '16 at 12:33
  • @bytesarelife I try that and nothing new, again the same error, i update my question if you can look – Devmasta Oct 25 '16 at 12:50
  • You still have to change the jQuery selector. The problem is with the input not being sent via the ajax request. – bytesarelife Oct 25 '16 at 12:58
  • The jQuery selectors are working fine, I already check them all, the problem is something with the ajax call. As I read something, the problem may be with csrf_token, but I don't know how to check that.. – Devmasta Oct 26 '16 at 08:57
  • I found the answer, the problem was with the ajax setup, i have to change `$.ajaxSetup({ headers:{ 'X-CSRF-TOKEN' : $('meta[name="csft-token"]').attr('content') } });` to this `$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('[name="_token"]').val() }' });` – Devmasta Oct 26 '16 at 09:14
  • Well, that's what my update was. Your CSRF token was missing and $.ajax call should've worked fine the way I mentioned (I use it like that everyday). – bytesarelife Oct 26 '16 at 14:06
0

You need to check your user exist

$user = User::where('name', $findUserInput)->first();

if($user)
{
    $user->name = $request->get('name');

    $user->save();
}
aleksejjj
  • 1,715
  • 10
  • 21
-2

change this code

$user = User::where('name',$findUserInput) -> first();

to

$user = User::where('name','=',$findUserInput) -> first();

I hope this will work. :)

Sudhanshu sharma
  • 1,917
  • 3
  • 20
  • 29