Select2 POST AJAX Request 500 Error Laravel - javascript

I'm trying to use select2 retrieving large data in my dropdown using the following article.
Getting 500 Internal Server Error in my console log.
I have store token in HTML meta tag.
<meta name="csrf-token" content="{{ csrf_token() }}">
And sending a token as a parameter in my POST request.
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function(){
$( "#test" ).select2({
ajax: {
url: "path/to/url",
type: "POST",
dataType: 'JSON',
delay: 250,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
});
<select class="test" id="test" style="width:100%;"></select>
I have checked routes using php artisan route:list and clear cache using php artisan config:cache. But still getting the same error link. and link.
Is there anything I'm missing? I would be grateful if you can help me out to debug/inspect my Request and Response.
Tried
error: function(err){
console.log(err)
}
Server-Side \ Controller
public function getdata(Request $request){
$search = $request->search;
if($search == ''){
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->limit(5)->get();
}else{
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->where('name', 'like', '%' .$search . '%')
->limit(5)->get();
}
$response = array();
foreach($data as $i){
$response[] = array(
"id"=>$i->id,
"text"=>$i->name
);
}
return response()->json($response);
}
Happy Coding.

Related

Unable to Show Meta information with Post

I am practicing on a very simple Laravel project with AJAX and jQuery. I am trying to edit post and its meta information which I added before. I Tried console.log and its showing me post with meta information. Post is coming from posts table and meta information is coming from post_metas table where I added post_id as forign key. Post data is showing in edit modal but I am unable to put meta information in their specific fields in edit Modal.
Here is my PostController.php
public function edit($id)
{
$post = Post::with('meta')->find($id);
if ($post) {
return response()->json([
'status' => 200,
'post' => $post,
]);
} else {
return response()->json([
'status' => 404,
'message' => 'Post Not Found',
]);
}
}
Here is Index.blade.php (jQuery AJAX Code)
$(document).on('click', '.edit_post_btn', function(e) {
e.preventDefault();
var post_id = $(this).val();
var route_url = "{{ route('blog.edit', ':id') }}";
route_url = route_url.replace(':id', post_id);
$.ajax({
type: "GET",
url: route_url,
success: function(response) {
if (response.status === 200) {
console.log(response.post);
$('#edit_title').val(response.post.title);
$('#edit_excerpt').val(response.post.excerpt);
$('#edit_content').val(response.post.content);
$('#edit_min_to_read').val(response.post.min_to_read);
$('#edit_meta_description').val(response.post.meta_description);
$('#edit_meta_keywords').val(response.post.meta_keywords);
$('#edit_meta_robots').val(response.post.meta_robots);
} else {
console.log(response.message);
}
}
});
});
And This is My route:
Route::get('/edit/{id}', [PostController::class, 'edit'])->name('blog.edit');
See File Please:
Meta information is in the meta object:
$('#edit_meta_description').val(response.post.meta.meta_description);
$('#edit_meta_keywords').val(response.post.meta.meta_keywords);
$('#edit_meta_robots').val(response.post.meta.meta_robots);

laravel cannot post data with ajax server status 419

I am doing a project with Laravel.
When I change the selected option of the following select element I should insert the selected value to mysql database to retrieve all the data about the selected id from the server (for example the name of the user).
This is the select element (adminArea.blade.php):
<select name="employees" onchange="fillEmployeeData(this)" class="form-control col-sm-6" id="employees">
<option value="0"></option>
#foreach ($users as $user)
<option value="{{ $user->id }}">{{ $user->surname . ' ' . $user->name }}</option>
#endforeach
</select>
And this is the called function (adminArea.blade.php)::
function fillEmployeeData(emp_id) {
var emp_selected = emp_id.value;
$.ajax({
type: "POST",
url: "{{ route('adminAreaPostEmployee') }}",
data: 'emp_selected=' + emp_selected,
success: function (data) {
var emp_data = JSON.parse(data);
alert(emp_data);
}
});
};
These are my routes (web.php):
Route::get('/adminarea', 'AdminAreaController#index')->name('adminArea');
Route::post('/adminarea/postemployee', 'AdminAreaController#post_employee')->name('adminAreaPostEmployee');
And these are my controller methods (adminAreaController.php):
public function post_employee(Request $request)
{
$select = $request->get('emp_selected');
$user = User::where('id', $select);
echo $user;
}
public function index()
{
$operations = Operation::all();
$users = User::all()->sortBy('surname');
$rooms = Room::all();
return view('adminArea', compact('users', 'rooms', 'operations'));
}
However, when I change the selected value nothing happens... and if I go to the developer tools I see the following error:
Failed to load resource: the server responded with a status of 419
(unknown status).
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods:
POST.
I don't see any alert. Someone can help me?
The HTTP status code for the MethodNotAllowedHttpException is 405
See here
public function __construct(array $allow, string $message = null, \Throwable $previous = null, ?int $code = 0, array $headers = [])
{
$headers['Allow'] = strtoupper(implode(', ', $allow));
parent::__construct(405, $message, $previous, $headers, $code);
}
A TokenMismatchException HTTP status code is 419
See here
protected function prepareException(Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
} elseif ($e instanceof AuthorizationException) {
$e = new AccessDeniedHttpException($e->getMessage(), $e);
} elseif ($e instanceof TokenMismatchException) {
// HTTP Status code is send in the header here
$e = new HttpException(419, $e->getMessage(), $e);
} elseif ($e instanceof SuspiciousOperationException) {
$e = new NotFoundHttpException('Bad hostname provided.', $e);
}
return $e;
}
So this appears to be a CSRF token issue
Make sure that you have a meta tag on the head of your document like this
<meta name="csrf-token" content="{{ csrf_token() }}">
Also from the JQuery Ajax Documentation
I think that the HTTP method should be defined as method parameter not type (though type works ¯\_(ツ)_/¯)
// Send a CSRF token header with every Ajax request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function fillEmployeeData(emp_id) {
var emp_selected = emp_id.value;
$.ajax({
method: "POST",
url: "{{ route('adminAreaPostEmployee') }}",
data: 'emp_selected=' + emp_selected,
success: function (data) {
var emp_data = JSON.parse(data);
alert(emp_data);
}
});
};
But now you're gonna get an error
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
Because you're trying to return a query builder instance User::where('id', $select) instead of the user record itself serialized
I think you may want to do this
public function post_employee(Request $request)
{
$select = $request->get('emp_selected');
return User::find($select);
}
Hope this helps
Try to 'method' instead of 'type' . You should use type if you're using versions of jQuery prior to 1.9.0
function fillEmployeeData(emp_id) {
var emp_selected = emp_id.value;
$.ajax({
method: "POST",
url: "{{ route('adminAreaPostEmployee') }}",
data: 'emp_selected=' + emp_selected,
success: function (data) {
var emp_data = JSON.parse(data);
alert(emp_data);
}
});
};
this is a CSRF protection of laravel,
you can add csrf meta tag in the head
<meta name="csrf-token" content="{{ csrf_token() }}">
and in the top of the script write
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

