I am doing a project in laravel and i want to change a value of a column from 0 to 1 when a button is clicked.
i am using ajax to do this.
view.blade
<td><button type="button" class="btn btn-primary" id="j-approve-user" onclick="approveLogin('{{ route('approve', $user->id) }}')">Approve</button></td>
ajax script:
let getToken = function() {
return $('meta[name=csrf-token]').attr('content')
}
function approveLogin(url){
let data = { '_token': getToken() }
$.ajax({
'url': url,
'method': 'POST',
'data': data,
}).done(function(response) {
//window.location.reload()
})
}
Controller:
public function approve($user_id)
{
$user = User::find($user_id);
$user->update(['loginapproval'=>'1']);
return "ok";
}
However, i am getting a status code of 500 when i click the button.
Can anyone please help?
500 error is caused because a variety of erros, things you may look it up:
have you checked your laravel error log? storage/logs/laravel.log The answer may be there!
is your model loginapprovalattribute fillable, not mass assignment?
have you check whether the $user_id or the mode is null then you're trying to update a null model:
Your code.
public function approve($user_id)
{
$user = User::find($user_id);
if (!is_null($user)) {
$user->update(['loginapproval'=>'1']);
return "ok";
}
}
Related
I'm working with Laravel 9 and I wanted to make an infinite loader pagination with ajax for my blade.
So at the Controller:
public function index(Request $request)
{
$ques = Question::orderBy('created_at', 'DESC')->where('que_private',0)->paginate(10);
if($request->ajax()){
$view = view('frontend.layouts.partials.infinite',compact('ques'))->render();
return response()->json(['html' => $view]);
}
return view('frontend.index', compact('ques'));
}
And in the index.blade.php:
function loadMoreData(page){
$.ajax({
url: '?page=' + page,
type:'get',
beforeSend: function ()
{
$(".ajax-load").show();
}
})
.done(function(data){
if(data.html == ""){
$('.ajax-load').html("");
return;
}
$('.ajax-load').hide();
$("#post-data").append(data.html);
})
.fail(function(jqXHR,ajaxOptions,thrownError){
alert("Server is not responding");
});
}
And this is infinite.blade.php which ajax loads:
<div id="post-data">
#foreach($ques as $que)
...
#endforeach
</div>
When I test this, the image comes up properly but it returns Server is not responding error alert meaning that .fail(function(jqXHR,ajaxOptions,thrownError){ runs instead.
So what's going wrong here?
How can I solve this issue?
I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) ). i don't know why im getting this error.
Route:
Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
JQuery and Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
Controller
class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.
This is written incorrectly.
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
It should look like this.
public function getstate(Request $request) {
$state = State::where('countryid', '=', $request->country_id)->get();
return response()->json($state);
}
please check controller function
public function getstate(Request $request) {
$state = State::where('countryid' `=` ,request->$countryid)->get();
return response()->json($state);
}
I am using Laravel 5.4 and I have Check Out button in my table. I want when I click that button, it will update check out time in the database and update my table. I am trying to use ajax, but it is not working, but sometimes it is working too but not reload the table so I need to refresh the page manualy. Here is my button code:
<a type="button" name="checkout_btn" id="checkout_btn" data-id=" {{ $Data->VST_ID }}" class="btn btn-primary">Check Out</a>
This is my ajax code:
$('#checkout_btn').click(function addseries(e){
var VST_ID = $(e.currentTarget).attr('data-id');
alert("dfads");
$.ajax({
type: "GET",
url: 'visitor/checkout',
data: "VST_ID="+VST_ID,
success: function(data) {
console.log(data);
}
});
});
Here is my controller code:
public function Checkout(Request $request)
{
$visitor = Visitor::where("VST_ID",$request['VST_ID'])->first();
$visitor->VST_CHECKOUT = date('Y-m-d H:i:s');
$visitor->UPDATED_AT = date('Y-m-d H:i:s');
$visitor->UPDATED_BY = 'User';
$visitor->save();
return redirect()->route('Visitor.VList')->with('message','The Visitor has been Checked Out !');
}
You can do this by two methods.
1st: by making different view for table body.
In controller set view as below Example
if($request->ajax())
{
$records=\View::make('admin.settings.state.state-holiday-tbody',['contents'=>$contents,'active'=>$active,'tab'=>$tab])->render();
return response()->json(array('html'=>$records));
}
and then perform for loop to append data in table body.
Note: call function to get all table records on document ready.
2nd: Make table body using javascript for loop by getting all records in response.
I think if you want to update the data, the method is PUT and why are you using GET method?
$('#checkout_btn').click(function addseries(e){
var VST_ID = $(e.currentTarget).attr('data-id');
$.ajax({
type: "PUT",
url: 'visitor/checkout' + VST_ID,
success: function(data) {
console.log(data);
}
});
});
change your controller
public function Checkout(Request $request, $id)
{
$visitor = Visitor::find($id);
$visitor->VST_CHECKOUT = date('Y-m-d H:i:s');
$visitor->UPDATED_AT = date('Y-m-d H:i:s');
$visitor->UPDATED_BY = 'User';
$visitor->save();
return redirect()->route('Visitor.VList')->with('message','The Visitor has been Checked Out !');
}
and change your route.php
Route::put('visitor/checkout/{id}', 'visitorController#Checkout');
After trying some possible solutions that I found through internet/other questions here, I can't seem to find the problem with my code. What I need is that, after clicking a button in my view, an action in my Yii2 controller gets called through Ajax and performs some action. However, with my current code, after clicking the button nothing seems to happen.
The relevant code is as follows...
The view:
(...)
Html::button('Eliminar', ['data-confirm' => '¿Eliminar enunciado?', 'onclick' => '
$.ajax({
type: "POST",
url: "/evaluacion/eliminar-enunciado",
data: {
id: '.$enunciado->id.'
}, success: function(result) {
if(result == 1) {
$.pjax.reload({container: "#construccion-evaluacion"});
} else {
}
}, error: function(result) {
console.log(\"server error\");
}
});
'])
(...)
The controller:
(...)
public function actionEliminarEnunciado($id)
{
Enunciado::findOne($id)->delete();
if(Enunciado::findOne($id) != null) {
echo 1;
} else {
echo 0;
}
}
(...)
Some considerations for clarification:
- The controller file is called EvaluacionController.php.
- The $enunciado->id variable is properly defined and has a valid value.
Any advice will be appreciated. Thanks for your time!
You need get value of POST request;
if(isset($_POST['id']))
$id = $_POST['id'];
As the title, i want to CI_Controller return value/data back to AJAX which give request before.
The_Controller.php
class The_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
function postSomething()
{
$isHungry = true;
if(isHunry){
return true;
}else{
return false;
}
}
}
AJAX
$(document).ready(function()
{
$('#form').on('submit', function (e)
{
e.preventDefault(); // prevent page reload
$.ajax ({
type : 'POST', // hide URL
url : '/index.php/The_Controller/postSomething',
data : $('#form').serialize (),
success : function (data)
{
if(data == true)
{
alert ('He is hungry');
}
else
{
alert ('He is not hungry');
}
}
, error: function(xhr, status, error)
{
alert(status+" "+error);
}
});
e.preventDefault();
return true;
});
});
The Problem :
The AJAX code above always get FALSE for variable data. It's not get return value from postSomething function inside CI_Controller.
The Question :
I want to if(data == true) result alert ('He is hungry');. But cause data not fill by return value of postSomething function inside CI_Controller so it always false. How to get return value/data from CI_Controller to AJAX?
Thank you
you need to change your code a little bit. no need to return data, just echo true or echo false from your controller. Hope you will get your desired result.
You have a typo in the PHP code
if(isHunry){
should be
if($isHungry){
Also, returning data to an AJAX request, you really should be sending the correct content type in the header. Ex.
header('Content-Type: application/json');
And print or echo the data, not return it, as well as json_encode it:
echo json_encode($data);
So your postSomething php function should look something like this:
$isHungry = true;
header('Content-Type: application/json');
echo json_encode($isHungry);