Reputation: 133
How do I take value from one textarea to another with laravel and jquery ajax. I have this files so far. Route:
Route::post('/post', 'PostController@post');
Controller:
class PostController extends Controller
{
public function post(Request $request)
{
$request->json()->all();
}
}
JQuery file:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(data);
}
});
});
});
and the html :
<textarea class="form-control" name="firsttextarea" rows="10" id="firsttextarea" ></textarea>
<button id="insert" class="btn btn-md btn-primary"><span class="glyphicon glyphicon-circle-arrow-right"></span>Insert</button>
<textarea class="form-control" name="secondtextarea" rows="10" id="secondtextarea" ></textarea>
When i push the button nothing happens.
Upvotes: 1
Views: 1846
Reputation: 441
First problem probably can be in CSRF Verify. You can disable it if it so or add {{ csrf_token() }}
.
Then your post action should be looks like this:
public function post(Request $request)
{
return response()->json($request->all());
}
I checked it and it's work fine. but in textarea insert [Object object]
because it JSON. You can add JSON.stringify in your Jquery script like this:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(JSON.stringify(data));
}
});
});
});
Upvotes: 2
Reputation: 5584
Try this, you're not returning a response in your Controller method.
class PostController extends Controller
{
public function post(Request $request)
{
return response()->json([
'data' => $request->get('intrare'),
]);
}
}
then, add this to your head in your blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
and replace your JS with the below:
$(function() {
// We need CSRF Token in our ajax request so we can
// validate the POST request
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
// Insert text from first textarea to the other textarea
$("#insert").on("click", function(e) {
e.preventDefault();
var intrare = $("textarea#firsttextarea").val();
$.ajax({
type: "POST",
url: "/post",
data: { intrare: intrare },
success: function(response) {
$("textarea#secondtextarea").val(response.data);
}
});
});
});
Upvotes: 1