select2 js empty value on load in select option - laravel-5

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

Related

Load data to Form:select in Laravel using 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>");
});
/
},

Why jquery ajax post request get error in yii2?

js:
$.ajax({
url: '/site/updateuserdata',
method: 'POST',
//async: true,
//cache:false,
data: {
'type': 'sort'
//val: val
//csrfParam: csrfToken
},
dataType: 'text',
error: function(jqXHR, textStatus, errorThrown) {
alert('error by ajax');
},
success: function(data, status, jqXHR) {
alert('success by ajax');
}
});
Controller:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['updateuserdata'],
'allow' => true,
// 'roles' => ['*'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'updateuserdata' => ['post'],
],
],
];
}
public function actionUpdateuserdata()
{
/*if (Yii::$app->request->isAjax) {
$message = 'Ваше сообщение успешно отправлено';
Yii::$app->response->format = Response::FORMAT_JSON;
$response = [
'success' => true,
'message' => $message
];
return $response;
}*/
$f = fopen('testajax.txt','a+');
fwrite($f, 'ajax: '.(isset($_POST['type'])?$_POST['type']:'error'));
fclose($f);
if(isset($_POST['type']))
return $_POST['type'];
else return 'error1';
// return Yii::$app->getResponse()->redirect(Yii::$app->request->referrer, 302, FALSE);
}
yii.js:
function initRedirectHandler() {
// handle AJAX redirection
$(document).ajaxComplete(function (event, xhr) {
var url = xhr && xhr.getResponseHeader('X-Redirect');
alert(url); //my code
if (url) {
window.location.assign(url);
}
});
}
I see first alert(ajax error) "error by ajax" and then alert(yii.js) "..../site/updateuserdata...", why ajax error? File testajax.txt not create.
I tried comment 'updateuserdata' => ['post'], and get error too.
Updated.
Also, tried:
public function beforeAction($action)
{
if ($action->id == 'updateuserdata') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
and uncomment csrf parameters in ajax.
And 'error' return status 302(jqXHR.status).
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
I find problem, it's stupid problem:
url: '/mag/updateuserdata/',
i have in 'urlManager':
'suffix' => '/',
i think this added for all, but not.....
Cause you commented
//csrfParam: csrfToken
from your ajax js file you have 400 http status code in your ajax.
So you can solve it in two way:
one: disable csrf validation by adding
$this->enableCsrfValidation = false;
in your actionUpdateuserdata method.
two: add csrf token and csrf param to your ajax.
print this code in your js, where you commented it.
Yii::$app->request->csrfParam . ':' . Yii::$app->request->csrfToken
then your request sent successfully and if you have other error you must check your code.

insert data in WordPress database as non-logged in user

I created a custom post type called 'visitor'. and I have an input in the front end. when the user saves input, I want to grab that data and post it as 'title' in my 'visitor' post type.
in functions.php-
$secureInfo= array(
'site_url' => get_site_url(),
'nonce' => wp_create_nonce("wp_rest")
);
wp_localize_script( "main-js", "data", $secureInfo);
in main.js-
sendUserInfo(){
var grabbingInfo = {
"title" : this.alertBoxInput.val() //my targeted input
}
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader("X-WP-Nonce", data.nonce);
},
url: data.site_url + "/wp-json/wp/v2/visitor", //custom post type
data: grabbingInfo,
type: "POST",
success: (res) => {
console.log("success");
console.log(res);
},
error: (res) => {
console.log("sorry");
console.log(res);
}
});
}
however, this code works for logged in user and says unauthorized for public users. but I don't care if a user is logged in or not. any suggestion?

Using infinite scroll AJAX load more with URL search parameter

I have an infinite scroll working on my site. It works perfectly well on category pages, e.g.
example.com/example
However, it doesn't work when I try to use it on a search page, e.g.
example.com/example//?search=true&gender=female
I know I need to pass more parameters to the AJAX call, I'm just not sure how. The shortcode is like so...
do_shortcode('[talent taxonomy="'.$_GET['params']['taxonomy'].'" term="'.$_GET['params']['term'].'" page="'.$_GET['params']['page'].'" per_page="'.$_GET['params']['per_page'].'"]');
And the AJAX data:
var ajax_data = {
page:1,
taxonomy:"'.$a['taxonomy'].'",
term:"'.$a['term'].'",
per_page:"'.$a['per_page'].'",
max_pages: '.$my_query->max_num_pages.'
};
UPDATE: Here's the talent function called in functions.php:
function talent_func( $atts ) {
$a = shortcode_atts( array(
'term' => false,
'taxonomy' => false,
'per_page' => 4,
'page' => 1,
'gender' => 1,
'orderby' => 1,
), $atts );
Here is the AJAX:
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
dataType: 'html',
data: {
'action':'talent_ajax',
'params': ajax_data,
'option':orderby
},

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