Load data to Form:select in Laravel using Ajax - ajax

So I have this Form in Blade
{!! Form::select('jobslist[]', $jobs, null, ['id' => 'jobs', 'class' => 'form-control jobs mav-select', 'multiple', 'style' => 'width: 60%; margin-top: 10px;', 'disabled'=>'disabled']) !!`}
I am trying to load $jobs data using Ajax, so I rewrote the form as
{!! Form::select('jobslist[]', [], null, ['id' => 'jobs', 'class' => 'form-control jobs mav-select', 'multiple', 'style' => 'width: 60%; margin-top: 10px;', 'disabled'=>'disabled']) !!}
And added onload script underneath
function loadData(card){
$.ajax({
type: 'POST',
url: '/loadJobs/',
data: {name: card, element: '{{$posting->id}}'},
dataType: 'json',
success: function (response) {
console.log(response);
$("#jobs").html('');
$("#jobs").html(response.options);
})
},
error: function(response){
console.log('Error: ', response["responseText"]);
}
});
}
Through console log I can verify that I am hitting the controller and obtaining data in the format
Object:
options:
27969: "2016-230 :: PL"
27974: "2016-231 :: ML"
27989: "2016-233 :: RF"
how should I pass it to the select box?

You can use append to add the items to select in the success function:
success: function(response){
...
$('#jobs').append('<option value='+response.id+'>' +response.name+ '</option>')
...
}
There you have it, just change 'id' and 'name' as necessary, I hope it helps.

//...
success:function(response){
var len = response.length;
$("#jobs").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#jobs").append("<option value='"+id+"'>"+name+"</option>");
}
}
//...

success: function(data){
console.log('success');
console.log(data);
jobs = data;
$.each(data, function(key, target){
//Use the Option() constructor to create a new HTMLOptionElement.
var option = new Option(target.name, target.id);
//Convert the HTMLOptionElement into a JQuery object that can be used with the append method.
$(option).html(target.name);
//Append the option to our Select element.
$("#jobs").append(option);
//$("#jobs").append("<option> An Option </option>");
});
/
},

Related

select2 js empty value on load in select option

I have implemented select2js in my project, In few cases when i load my page, an empty value is appending to my select input box. Can anyone help me out, what is the issue,
I have added a image of it and My code is
{!! Form::select('searchSkillTools[]',[],(isset($skillToolXref) && $skillToolXref!='')?$skillToolXref:'', array('autocomplete' => 'off', 'class' => 'chosen-select','multiple'=>'multiple', 'id' => 'searchSkillTools-'.$randomId, 'placeholder' => '' ,'style' => 'height: auto !important')) !!}
$('#searchSkillTools-{{$randomId}}').select2({
ajax: {
url: skillToolUrl,
dataType: 'json',
method:'get',
delay: 250,//delay in response
data: function (data) {
return {
search: data.term //search term
};
},
/*option to transform the data returned by response into the format expected by Select2*/
processResults: function (response) {
return {
results:response
};
},
cache: true
}
});
This way will fix the bug:
(isset($skillToolXref) && $skillToolXref!='')?$skillToolXref:null

Yii1: CGridView link ajax request shows 400 Bad Request

I am working on Yii 1 application. In my application, there is a CGridView where there is a link, which also fires an ajax request on onclick event. I am sending id as parameter. But the ajax return 400 Bad Request error. Please help me in this matter.
Here is the Gridview:
<h3>Civil Cases</h3>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'notifications-grid',
'dataProvider'=>$dataProvider_civil,
'summaryText' => false,
'columns'=>array(
array(
'name' => 'case_id',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->case_id),array("civilcases/view","id"=>$data->case_id), array("onclick"=>"js:readNotification($data->id)"))'
),
array(
'name' => 'caseno',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->caseno),array("civilcases/view","id"=>$data->case_id), array("onclick"=>"js:readNotification($data->id)"))'
),
'date_filing',
'next_date',
'panel_lawyer_id',
),
));
?>
here is the script:
<script>
var readNotification = function(id) {
console.log("button clicked with ID: "+id); //getting id here
$.ajax({
type:'POST',
url:'<?php echo Yii::app()->createUrl("notifications/readNotification");?>',
data: {id: id}
});
};
</script>
here is the controller:
public function actionReadNotification(){
echo $_POST['id'];
}
added readNotification function to the accessRules. When clicking on the link new page is loading but ajax request shows error.
Try adding the csrf token inside your data with your ajax request.
<script>
var readNotification = function(id) {
console.log("button clicked with ID: "+id); //getting id here
$.ajax({
type:'POST',
url:'<?php echo Yii::app()->createUrl("notifications/readNotification");?>',
data: {id: id,<?=
Yii::app()->request->csrfTokenName?>:<?=Yii::app()->request->csrfToken?>,}
});
};
</script>
You can also disable the csrftoken by adding the below in the beforeAction()
public function beforeAction($action) {
if($action->id=='readnotification'){
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
but this is not recommended way of doing the work.
EDIT
i mistakenly added Yii::$app->request instead of Yii::app()->request as the first one is for Yii2 and not for Yii1 please change it to
<?=Yii::app()->request->csrfTokenName?>:<?=Yii::app()->request->csrfToken?>
and make sure you have the request component with the following configurations
'components'=>array(
.
.
.
'request'=>array(
'enableCookieValidation'=>true,
'enableCsrfValidation'=>true,
'csrfTokenName'=>'_my-token',
),
Note : you can change the _my-token to any other name you like

Laravel ajax 422 Unprocessable Entity even when token is matching

I'm getting 422 Unprocessable Entity error even when I'm submitting my form via Ajax.
My javascript file
$.ajaxSetup({
headers: {
'X-XSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.keywords-plan-form').submit(function(event) {
event.preventDefault();
$.ajax({
url: '/laravel/public/keywordsplans',
type: 'POST',
data: $(this).serialize(),
success: function(data){
alert(data);
// success logic
},
error: function(data){
// Error...
var errors = $.parseJSON(data.responseText);
console.log(errors);
$.each(errors, function(index, value) {
});
}
});
});
as you can see I added X-XSRF-TOKEN****strong text to ajax header.
This is my '' tag
<meta name="csrf-token" content="{{ csrf_token() }}">
my Form Data in chrome debuger
_token:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
date:
keyword[0]:Lorem ipsum
keyword[1]:Is dolor amet
keyword[2]:plumber tampa
Request Headers
X-XSRF-TOKEN:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
.....
am I doing something wrong or forgetting something?
I don't think that csrf token is the issue here. If it were you would get TokenMissmatchException and not Unprocessable Entity.
Do you happen to have a request validator in your Controller like this?
$validator = Validator::make($request->all(), [
'username' => 'required|max:30|min:6|unique:users',
'email' => 'required|email|max:50|unique:users',
'password' => 'required|confirmed|min:6',
]);
If so maybe you can do something like this:
if ($validator->fails()) {
if($request->ajax())
{
return response()->json(array(
'success' => false,
'message' => 'There are incorect values in the form!',
'errors' => $validator->getMessageBag()->toArray()
), 422);
}
$this->throwValidationException(
$request, $validator
);
}
After that you can catch validation errors in your ajax error handler like this:
$('.keywords-plan-form').submit(function(event) {
event.preventDefault();
$.ajax({
url: '/laravel/public/keywordsplans',
type: 'POST',
data: $(this).serialize(),
success: function(data){
alert(data);
// success logic
},
error: function(jqXhr, json, errorThrown){// this are default for ajax errors
var errors = jqXhr.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
});
//I use SweetAlert2 for this
swal({
title: "Error " + jqXhr.status + ': ' + errorThrown,// this will output "Error 422: Unprocessable Entity"
html: errorsHtml,
width: 'auto',
confirmButtonText: 'Try again',
cancelButtonText: 'Cancel',
confirmButtonClass: 'btn',
cancelButtonClass: 'cancel-class',
showCancelButton: true,
closeOnConfirm: true,
closeOnCancel: true,
type: 'error'
}, function(isConfirm) {
if (isConfirm) {
$('#openModal').click();//this is when the form is in a modal
}
});
}
});
});
And see the messages in the
modal message
Maybe someone will come in handy.
422 Unprocessable Entity
is default error by validator laravel
vendor/laravel/framework/src/Illuminate/Validation/Validator.php
If fails validate params, then throught Exception ValidationException
vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php
where default status = 422
And therethore all your ajax responses with non validate forms will be with status = 422
I have solved this issue :
public function register(\Illuminate\Http\Request $request) {
if ($this->validator($request->all())->fails()) {
$errors = $this->validator($request->all())->errors()->getMessages();
$clientErrors = array();
foreach ($errors as $key => $value) {
$clientErrors[$key] = $value[0];
}
$response = array(
'status' => 'error',
'response_code' => 201,
'errors' => $clientErrors
);
} else {
$this->validator($request->all())->validate();
$user = $this->create($request->all());
$response = array(
'status' => 'success',
'response_code' => 200
);
}
echo json_encode($response);
}
Whoever is still looking for the answer, if you are using Lumen make sure the Request object is a type of Illuminate\Http\Request and not the default one from Lumen.
```function create(Request $request){

Need JSON to pass values to AJAX from specific content type fields

Im new to PHP.
I'd like to build a module and i need json to pass specific content type fields.
Im trying with this but i dont know how to deal with callback function.
here is my ajax in .js
$.ajax({
type: 'GET',
url: '/mappy/ajax/poi',
data: {
nid: nid
},
dataType: 'json',
success: function(data){
alert(data)
}
});
})
here is my php in .module
function mappy_menu() {
$items = array();
$items['/mappy/ajax/poi'] = array(
'title' => 'Mappy Pois',
'page callback' => 'mappy_get',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mpapy_get() {
$nid = $_GET('nid');
$title = field_get_items('node', $node, 'field_title');
$result = json_encode(
db_query("SELECT nid,title FROM {node}", $nid)
);
drupal_json_output($result);
print $result;
}
Many thanks for advice.
Once you get the JSON response you need to convert it to a javascript array. For that, you can do:
var javaArray = $.parseJSON(data);
Now you can retrieve the data, using code like javaArray['key1']['key2'], etc.
.js
$.ajax({
type: 'GET',
// Do not use slash at the beginning, use Drupal.settings.basePath instead
url: Drupal.settings.basePath + 'mappy/ajax/poi',
data: {
nid: nid
},
dataType: 'json',
success: function(data) {
alert(data)
}
});
.module
function mappy_menu() {
$items = array();
// Never use slash at the beginning in hook_menu
$items['mappy/ajax/poi'] = array(
'title' => 'Mappy Pois',
'page callback' => 'mappy_get',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mappy_get() {
$node = node_load($_GET('nid'));
// Or equivalent
/* $node = db_select('node', 'n')
->fields('n', array('nid', 'title'))
->condition('n.nid', $_GET('nid')))
->execute()
->fetchAll(); */
$values = array(
'nid' => $node->nid,
'title' => $node->title
);
#$result = json_encode(
# db_query("SELECT nid,title FROM {node}", $nid)
#);
// drupal_json_output already print the value
// print $result;
drupal_json_output($values);
drupal_exit();
}

Concatenate multiple fields to display in autocomplete using AJAX in cakephp

currently my autocomplete works in displaying the first name of the user, but I want to concatenate the first name, last name and etc. How do I achieve this in the following code?
<script type="text/javascript">
$(function() {
$(".suggest").autocomplete({
source: function( request, response ) {
$.ajax({
url: '<?php echo $this->Html->url(array('controller' => 'searches', 'action' => 'suggestUser')); ?>',
dataType: "json",
data: {
//request.term is the value of the current textbox.
term: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.User.firstName,
value: item.User.firstName
}
}));
}
});
},
minLength : 1
});
});
In my controller, the following codes below is my logic to search for that field.
function suggestUser() {
if (isset($_GET["term"])) {
$term = $_GET["term"];
$result = $this->User->find('all', array(
'conditions' => array(
'User.firstName LIKE' => $term . '%'
),
'fields' => array(
'firstName'
)
));
if ($term) {
$this->set('results', $result);
$this->view = 'Json';
$this->set('json', 'results');
}
}
}
http://book.cakephp.org/view/1588/virtualFields
It is really simple I realised. I managed to resolve it.
label: item.User.firstName + " " + item.User.lastName,
value: item.User.firstName + " " + item.User.lastName
You also need to append the lastName field in.
'fields' => array(
'firstName',
'lastName',
)

Resources