I try to pass a return json to my view but I get an error who say that I didn't past all the variables objects to the view, the problem if I pass all the variables in my table I get all my web page in the table wish is no sense..
someone know how I could do?
here my controller:
public function searchEquipes(Request $request)
{
if ($request->has('poule_id')) {
$equipes = EquipePoule::where('poule_id' , $request->poule_id)->get();
return response()->json([
'table' => view("competitions/show", compact('equipes'))->render(),
]);
}else {
//nothing
}
}
here my view:
#foreach($equipes as $equipe)
<tr>
<td>{{$equipe->equipe->structure->nom_structure}}</td>
<td>{{$equipe->equipe->lb_equipe}}</td>
<td>{!! Form::text('nb_bonus') !!}</td>
</tr>
#endforeach
here my script:
<script>
$('#poule').change(function () {
$.ajax({
type: 'GET',
url : 'search/equipes',
dataType: "json",
data : {
poule_id : document.getElementById('poule').value
},
success:function(data){
$('#equipes').html(data.table);
}
});
});
</script>
i guess you are not returning the json response the right way try using
return response()->json([$equipes]);
success:function(data){
//loop $equipes here
}
Related
It seems like my save(); in my categories does not function as intended below. I will show the necessary codes first:
my table name is hms_bbr_category which is also connectec to my .env locally:
DB_CONNECTION=pgsql
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=jhs
DB_USERNAME=postgres
DB_PASSWORD=pa55wor0
my model: HmsBbrCategory
class HmsBbrCategory extends Model
{
protected $table = 'hms_bbr_category';
protected $fillable = [
"category_name", "category_description"
];
}
my controller: BBRCategoryConfigurationController
class BBRCategoryConfigurationController extends Controller
{
public function index(){
return view('frontend.bbr-settings.bbr-category-configuration');
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'category_name'=>'required|max:191',
'category_description'=>'required|max:191',
]);
if($validator->fails())
{
return response()->json([
'status'=>400,
'errors'=>$validator->messages(),
]);
}
else {
$category = new HmsBbrCategory;
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->save();
return response()->json([
'status'=>200,
'message'=>'Category Added!',
]);
}
}
The ajax and modal fields
<div class="form-group">
<input type="text" class="form-control form-group w-100 category_name" placeholder="Category Name">
</div>
<div class="form-group">
<textarea class="form-control w-100 category_description" placeholder="Category Description" cols="50" rows="10"></textarea>
</div>
<script>
$(document).ready(function (){
$(document).on('click', '.add_category', function(e){
e.preventDefault();
var category_data = {
'category_name': $('.category_name').val(),
'category_description': $('.category_description').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(category_data);
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: "category_data",
dataType: "json",
success: function (response){
// console.log(response);
if(response.status == 400)
{
$('#saveform_errList').html("");
$('#saveform_errList').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#saveform_errList').append('<li>'+err_values+'</li>');
});
}
else
{
$('#saveform_errList').html("");
$('#success_message').addClass('alert alert-success');
$('#success_message').text(response.message);
$.('#createCategory').modal('hide');
$.('#createCategory').find('input').val("");
console.log(category_data);
}
}
});
});
});
</script>
my routes at web.php
Route::get('/bbr-category-configuration', [BBRCategoryConfigurationController::class,'index']);
Route::post('/bbr-category-configuration', [BBRCategoryConfigurationController::class,'store']);
Things to note:
my hunch is that my store function does not connect properly at $category = new HmsBbrCategory; However I have checked that my table name and the fields taken are the same, as seen at $category->category_name = $request->input('category_name');
I have also tested in ajax with the values by simply adding console.log(response) as seen in the screenshot, I cannot get past my validator to get to the save(). I am not sure how but There should not be an error since my text fields are filled.
I can elaborate more if needed, I am asking what can I change to fix my validation/save. thanks for any help.
As the error shows, The validation is failing (empty value i guess) and returning the code you programmed (400).
i'm guessing it is because you are using a string instead of the variable at the attribute data: "category_data",
update the code to send the variable instead
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data, //change here
dataType: "json",
success: function (response){
//...
I have a simple app in codeigniter. In my view I have ajax POST request to the controller, but I don't receive response data. I checked in the chrome dev tool in network tab the response and the message is: No response data available for this request :
My view:
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>First</td>
<td>Sec</td>
<td>Th</td>
<td>Th</td>
</tr>
</thead>
<tbody>
<?php
if(isset($result))
{
foreach($result as $value)
{
echo "<tr><td>". $value->cai . "</td><td>". $value->partner ."</td><td>". $value->spot ."</td><td><button type='button' id='".$value->cai."' class='btn btn-danger delete'>Delete</button></td></tr>";
}
}
?>
</tbody>
</table>
<?php echo $this->pagination_bootstrap->render(); ?>
<script>
$('.table').on('click','.delete',function(){
var id=$(this).attr('id');
var confirm_box=confirm('Sure?');
if(confirm_box === true)
{
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
type: 'POST',
data: {
key: id
},
dataType: 'json',
success: function(data) {
console.log(JSON.parse(data));
}
});
}
});
</script>
My controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Tires_Crud extends MY_Controller
{
public function deleteCai()
{
$status = array(
"STATUS" => "true"
);
return json_encode($status);
}
}
In my config file CSRF protection is DISABLED! Because when its enabled the ajax request is not working. Thanks for your help in advance!
Some issues with this code.
#1: The way you're forming the ajax request. Where you have type: 'POST' should be method: 'POST' - but more than a typo, it's important that you understand these are referred to as the HTTP method - same way you'd specify that in a <form method='post' tag. If you don't provide a method, it's assumed to be GET.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
Also, because you specified dataType:'json' - jquery will deliver a ready to use parsed JSON object. No need for you to parse it yourself
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
method: 'POST', // <-- change this from 'type' to 'method'
data: {
key: id
},
dataType: 'json',
success: function(data) {
// console.log(JSON.parse(data)); // <-- no need to parse - you have set dataType to be json, which means it will come to you already parsed
console.log(data);
})
#2 - In your PHP, you'd catch your key variable (you sent in ajax) with $_POST['key'] - though in codeigniter you get it like this:
// codeigniter 2.x and 3.x
$this->input->post('key');
// codeigniter 4
use CodeIgniter\HTTP\IncomingRequest;
$request = service('request');
$request->getPost('key');
#3 - With ajax, you actually echo the response, rather than return it:
public function deleteCai(){
$status = array(
"STATUS" => "true"
);
echo json_encode($status);
}
I have a list of hotels in a select I want update the database base on the hotel selected if it update the field I want to alert it on the home page.
this is the ajax function
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});
}
}
my controller
public function update(Request $request, $hotel_plan_id)
{
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}
my route
Route::post('home/{hotel_plan_id}', 'HomeController#update')->name('home');
my select form
{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}
You have error with ajax url and you dont also pass the value of hotel name.
Check this changes.
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}
Please return json response
return response()->json();
You have to return json object like this
return response->json([
'status' => 200,
'result' => true,
'error' => false,
'data' => $hotel
]);
I am using laravel 6.0 and i am building crud application. I have following jquery code in view file
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/'+id,
method: 'post',
success: function (res) {
console.log(res);
}
})
});
}
And this is the code in controller
public function update(Request $request, $id='') {
$country = $request->input('countryname');
$sortname = $request->input('sortname');
$phonecode = $request->input('phonecode');
//return $country.$sortname.$phonecode;
return $request;
// DB::table('countries')->where('id',$id)->update(
// [
// 'name' => $country,
// 'sortname' => $sortname,
// 'phonecode' => $phonecode,
// ]);
}
The problem is $request returns empty.
If I don't use ajax then I am getting all input values. But I dont know why its not working for ajax request. Also I have added this line in view file
headers: {
'X-CSRF-TOKEN': '{!! csrf_token() !!}'
}
});
Please help me to solve this problem
You are not passing your form data. Try this:
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: $(this).serialize();
success: function (res) {
console.log(res);
}
})
});
}
laravel by default does not send raw data , you have to convert your data to json, the best practice is :
return response()->json([
'data' => $request
]);
Just try this code for example and see if you get any hint.
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: {'countryname' : 'India','sortname' : 'Sort Name', 'phonecode' : '022'};
success: function (res) {
console.log(res);
}
})
});
}
See if you are getting any response.
I need help: I do not know how to edit two tables of the database from the same form. I'm using cakephp3.
I'm trying to use ajax
Thanks for your help
Data to save in a different driver, there the script
This script is in a controller called carsController
**<script type="text/javascript">**
function editarCliente(a, b ){
var parametros = {
"clasificacionC" :a,
"descripcion": b,
};
$.ajax({
data: parametros,
url: '<?php echo router::url(array('controller'=>'Clientes','action'=>'editarcliente',$cliente->id));?>',
type: 'post',
dataType: 'json',
success: function (response) {
$("#nomCliente").val(response.uno+" "+response.dos);
$("#telCliente").val(response.tres);
$("#celCliente").val(response.cuatro);
}
});
}
**</script>**
This method is in a controller called clientesController.
public function editarcliente($id = null)
{
$cliente = $this->Clientes->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$cliente->clasifi_cliente=$_POST("clasificacionC");
$cliente->descripcion=$_POST("descripcionC");
if ($this->Clientes->save($cliente)) {
$this->Flash->desactivar(__('Cliente desactivado'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The cliente could not be saved. Please, try again.'));
}
}
$this->set(compact('cliente'));
$this->set('_serialize', ['cliente']);
}