Laravel 5: Request data is null when using an Ajax Post Request - php

I have some problems with receiving data when using an ajax call to EDIT my data. I'm trying to get data that the user has filled in but every time my data is empty or 'null'. Do i need to pass data in ajax call? Or are there other ways in laravel to get the data?
My code at the moment as we speak:
showuser.blade.php
<div class="comments">
#if(count($user->cars))
<h1>Auto in reparatie</h1>
<hr>
#foreach($user->cars as $car)
<!-- Form to show each car and edit / delete the cars -->
<!--<form action="{{ action('CarController#edit', [$user->id, $car->id]) }}" method="POST">-->
<form>
<div class="form-group">
<label for="brand">Merk:</label><br>
<select name="brand">
#foreach($brands as $brand)
<option value="{{$brand->id}}"{{ $brand->id == $car->brand_id ? ' selected="selected"' : '' }}>{{$brand->brandname}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="year">Bouwjaar:</label><br>
<input type="text" value="{{$car->year}}" name="year">
</div>
<div class="form-group">
<label for="licentsplate">Kenteken:</label><br>
<input type="text" value="{{$car->licensplate}}" name="licenseplate">
</div>
<div style="float: left; width: 80px">
<input type="submit" class="btn btn-primary" value="Edit" id="{{$car->id}}" name="editcar" />
</div>
</form>
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
#endforeach
#endif
</div>
Script
<script type="text/javascript">
$( document ).ready(function() {
$('[name="editcar"]').click(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
})
});
});
</script>
Routes
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
CarController.php
// Function to edit a car by ID
public function edit($userId, $carId)
{
$car = Car::where('id', $carId)->where('user_id', $userId)->first();
$car->brand_id = request('brand');
dd(request('year'));
$car->year = request('year');
$car->licensplate = ('licenseplate');
$car->save();
}
If I dump and die request('brand'), request('year'), request('licenseplate') i get 'null'.
EDIT:
If I dd $car in my controller, i get the car that i need. Means that there is no problemen finding the right car.
Thx for reading!

You aren't posting any data in the AJAX request. Pass the form values through in an object.
var form = $(this).find('form');
var licenseval = form.find('input[name=licenseplate]').val();
var yearval = form.find('input[name=year]').val();
var brandval = form.find('select[name=brand]').find(":selected").val();
$.ajax({
type: "POST",
data: {licenseplate: licenseval, year: yearval, brand: brandval}
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
});

Change following lines:
public function edit($userId, $carId)
to
public function edit(Request $request, $userId, $carId)
and use
use Illuminate\Http\Request;
after that you can get $userId, $carId to use inside the controller function.

As per your ajax call you are only calling the route
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
but you are not passing any other value. Your application is working as expected.
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
//data: dataObject, ----->Missing Data which you want to pass (brand, year, licenceplate)
success:function(data){
//...
}
})
You are iterating through multiple $cars you need to get current car's data and pass to ajax call.

Related

Ajax jquery(post) doesn't pass data to php [duplicate]

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 9 months ago.
I am trying to pass data to my php page:
<?php
var_dump($_POST);
if (isset($_POST['goal']) && isset($_POST['amount'])){
$goal = $_POST['goal'];
$amount = $_POST['amount'];
$array = array(
"goal" => $goal,
"amount" => $amount
);
echo json_encode($array);
}
However as a result of var_dump $_POST I keep getting an empty array, for some reason my ajax doesn't pass the neccessary data. I tried console.logging the value of fields that I am using and their value is correct it's just that data doesn't pass on the php page.
ajax:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
let amount = $("#amount").val();
let goal = $("#goal_name").val();
$.ajax({
method: "post",
url: "target-modal-code.php",
data:JSON.stringify( {
amount: amount,
goal: goal
}),
contentType:"application/json",
success: function (response){
$("#response").text(response);
console.log(amount);
console.log(goal);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
And my form is inside a modal :
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="enrollLabel">Change your goal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="target-modal-code.php" name="target-form" id="target-form">
<div class="modal-body">
<form action="">
<div class="mb-3 input-control">
<label for="amount">Cost</label>
<input type="number" class="form-control" id="amount" name="amount"
placeholder="Amount">
<small class="message" id="message-password"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="goal_name">Goal</label>
<input type="text" class="form-control" id="goal_name" name="goal_name"
placeholder="Goal">
<small class="message" id="message-password"></small>
<br>
</div>
</form>
</div>
<p class="response" id="response"></p>
<div class="modal-footer">
<div class="response">
</div>
<button type="button" id="goalBTN" class="btn btn-warning">Save changes</button>
</div>
</form>
</div>
</div>
Updated answer after some live testing with Network tab in firefox web dev tools
The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don't provide it specifically.
So, this worked:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
// let amount = $("#amount").val();
// let goal = $("#goal_name").val();
var formData = {
amount: $("#amount").val(),
goal_name: $("#goal_name").val(),
};
$.ajax({
method: "post",
url: "target-modal-code.php",
// datatype:"json",
//data:JSON.stringify(formData),
data: formData,
//contentType:"application/json",
//encode: true,
success: function (response){
$("#response").text(response);
// console.log(amount);
// console.log(goal);
console.log(formData);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
After little bit of fiddling, I noticed that it works if you DON'T provide it contentType at all. Otherwise, AJAX won't send GET or POST params to the server.... dont know why. I know it's weird but that's how it is in jquery ajax.
I have intentionally kept the comments for you to see what all I have tried.
So to summarize,
Don't stringify the form data,
Don't provide contentType to ajax
request.
Cheers.!
format send ajax:
$.ajax({
...
data : {
foo : 'bar',
bar : 'foo'
},
...
});
in your case: change data send format like:
data: {
amount: amount,
goal: goal
}

laravel api ajax form wont submit

This is my first api project. Can you help me with my code please?
I can't see the problem.
Here is my controller.
public function store(Request $request)
{
//
$valid=Validator::make($request->all(),[
'text'=>'required',
'body'=>'required'
]);
if($valid->fails()){
return response()->json(['message'=>$valid->messages()]);
}else{
$item= Item::create([
'text'=>$request->input('text'),
'body'=>$request->input('body')
]);
return response()->json($item);
}
}
and here is my form.Is there anything wrong in the form?
<form id="form">
<div class="form-group">
<label>Text :</label>
<input type="text" id="text" class="form-control col-sm-4">
</div>
<div class="form-group">
<label>Body :</label>
<textarea id="body" class="form-control col-sm-4"></textarea>
</div>
<div class="form-action">
<input type="submit" class="btn btn-primary" value="submit">
</div>
</form>
and the ajax code between the show function is working but I don't know where the problem is ?.
$('#form').on('submit', function (e) {
e.preventDefault();//prevent the form to submit to file
let text = $('#text').val();
let body = $('#body').val();
addItems(text, body);
});
function addItems(text, body) {
var item = {
text: text,
body: body
};
$.ajax({
method: 'POST',
url: 'http://localhost:8000/api/items',
data: item,
success: function (item) {
alert('done the item number' + item.id + ' has been added!!');
location.reload();
},
error: function () {
alert('error')
}
})
}
Thanks for helping!
if your front-end source separated from back-end source, then add cross-Origin Resource Sharing
package to your laravel project.
if its on your laravel view then add csrf token to meta tag -
<meta name="csrf-token" content="{{ csrf_token() }}">
and send it with your ajax request { _token : document.querySelector('meta[name="csrf-token"]').content}
The problem is that you're sending the form without sending the cross site request forgery token.
Add the directive #csrf to your view
Then send it has Hasan wrote ;)

Controller not getting inputs laravel

Currently I am trying to pass a creation form to a controller. I have the route and the ajax call setup and talking to the route. My problem is that when I use the ajax call the inspect tool for headers is showing my form values correctly but when I go into the controller the request->input doesnt show any values for the form.
Here is my ajax call
$(document).on("click", ".form-submit-btn", function() {
// Get the form id.
var formID = $(this).closest("form").attr("id");
var serializedForm = $(this).closest("form").serialize();
var substringEnd = formID.indexOf("-form");
var route = formID.substr(0, substringEnd).replace("-", "_");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Submit the form.
$.ajax({
method: "POST",
url: "/" + route,
data: {
serializedForm
},
success: function(data) {
alert(data);
}
});
});
Here is my controller
// Create Role
public function create(Request $request)
{
// Get and validate request params
$role = $request->input('role_name');
$active = $request->input('role-active', false);
return $role;
}
And here is my route
Route::post('/create_role', 'RoleController#create');
Am I missing something that is preventing the ajax call from sending the values to the controller
Here is my form also if that helps.
<form id="create-role-form" class="form">
{{ csrf_field() }}
<button class="pull-right right-close-btn">X</button>
<h1>Add Role</h1>
<hr />
<div class="form-group">
<label>Role Name</label>
<input type="text" name="role_name" class="form-control" />
</div>
<div class="form-group">
<input type="checkbox" name="role_active" value="true" checked /> Active
</div>
<div class="form-group">
<button class="btn btn-primary form-control form-submit-btn">Create</button>
</div>
I think problem is this line
data: {serializedForm},
Just change it to
data: serializedForm,
and it should fix the problem.
Problems
I see two problems with your ajax request
Are you sure you're using ES-6 TransPiler because data:{serializedForm}, is ES-6 Syntax http://es6-features.org/#PropertyShorthand
If you're javascript is working fine. You should be able to get it like $request->get('serializedForm')['role_name'] with your existing code.
Hope it helps

Jquery pass value to radio button

I used jquery ajax code to run search function.
here's my ajax so far :
$('button[type="search"]').click(function(e) {
$.ajax({
url: "{{ route('fine.search') }}",
type: "POST",
data: {
'_token' : '{{csrf_token() }}',
'driver_id' : $('select[name="driver_id"]').val(),
'fine_date' : $('input[name="fine_date"]').val(),
},
success: function(data) {
if(data.status == true) {
var result= $('#search-result');
$.each(data.getCarbyDriver, function(i, data) {
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'});
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
});
$('#search-result').append(PlateEle, StartEle, EndEle);
}
},
error: function(data) {
}
});
});
and the data being returned like this on my network (inpect element) :
car_id:5
driver_id:1
end_time:"2016-11-16 18:00:00"
plate_no:"DFE82846J"
start_time:"2016-11-16 08:00:00"
working_date:"2016-11-16 00:00:00"
here's the form blade code so far :
<div class="row top">
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label class="control-label">Driver Name:</label>
{!! Form::select('driver_id', $driver, null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label>Fine Date:</label>
{!! Form::text('fine_date', null, array('id' => 'datetimepicker', 'class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group filter-btn">
<button class='btn btn-info' type='search'>Search</button>
</div>
</div>
</div>
<div class="row mid ">
<div class="col-xs-4 col-sm-4 col-md-4">
<div id="search-result"></div>
</div>
</div>
the issue is I can't save. it throws error car_id' cannot be null'.
how do i pass car_id into my radio, so once i clicked on radio button it save car_id by plate_no
im using laravel 5.3
It's unclear to me where you have PlateEle, StartEle and EndEle defined. Are those global vars defined elsewhere in your javascript?
Either way, as I understand it, car_id is being returned by the ajax POST, so it's in the data var returned to your success function?
If you want to set the value in the radio element you're creating dynamically I think it would be this:
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'}).val(data.car_id);
Here is an example I mocked up. I am creating a data object like what I believe you're saying is being returned. When I load this page I get a radio input created. Does this work for you?
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var result= $('#search-result');
//mocking up what I assume your data object looks like
var data = {};
data.car_id=5;
data.driver_id=1;
data.end_time="2016-11-16 18:00:00";
data.plate_no="DFE82846J";
data.start_time="2016-11-16 08:00:00";
data.working_date="2016-11-16 00:00:00";
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'}).val(data.car_id);
console.log(PlateEle);
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
$('#search-result').append(PlateEle, StartEle, EndEle);
});
</script>
</head>
<body>
<div id="search-result"></div>
</body>
</html>
To save the value on your input radio this could should make the trick:
$.ajax({
url: "{{ route('fine.search') }}",
type: "POST",
data: {
'_token' : '{{csrf_token() }}',
'driver_id' : $('select[name="driver_id"]').val(),
'fine_date' : $('input[name="fine_date"]').val(),
},
success: function(data) {
if(data.status == true) {
var result= $('#search-result');
$.each(data.getCarbyDriver, function(i, data) {
PlateEle = $('<input type="radio" name="rad" val="'+data.car_id+'">'+data.car_id+'</input>');
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
});
$('#search-result').append(PlateEle, StartEle, EndEle);
}
},
error: function(data) {
}
});
Well, adding or changing value of radio buttons is simple. For your ID in database you could also use some data-* attribute on your radio button. But remember, data-* on your form elements will not be sent to the server, if the form is submitted in browser. For more details see my working code example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Radio Button</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
var $rdBtn = null;
var $txtReader = null;
var $txtRdBtnValueReader = null;
function doReady() {
$rdBtn = $("#myRdBtn");
$txtReader = $("#txtDataReader");
$txtRdBtnValueReader = $("#txtRdBtnValueReader");
$("#btnSetValue")
.click(function () {
// note the jQuery .val("some text") issue at this point. You will need .attr("value") for setting
// .val() is just helpful for reading the current value!
$rdBtn.attr("value", "my new value");
$txtRdBtnValueReader.attr("value", $rdBtn.val());
});
$("#btnSetDataValue")
.click(function () {
$rdBtn.data("mykey", "myval");
$txtReader.attr("value", $rdBtn.data("mykey"));
});
}
$(document).ready(doReady);
</script>
</head>
<body>
<button type="button" id="btnSetValue">set Value</button>
<button type="button" id="btnSetDataValue">set data-* value</button>
<div id="myRadioButtonWrapper">
<label for="myRdBtn">your value choice</label>
<input type="radio" id="myRdBtn" name="myRdBtn" value="to be replaced" />
<br />
<label for="txtRdBtnValueReader">radio value</label>
<input type="text" id="txtRdBtnValueReader" name="txtRdBtnValueReader" readonly />
<br />
<label for="txtDataReader">data-mykey value</label>
<input type="text" id="txtDataReader" name="txtDataReader" readonly />
</div>
</body>
</html>
It is also a common way if you need more data assigned to an input field to serialize its value as json. So, that you could have a whole object sent to the server. It's easy to parse again in PHP. Maybe this could help you, too. Good luck!

php - Laravel : how to Load Ajax data after selected changes from dropdown?

I want to load some ajax data after selected a value from dropdown in textbox.
Eg: After selecting a teacher from dropdown, teachers remaining credit and credit_taken value should be load. How do I do it with ajax?
NB: Here teacher value has selected from another dropdown selecting in Ajax
<script>
$('#teacher').on('change',function(e){
var teach_id = $('#teacher option:selected').attr('value');
var info=$.get("{{url('ajax-teach')}}",{teach_id:teach_id});
info.done(function(data){
$.each(data,function(index,subcatObj){
/// Here will be the loaded code ///
});
});
info.fail(function(){
alert('ok');
});
});
</script>
Here is my controller:
Route::get('ajax-teach',function(Request $request){
$teach_id = $request::input(['teach_id']);
$teachers=\App\Teacher::where('teacher_id','=',$teach_id)->get();
return Response::json($teachers);
});
Here is the view Page:
<div class="form-group">
<label for="">Teacher</label>
<select class="form-control input-sm" required name="teacher_id" id="teacher" >
<option value=""></option>
</select>
</div>
<div class="form-group">
<label>Credit to be Taken</label>
<input type="text" name="credit_taken" id="credit_taken" class="form-control" required placeholder="Credit to be Taken">
</div>
<div class="form-group">
<label>Remaining Credit</label>
<input type="text" name="remaining_credit" class="form-control" required placeholder="Remaining Credit">
</div>
In your routes (routes/web.php)
Route::get( '/ajaxteach', array(
'as' => 'ajaxteach',
'uses' => 'TeachController#get_teach'
) );
In your controller (app/Http/Controllers/TeachController.php)
class TeachController extends Controller
{
public function get_teach(Illuminate\Http\Request $request)
{
$teach_id = $request->get('teach_id');
$teachers=\App\Teacher::where('teacher_id','=',$dept_id)->get();
return response()->json(['response' => $teachers]);
}
}
Then in your AJAX script you can use at least one of the following ways
use absolute url in javascript code
var base_url = 'http://localhost/laravel'
$.ajax({
type: "GET",
url : base_url+"/ajaxteach",
data : dataString,
success : function(data){
console.log(data);
}
use url() with route
$.ajax({
type: "POST",
url : "{{url('ajaxteach')}}",
data : dataString,
success : function(data){
console.log(data);
}

Categories