I'm using Laravel 5.2 with ajax but I have internal server error 500 when I click on the link for example.
Here my code . . .
Blade file:
<a class="delete" href="#" data-userid="{{ $user->id }}">X</a>
Js file:
var userId = 0;
$('.delete').on('click', function(event){
event.preventDefault();
userId = event.target.dataset['userid'];
$.ajax({
method:'POST',
url: 'users/delete',
data: {userId: userId, _token: token}
}).done(function() {
console.log('done');
});
console.log(userId);
});
Route file:
Route::post('users/delete', 'HomeController#delete');
HomeController file:
public function delete(Request $request)
{
$user = POST::find($request['userId']);
$user->delete();
return response();
}
Js file works good out of laravel . . .
Of course I have database with users table, and connection with database.
I'm working locally and using windows 10.
This is error screenshot:
Can you please try using request Method as DELETE rather than a POST ?
It may fix your error. Here. Below check example for delete.
http://www.sitepoint.com/crud-create-read-update-delete-laravel-app/
[2016-04-30 21:35:42] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\POST' not found' in C:\project-user\app\Http\Controllers\HomeController.php:47
looks like you didn't imported POST with use keyword or you used wrong class (not POST)
use this
(check if POST is the right name for ur model in App folder)
$user = \POST::findOrfail($request->input('userId');
$user->delete();
return response()->json('Success');
in js
success: function(response){
console.log(response);
}
Related
I am trying to update a field in laravel and it doesn't do anything, I tryed to trace the error checking if the fields are correct and the routes but I don't really know.
//js file
$(document).on('blur','#dato-anyadir',function(){
var atributo=$(this).parent().attr('name');
var id=$(this).parent().parent().attr('id');
var valor= $(this).val();
if($(this).val() == ''){
$(this).parent().html($(this).attr('placeholder'));
}else{
if(!comprobacionModificacion(atributo,valor)){
alert("hola");
alert(id);
alert("atributo " + atributo);
alert("valor " + valor);
$.ajax({
//This is the url
url: "/listar/modificar/"+id+"/"+atributo+"/"+valor,
method: "GET",
});
}
$(this).parent().html(valor);
}
});
//web routes
Route::get('/listar/modificar/{id}/{atributo}/{valor}', 'AnimalController#modificarAnimal');
//Controller php
public static function modificarAnimal($id,$atributo,$valor){
$animal = Animal::find($id);
$animal->$atributo = $valor;
$animal->save();
}
Any idea? It doesn't do anything when it reaches the controller
Firstly if you dont put this route in except list in VerifyCsrfToken middleware, you must to use:
$.ajaxSetup ({
headers: {
'X-CSRF-TOKEN': $ ('meta[name="csrf-token"]').attr ('content')
}
});
and ensure you have meta tag csrf-token on header
Then your ajax code not doing anything after get, valor not changed. so please lookup jquery ajax done method
I finally know what's happening, it was my fault ofcourse.
I didn't had the migrations so laravel tried to update the 'animals.updated_at' . A field that is created when you do the migrations.
My fault.
Thanks for the help!
i work on laravel 5.2 and i added vinkla/laravel-pusher to do real time chat app on my site but i faced this issue:
"JSON returned from webapp was invalid, yet status code was 200."
this my controller:
public function authMessageChat(Request $req)
{
$channelName = e($req->input('channel_name'));
$socketId = e($req->input('socket_id'));
$auth = $this->pusher->presence_auth($channelName, $socketId, auth()->user()->id);
return response($auth);
}
this is my script:
var pusher = new Pusher('{{env("PUSHER_KEY")}}', {
authEndpoint: '../auth',
auth: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
params: {
id: currentUser.id
}
}
});
var channel = pusher.subscribe('{{$chatChannel}}');
channel.bind('pusher:subscription_error', function(PusherError){
console.log('PusherError' + PusherError);
});
channel.bind('new-message', function(data) {
console.log(data.sender);
)};
Pusher error:
#chrismou Thank you for your answer..
your answer is right and we can implement the solution in another way..
just go to your .env file and make:
APP_DEBUG=false
instead of
APP_DEBUG=true
Thank you
It looks like your app is returning the debugbar html as part of the json response.
Assuming it's the barryvdh/laravel-debugbar you're using, according to the documentation you can switch off the debug bar at runtime:
Config::set('laravel-debugbar::config.enabled', false);
I assume you'll need to add that prior to the response being sent, in the controller method/route you're using for the authentication endpoint (ie, the one you're calling the socket_auth method from)
Good day. I'm working on a admin page basically it is a content management system. I want to delete the data based on their id. But unfortunately i've encounter a error on the htpp request. here is the error.
Request URL: admin/ajax_delete
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:144.76.136.165:8181
VIEW FILE:
<span class="glyphicon glyphicon-trash"></span>
$("#delete_tpi").click(function() {
alert("Are you sure you want to delete?");
var tpi = $('.datatpi').val(); //package includes
var did = $('#data-id').val();
$.ajax({
url: '<?php echo site_url('admin/ajax_delete'); ?>',
type: 'POST',
datatype: 'html',
data: {id: did, tpi: tpi},
success:function (b){
if (b == 'Success') {
$('.#data-id').val('');
$('.datatpi').val('');
location.reload();
}
}
});
});
$('body').on('click','.edit-content-modal',function(){
var id = $(this).attr('data-id');
$('#data-id').val(id);
});
Controller file:
public function ajax_delete(){
$did = $this->input->post('id');
$ptpi = $this->input->post('tpi');
$update = $this->products_model->row_delete($did,$ptpi);
var_dump($update);
echo ($update)?'Success':'Fail';
}
MODEL FILE:
function ajax_delete($did,$ptpi){
$this->db->where('id',$did);
$this->db->delete('products',$ptpi);
return $this->db->affected_rows() > 0;
}
Because <a></a> element does not expect a value tag. You can get the ID of the clicked #delete_tpi link by using attr():
var did = $("#delete_tpi").attr('data-id');
Your POST request to admin/ajax_delete returns 500 Internal Server Error. This is a server-side error. If you use codeigniter, take a look at application/logs/*.log files that will give you detail information about the error.
I think, your problem is calling a non-existing function from model:
In your controller, you have:
$this->products_model->row_delete($did,$ptpi);
But your model, contains:
function ajax_delete($did,$ptpi){
....
}
Do you have row_delete() function in your model?
Once again, i suggest you to look at logs file, because many problems can result in server-side error.
I want to display a view to the user whenever user clicks on a button using ajax.
This is my code.
// BASE = localhost/project/public/
$('#button').click(function() {
$.ajax({
url: BASE + "user/settings",
type: 'GET'
})
.done(function( data ) {
console.log( data );
});
});
And my routes.php
Route::get('user/settings', 'UserController#getSettings');
And UserController.php
public function getSettings(){
return View::make('user.settings');
}
But output is this error:
{"error":{"type":"ErrorException","message":"Undefined offset: 0","file":"H:\\dev \\xampp\\htdocs\\lchat\\vendor\\laravel\\framework\\src\\Illuminate\\Support \\Collection.php","line":470}}
EDIT: error was in view. I fixed it.
Problem2: The page which is loading via ajax, itself contains another ajax post request. but it's not sending data via ajax anymore. refreshes the page to send data.
The jquery code:
$('#settings :submit').click(function(e){
e.preventDefault();
$.post(BASE + 'settings/save', {
'userName' : $('#userName').val()
}, function(data) {
return 'OK';
});
});
Problem solved: I used .on to bind event:
$(document).on('click', '#settings :submit', function(e){ ... } );
It's working...
Thank everyone.
Well, for starters, you have an error in your view. The error you're getting is in reference to an array you're trying to access that doesn't actually have the key you're trying to use ($arr[0]).
Once you fix the errors with the view itself, it should work fine. The JavaScript will get the data as HTML, and you can just insert it into wherever you want it to show up.
Use string method before view file
return (String) view('Company.allUserAjax');
I have a pretty simple CodeIgniter project that does some simple database work. Currently I have a controller method that deletes an item in the database. In my view, the code uses the jQuery ajax object to reference that controller, then displays either success or failure through its callbacks.
The problem is, although the controller works fine (deletes the item in the DB as expected), the ajax "error" callback is being called, instead of "success".
I'm sure I'm missing something super basic here...
Here is my controller method:
public function delete_note()
{
$this->load->helper('url');
$this->load->model('auth/user', 'User');
$this->load->database();
$note_id = $this->input->post('id');
$this->db->delete('admin_notes', array('id' => $note_id));
$this->db->query();
$this->output->set_status_header('200'); // Attempting to force the issue
}
And here is the code within the view:
$('.delete_note').each(function(){
var current = this;
this.onclick = function(event)
{
var note_id = this.title;
$.ajax({
type: "POST",
url: "/admin/delete_note",
data: { id: note_id },
success: function(data) { alert('I never see this!');},
error: function () { alert('I *always* see this!');}
});
}
});
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
Just because the database logic is working, you may be receiving issues related to something else (cross-browser perhaps?). To see the error, change your error function to be like this:
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
I'd like to thank WojtekT for reminding me to check my responses in Firebug. I was actually receiving back a 500 status code for PHP errors. My extraneous $this->db->query(); call needed to be removed.
Everything works great now.
Thanks!