简体   繁体   中英

Passing data from view to controller using Ajax in Laravel

I am trying to pass two variables to my controller using ajax. There are no errors but the data is null when I get it in the controller.

Web.php

Route::get('/donate/select-card', 'CardController@chooseCard')->name('select-card');

CardController.php

public function chooseCard()
{
  $from = Input::get("fromAmount");
  // $to = $request->input('toAmount');
  dd($from);
}

'null' is the output here

Script.js

fromAmount = $(this).find('p span:nth-child(1)').text().split("₹ ")[1];
toAmount = $(this).find('p span:nth-child(2)').text().split("₹ ")[1];
$.ajax({
  type:'GET',
     url: '/donate/select-card',
     data:  { fromAmount : fromAmount, toAmount : toAmount }
});

What I want is to have the fromAmount & toAmount in my controller.

Thanks in advance.

This is the ajax data from network:

在此处输入图像描述

public function chooseCard(Request $request)
{
  return $request->all();
}

** Inject the Request class

** See the response from dev tool.

That one was tricky:)

In your HTML you have a link that is wrapping this call to the ajax. This is messing with

<a href="/donate/select-card">
    <button type="button" onclick="test123()">click here for ajax Call</button>
</a>

So clicking on this will send you to "/donate/select-card" but won't be trough the ajax. For the same reason, once you try to use POST, you get:

The GET method is not supported for this route. Supported methods: POST

The href is with priority and it is GET while the route is expecting a POST.

Make sure you remove all links and default behaviours around the html you use to call the ajax call then use GET or POST as you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM