andreixfr
8 months ago
430
1
Laravel

How to add Ajax to send data in database on click?

Posted 8 months ago by andreixfr

I need to add Ajax function to my Mailbox page.When I press on every mail, in database I sent value 1, and that's means the mail is read. In my mails I added an

    @if($inbox->pivot->read == 0)
                        <td><a style="font-weight: bold" class="get-inbox" read="inbox" mailval="{{ $inbox->pivot->id }}">{{ $inbox->pivot->subject }}</a></td>
                        @else
                        <td><a  class="get-inbox" read="inbox" mailval="{{ $inbox->pivot->id }}">{{ $inbox->pivot->subject }}</a></td>
                        @endif

Here is my controller

    public function getInbox(Request $request)
    {
        if ($user = Sentinel::check())
        {
            // return $request->all();
            $mail = Mailbox::findOrfail($request['mail_id']);
            $sender_user = User::where('id','=',$mail->sender_id)->first();
            if($request['read'] == "inbox")
            {
                $mail->read = 1;
                $mail->save();
            }
            echo $html = '<tr>
                            <td style="border:unset">
                                <b>Sent To:</b> '.$mail->target_username.'<br>
                                <b>From:</b> <a href="'.$sender_user->username.'">'.$sender_user->username.'</a>'.
                            '</td>
                            <td style="border:unset" colspan="2">'.$mail->subject.'</td>
                            <td style="border:unset">'.date("d-m-Y", $mail->date).'</td>
                        </tr>
                        <tr style="background-color:#DDDDDD;">
                            <td style="border:unset" colspan="4">'.$mail->message.'</td>
                    </tr>';

        }
        else
        {
            return redirect('home');
        }

    }

Here is my route

Route::post('get-inbox', '[email protected]');

But now this is correctly display only if I refreshing my page.Can I use Ajax to send data to database, and displaying bold/ normal mails based on value from database in read column?Because I don't want to refresh the page every time to record it in database, I want to display that if correctly based on records from read.

Please sign in or create an account to participate in this conversation.