crud ajax jquery symfony3 wont work

Problem: How do I validate the form and return the validation messages in modal box without refreshing the page.
I just started learning Symfony 3 and I got trouble adding data using AJAX.
I know how to include the template form inside of the modal box but I don't know how to show the error messages of $form->isValid() inside the modal and persist it.
new.html.twig
UPDATE: I can now call the method action in Controller. But when I validate the form I haven't received any validation error inside modal box.
<script>
$(function () {
$('.withdropdown').dropdown();
$('.add-company-launch').modal();
$('#company-form').submit(function(e) {
var formUrl = "{{ path('monteal_backend_company_ajax') }}";
var formData = new FormData(this)
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data, textStatus, jqXHR)
{
if(data['status'] === 'success'){
alert('success');
} else {
$('#add-company').html(data['html']);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault();
});
})
</script>
{% endblock %}
CompanyController.php
UPDATE: I have create two methods for AJAX,
1. Method to handle a form.
2. AjaxHandler.
public function newAction() {
$company = new Company();
$form = $this->createForm(CompanyForm::class, $company);
return $this->render('Admin/Backend/Company/new.html.twig', array(
'form'=>$form->createView()
));
}
public function ajaxAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$company = new Company();
$form = $this->createForm(CompanyForm::class, $company);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($company);
$em->flush();
return new JsonResponse(array(
'status' => 'success'), 200
);
}
$html = $this->renderView("Admin/Backend/Company/new.html.twig", array(
'form' => $form->createView())
);
return new JsonResponse(['status' => 'error', 'html' => $html]);
}
1 - In your newAction, just create the form and pass the view (createView) to your template.
2 - write a ajaxFormHandlerAction and here create the form, handle it, validate it, render a view in a variable :
$html = $this->renderView('yourTemplate.html.twig', array($form->createView()));
Edit: of course your ajax must post the form to your newly ajax url... END Edit
3 - if it is'nt validated
Return a JsonResponse(array('html' => $html, 'status' => 'error'));
if validated
Return a JsonResponse(array('status' => 'success'));
4 - In your ajax success callback, render the newly form if status error..
if status success, redirect or whatever
Hope this help
Edit :
something like this for your controler :
use Symfony\Component\HttpFoundation\JsonResponse;
public function ajaxFormHandlerAction(Request $request)
{
$company = getYourCompany(); //get it from db?
$form = $this->createForm(CompanyForm::class, $company));
$form ->handleRequest($request);
if($form ->isValid()){
//do whatever you want, maybe persist, flush()
return new JsonResponse(array(
'status' => 'success'));
}
$html = $this->renderView("yourModalTemplate.html.twig", array('form' => $form->createView()));
return new JsonResponse(['status' => 'error', 'html' => $html]);
}
And in your success ajax callback:
success: function(data, textStatus, jqXHR)
{
if(data['status'] === 'success'){
alert('success');
// maybe redirect the user ???
}else if(data['status' === 'error']){
$('#idOfYourModal').html(data['html']); //assuming you use jquery, or translate to javascript
}
},
You have to create a twig template with only the modal inside...

