two ajax request url (success/fail) - javascript

Good day,
I was in some disarray . I have a ajax request from select2. Also I have two urls. How should I event organized If / else success/failure statements, if suddenly one will not work , then send an inquiry to another link?
I'm trying again and again and alwas there is error somewhere((
$(".js-data-example-ajax").select2({
language: "ru",
placeholder: "Serach.........",
disabled: false,
selected: true,
ajax: {
url: "url_1",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term + "%", // search term
};
},
processResults: function (data) {
if (data.features.length > 0) {
var resultArray = [];
$.each(data.features, function (index, value) {
value.attributes.id = value.attributes.OBJECT_ID;
resultArray.push(value.attributes);
});
return {
results: resultArray
};
} else {
return []
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 5,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

It should be quite simple because you only have to call the first url and, on error, call the second.
$.ajax(function(data){
url: "url_1",
...,
success(function(data){
//do stuff on success
}),
error(function(e){
$.ajax(function(data{
//call the second url
})
})
})

Related

How to provide a datasource for Select2 with October CMS via the built in Ajax Framework

October CMS provides an extensive AJAX framework, that I'm looking to use to populate a Select2 box with.
According to Select2, using a remote dataset happens as follows:
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
But from the October CMS docs, I cannot figure out how to pass the data to the server manually.
Questions are: which URL to use, and which parameters do I need to pass along so that October knows which function I want to access. Also, how can I capture the result without a partial being loaded?
This might be a trivial question; I might be looking in the wrong direction. Maybe the AJAX framework should not be used at all. Any insights on the correct way to proceed?
** EDIT FOLLOWING CORRECT ANSWER BY SAMUEL **
To make Select2 work with a remote dataset in combination with October CMS,
please take into account the following pitfalls. Below is my working code:
// SELECT 2
$('select').select2({
/*placeholder: "Your placeholder", // Remove this, this causes issues*/
ajax: {
// Use transport function instead of URL as suggested by Samuel
transport: function(params, success, failure) {
var $request = $.request('onSelect', {
data: params.data
});
$request.done(success);
$request.fail(failure);
return $request
},
dataType: 'json',
delay: 250,
data: function (params) {
console.log(params);
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data,params) {
console.log(data);
return {
// The JSON needs to be parsed before Select2 knows what to do with it.
results: JSON.parse(data.result)
};
},
cache: true
},
minimumInputLength: 1
});
Below is the example output I used in combination with this Select2 example:
[
{
"id":1,
"text":"Henry Kissinger"
},
{
"id":2,
"text":"Ricardo Montalban"
}
]
Above JSON was generated by my VisitorForm.php file:
<?php namespace XXX\VisitorRegistration\Components;
use Cms\Classes\ComponentBase;
use XXX\VisitorRegistration\Models\Visitor;
use October\Rain\Auth\Models\User;
class VisitorForm extends ComponentBase {
public function componentDetails()
{
return [
'name' => 'Visitor Form',
'description' => 'Description of the component'
];
}
// The function that returns the JSON, needs to be made dynamic
public function onSelect() {
return json_encode(array(array('id'=>1,'text'=>'Henry Kissinger'), array('id'=>2,'text'=>'Ricardo Montalban')));
}
}
VoilĂ , hope this can be useful.
Pass the transport option instead of url. Here is an example:
$(".js-data-example-ajax").select2({
ajax: {
transport: function(params, success, failure) {
/*
* This is where the AJAX framework is used
*/
var $request = $.request('onGetSomething', {
data: params.data
})
$request.done(success)
$request.fail(failure)
return $request
},
dataType: 'json'
},
// ...
});

jquery Select2: How to add attributes to li element in DropDown

I use the select2 plugin from jquery and get my data over an ajax load. When I set the response I want to add attributes to the li-elements of my dropdown.
I already tried it with calling a function in "templateResult" but there I can only give back the vakue which is IN the <li></li> tags
My javascript:
var autocomplete = function () {
$("body").find("#myDropDown").select2({
language: "es",
ajax: {
url: searchDataUrl,
type: "POST",
// dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
return {
results: data.userData,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true // add additional parameters
}
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatReponse, //With this it doesnt work
});
};
And the function from my templateResult Call:
//When I do this, I have a "<li>"-Tag within a "<li>"-Tag
var formatReponse = function (data) {
return '<li data-id="'+data.id+'" class="select2-results__option" role="treeitem">'+data.text+'</li>';
};
Can anybody help me with this? THANKS!
use the .attr(att,val) function like this:
Give your <li> an id name like liID in <li id='liID'> the following example
then give the name of the attribute you want to change in the example given as attributeToChange then give the value you want to set in the atribute in the example: valueToSet. good luck
$('#liID').attr('attributeToChange', 'valueToSet');

Select2 - infinite scroll not loading next page with remote data

I am using Select2 4.0.1, I have used ajax to populate the result based on users input, but whenever I search for anything select2 lists first page result, but consecutive pages were not loading, also request is made for 2nd page on scroll. seems to be I am missing something.
$multiselect = $(element).select2({
closeOnSelect: false,
multiple: true,
placeholder: 'Assign a new tag',
tags: true,
tokenSeparators: [","],
ajax: {
url: '/search_url',
dataType: 'json',
type: 'GET',
delay: 250,
data: function(params) {
return {
search: params.term,
page: params.page
};
},
processResults: function(data, params) {
var more, new_data;
params.page = params.page || 1;
more = {
more: (params.page * 20) < data.total_count
};
new_data = [];
data.items.forEach(function(i, item) {
new_data.push({
id: i.name,
text: i.name
});
});
return {
pagination: more,
results: new_data
};
},
cache: true
}
})
Any help is much appreciated.Thnx:)
This is the code I got working last week. I am using a different transport on my end, but that shouldn't make a difference. I was having the same issue as you regarding the lack of paging working while scrolling. My issue ended up being that I didn't have the proper {'pagination':{'more':true}} format in my processResults function. The only thing I can see that may work for you is to "fix" the page count in the data function vs. the processResults function.
When you scroll to the bottom of your list, do you see the "Loading more results..." label? Have you attempted to hard code the more value to true while debugging?
this.$(".select2").select2({
'ajax': {
'transport': function (params, success, failure) {
var page = (params.data && params.data.page) || 1;
app.do('entity:list:search',{'types':['locations'],'branch':branch,'limit':100,'page':page,'term':params.data.term})
.done(function(locations) {
success({'results':locations,'more':(locations.length>=100)});
});
}
, 'delay': 250
, 'data':function (params) {
var query = {
'term': params.term
, 'page': params.page || 1
};
return query;
}
, 'processResults': function (data) {
return {
'results': data.results
, 'pagination': {
'more': data.more
}
};
}
}
, 'templateResult': that.formatResult
, 'templateSelection': that.formatSelection
, 'escapeMarkup': function(m) { return m; }
});

Select2(4.00) return undefined in onSelect event when useing ajax

I'm using Select2 (ver 4.00) and loading remote data with ajax method.
I need to retrieve title of selected option, but in select2:select event data is undifined
my code:
$(".js-data-action-terms").select2({
ajax: {
url: ajaxurl + "?action=terms",
dataType: 'json',
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: false
},
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
$('.js-data-action-terms').on("select2:select", function(e) {
console.log(e);
});
Result log:
In Select2 4.0.0, the selected object was moved from the evt.data property to evt.params.data. Now all extra data for events in Select2 is put in evt.params for consistency.

angular-ui select2 initSelection not getting called

I have an angular-ui select2 component on my page. It works fine when the user types something in (it uses ajax to load in the data).
But the initSelection function never gets called. Here's the configuration object I pass into the select2
{
multiple: true,
minimumInputLength: 1,
tokenSeparators: [",", " "],
createSearchChoice: function (term) {
return term;
},
width: 'resolve',
ajax: {
url: '...',
method: 'GET',
quietMillis: 100,
data: function (term, page) {
...
},
results: function (data, page) {
...
}
},
initSelection: function (element, callback) {
console.log('initSelection');
return $.ajax({
url: "...",
type: "GET",
data: {
...
},
}).done(function(data) {
console.log(data);
return callback(data);
});
}
};
"initSelection" never gets logged to the console. Why isn't initSelection getting called?
initSelection is only called when there is initial input to be processed (see blue box just above here - the closest place to link to, I'm afraid). I suspect this may be your problem from the way the question is worded.
I'm able to do selected value as Edit time using InItSelection in Angular Js.
$scope.partInitSelection = function (element, callback) {
var resultArray = [];
resultArray.push({ id: "1", text: "hi" });
$scope.HospitalizationView.HospitalName = resultArray[0];
callback(resultArray[0]);
};

Categories