melx's avatar
Level 4

POST data to controller Using Ajax

I want to pass id from my blade form and store that id to another table,

am try like this but get this error

my blade form

                 <td>
                  <meta name="csrf-token" content="{{ csrf_token() }}">
                  <a href="#" data-id="{{$dt->id}}" id="add_btn" class="btn btn-sm btn-default add_btn ">Issue</i> 
                  </a> </td>
              </tr>
              @endforeach
           </tbody>

my ajax

           $(".add_btn").click(function(e){

               e.preventDefault();
     
              var id = $(this).data("id");

                 var token = $("meta[name='csrf-token']").attr("content");
           

                     $.ajax(
                     {
                      url: "addUnit/"+id, 
                  type: 'POST',
          
                  data: {
                    "id": id,
                    "_token": token,
                  },
                 dataType: 'json',
                    success: function(data) {
                        console.log('SUCCESS: ', data);
                    },
                    error: function(data) {
                        console.log('ERROR: ', data);
                    },
               });
            });

my controller public function addUnit_to_issued(Request $request){

             $id = $request->input('id');
            // store id data to another table here

              dd($id);
                      

            return redirect()->back()
                            ->with('success',' Updated successfully.');
              }

error

             ERROR:  {readyState: 4, setRequestHeader: ƒ, getAllResponseHeaders: ƒ, getResponseHeader: ƒ, 
             overrideMimeType: ƒ, …}

             POST http://127.0.0.1:8000/store/addUnit/1 404 (Not Found)
0 likes
13 replies
jlrdw's avatar

After this line:

var id = $(this).data("id");

If you

alert(id);

Does it give you the id? And

This

return redirect()->back()
                            ->with('success',' Updated successfully.');

Sent back a response json.

MichalOravec's avatar

You have problem with your routes.

When you have this

url: "addUnit/"+id, 

It should be

Route::post('addUnit/{id}', 'YourController@addUnit_to_issued');
public function addUnit_to_issued(Request $request, $id) 
{
    echo $id; // here you have your id 
}
melx's avatar
Level 4

controller

          public function addUnit_to_issued(Request $request,$id){
              echo $id;

            $id = $request->id;

            dd($id);
                      

            return redirect()->back()
                            ->with('success',' Updated successfully.');
            }

route

          Route::post('addUnit/{id}','IssuedUploadController@addUnit_to_issued');
MichalOravec's avatar

Add leading slash to url

url: "/addUnit/"+id,

So you pass id as parameter of route

public function addUnit_to_issued(Request $request, $id)
{
    // here handle id

    if ($request->wantsJson()) {
        return response()->json([
            'success' => 'Updated successfully.'
        ]);
    }

    return back()->with('success',' Updated successfully.');
}
melx's avatar
Level 4

am get

 		SUCCESS:  
     {success: "Updated successfully."}
      success: "Updated successfully."

i want to store/create this id to another table, kindly can you show me how i can add there

MichalOravec's avatar

So it works.

public function addUnit_to_issued(Request $request, $id)
{
    // here handle id

    SomeModel::create([
        'some_foreign_key_id' => $id
    ]);

    if ($request->wantsJson()) {
        return response()->json([
            'success' => 'Updated successfully.'
        ]);
    }

    return back()->with('success',' Updated successfully.');
}

Propably you need send more data or just add some static data.

melx's avatar
Level 4

@michaloravec , i would like to ask something am a new in Javascript

I want to put validation here id this id has alread created no need to add again

I tried like this

   public function addUnit_to_issued(Request $request,$id){

            // echo $id;

            $check=IssuedUpload::where('id',$id);
            // dd($check);

            if(!$check){

                IssuedUpload::create([
                    'unit_id' => $id,

                ]); 

            }
            else{
                return redirect()->back()
                ->with(error('Error','not added successfully.'));

            }
            if ($request->wantsJson()) {

                return response()->json([
                    'success' => 'added successfully.'
                ]);
            }
MichalOravec's avatar
Level 75
public function addUnit_to_issued(Request $request, $id)
{
    IssuedUpload::firstOrCreate(['unit_id' => $id]);

    if ($request->wantsJson()) {
        return response()->json([
            'success' => 'Updated successfully.'
        ]);
    }

    return redirect()->back()->with('success',' Updated successfully.');
}

Documentation: https://laravel.com/docs/7.x/eloquent#other-creation-methods

Please or to participate in this conversation.