How to pass hidden field value via ajax to codeigniter controller

I have a view file which contains a button (link):
<a href id="savebutton" class="btn btn-warning">Save</a>
Somewhere else in this view I have also declared some hidden fields in a form that contain my userid and vacancyid.
echo form_input(dataHiddenArray('userid', $this->auth_user_id));
echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy_id));
These hidden fields translate to:
<input type="hidden" value="2" class="userid">
<input type="hidden" value="1" class="vacancyid">
Now I want to be able to send these values to my controller (via AJAX) so that I can insert them in my database.
My JS file looks like this:
$(function() {
var postData = {
"userid" : $("input.userid").val(),
"vacancyid" : $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
cache: false,
type: 'POST',
url: "<?php echo base_url();?>dashboard/vacancy/saveVacancy",
contentType: 'application/json',
dataType: 'text'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function(data) {
alert(data); // plausible [Object object]
//alert(data[0]); // plausible data
console.log(data); // debug as an object
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
And my controller looks like this (it is not doing much because it doesn't return anything):
public function saveVacancy() {
//$this->load->model('user/usersavedvacancies_model');
/*$data = array(
'userid' => $this->input->post('userid'),
'vacancyid'=>$this->input->post('vacancyid')
);*/
echo $this->input->post('userid');
}
Minor changes to javascript
$(function () {
var postData = {
"userid": $("input.userid").val(),
"vacancyid": $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
type: 'POST',
url: "<?php echo base_url('dashboard/vacancy/saveVacancy);?>",
dataType: 'json'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function (data) {
console.log(data); // debug as an object
if (data.result === 'success') {
alert("Yeah, it saved userid " + data.userid + " to vacancy id " + data.vacancyid);
}
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
});
In the controller
public function saveVacancy()
{
//assigning a more useable object name to the model during load
$this->load->model('user/usersavedvacancies_model', 'save_vacancy');
$data = array(
'userid' => $this->input->post('userid'),
'vacancyid' => $this->input->post('vacancyid')
);
//send data to model and model returns true or false for success or failure
$saved = $this->save_vacancy->doSaveId($data); //yes, I made up the method, change it
$result = $saved ? "success" : "failed";
echo json_encode(array('result' => $result, 'userid' => $data['userid'], 'vacancyid' => $data['vacancyid']));
}
You need to understand that $.ajax takes two methods i.e GET and POST and from the documentation you can see that default method is GET so Since you have not defined method as GET/POST probably the method is taken GET so first change define ajax method to POST as well as you need to be clear about dataType of ajax it may be one of JSON/html and default is json.
$.ajax({
method: "POST",
url: url,
data: data,
dataType:'html'
});
I guess this helped you can learn detail from
Learn more.

$this->request->is('ajax') always false

I have the code in my view but on sending to my controller action via ajax(as shown in the last part of the add.ctp)
//add.ctp
<?php
echo $this->Form->create('Poll',array('action' => 'index'));
echo $this->Form->input('one', array('id'=>'name'));
echo $this->Form->input('two', array('id'=>'email'));
echo $this->Form->input('three', array('id'=>'message'));
echo $this->Form->input('four', array('id'=>'four'));
echo $this->Js->submit('Send', array('id' => 'btn'), array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));
echo $this->Form->end();
?>
<div id="sending" style="display: none; background-color: lightgreen;">Sending...</div>
<script>
$('#btn').click(function(event) {
form = $("#PollIndexForm").serialize();
// console.log(form);
$.ajax({
type: "POST",
url: 'pollsController/index';,
data: form,
success: function(data){
//
}
});
event.preventDefault();
// return false; //stop the actual form post !important!
});
</script>
on getting to my controller, I made an isAjax request test and if failed
public $components = array('RequestHandler');
public function index(){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
echo debug('Ajax call');
}
if(!empty($this->data)){
echo debug('not empty');
}
}
I get 'not empty' every time i tried to run this and $this->request->is('ajax') is always false
My version of cakephp is 2.3 and I have tried $this->request->is('ajax') and all that.
I'll appreciate if someone can point out what I am missing out
In your code, you have
if($this->RequestHandler->isAjax()){
Try to make the condition this way:
if ($this->request->is('ajax')) {
}
http://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html?highlight=isajax#requesthandlercomponent
RequestHandlerComponent: Many of RequestHandlerComponent’s methods are
just proxies for CakeRequest methods. The following methods have been
deprecated and will be removed in future versions: isSsl() isAjax()
isPost() isPut() isFlash() isDelete() getReferer()getClientIp()
Are you sending with your AJAX call the right headers?
{ 'X-Requested-With': 'XMLHttpRequest'}
If you are using jQuery, you can use:
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
You can check it in Chrome developer tools under the network tab, where you must select your request.
and here is the documentation for ajaxSetup()
EDIT:
You can put it here:
<script>
$('#btn').click(function(event) {
form = $("#PollIndexForm").serialize();
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
$.ajax({
type: "POST",
url: 'pollsController/index';,
data: form,
success: function(data){
}
});
event.preventDefault();
// return false; //stop the actual form post !important!
});
</script>

Categories

Resources