Accessing variable from another function from view ajax post

Viewed 53

I have a class like below :

class Giving extends Controller
{
    public function test()
    {
        $name; // i want to access $name from function below
        $email; // i want to access $email from function below
        return view('route/routes', [
            'name' => $name,
            'email' => $email
        ]);
    }

    public function sendGiving()
    {
        $name = $this->request->name;
        $email = $this->request->email;
    }
}

function sendGiving receives its value from ajax post (at blade view) :

data = {
    _token: '{{ csrf_token() }}',
    name: $('#txtName').val(),
    email: $('#txtEmail').val(),
    phone_number: $('#txtPhnum').val(),
}

$.ajax({
    url: "{{ route('sendGiving') }}",
    type: 'POST',
    data: data,
    dataType: 'JSON',
    success: function (response) {
        //do something
    }
});

Routes :

Route::get('/givingtest','Giving@test')->name('test');
Route::post('/givingsend', 'Giving@sendGiving')->name('sendGiving');

how can i access value from sendGiving() function to test() function ? Or can i make a second ajax post call in the view to send data to test() function ?

1 Answers

As far as I understand your question I can see (at least) three ways here.

1. Use Session

public function sendGiving()
{
    session(['name' => $this->request->name, 'email' => $this->request->email]);
}

public function test()
{
    $name = session('name');
    $email = session('email');
    return view ('route/routes', compact('name', 'email'));
}

2. Pass the data to your function directly

Define givingtest as post route and just send the data to that function as well. So you can just do:

public function test()
{
    $name = $this->request->name;
    $email = $this->request->email;
    return view ('route/routes', compact('name', 'email'));
}

3. Persist the data in the database

If the data of sendGiving() is already valid and worthy to keep, why not save it in a database right away?

Related