I'm trying to put checkbox checked in an array (checkBoxArray) and send it via ajax to my php request file using the Select2 jQuery plugin.
But the filter value is always empty.
//Here the checkBox array
$('.chkfilters').on("change", function() {
var checkBoxArray = $('.chkfilters:checked').map(function(i,n) {
return $(n).val();
}).get(); //get converts it to an array
});
// Here the Select2 plugin
$(".searchInput").select2({
placeholder: "Rechercher un article, une référence...",
minimumInputLength: 3,
ajax: {
url: "/suggest",
dataType: 'JSONP',
type: 'GET',
data: function (term, page, checkBoxArray) {
return {
q: term,
page_limit: 10,
page: page,
filter : checkBoxArray
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {
results: data.articles,
more: more
};
}
},
createSearchChoice: function(term, checkBoxArray) {
return {
text:term,
tform:'/recherche',
filter : checkBoxArray
};
},
...
});
Code from my project. It works:
$('.lstProgramStoplistId').select2({
ajax: {
url: programsUrl,
dataType: 'json',
contentType: 'application/json',
type: 'POST',
delay: 250,
data: function (params) {
var lstProgramCategoryId = $('.lstProgramCategoryId').select2('val');
return JSON.stringify({
str: params.term,
lstProgramCategoryId: lstProgramCategoryId
});
},
processResults: function (data, params) {
return {
results: data.items
};
},
cache: false
},
minimumInputLength: 2
});
Related
I'm trying to implement AJAX Request to Codeigniter 4.21 route and bind it to select2, the result data was OK, but won't binded to select2. Is there any solution?
Controller
public function getSpesialis(){
$response = array();
$userlist = $this->spesialisModel->findAll();
$data = array();
foreach($userlist as $user){
$data[] = array(
"id" => $user['id'],
"spesialis" => $user['spesialis'],
);
}
$response['data'] = $data;
return $this->response->setJSON($response);
}
Jquery
<script>
$('#spesialis').select2({
placeholder: "Pilih Spesialisasi...",
ajax: {
url: '/getspesialis',
type: 'GET',
dataType: 'JSON',
delay: 250,
processResults: function(data) {
return {
results: data
};
}
},
});
it's DONE with this... thanks all
$('#spesialis').select2({
placeholder: "Pilih Spesialisasi...",
ajax: {
url: '/getspesialis',
type: 'GET',
dataType: 'JSON',
delay: 250,
processResults: function({
data
}) {
return {
results: $.map(data, function(item) {
return {
id: item.id,
text: item.spesialis
}
})
}
}
},
});
I want to get the return result of a php function in an Ajax request in order to make some verification in onSucces. How can I get the JSON result from the php function into the ajax request?
public function verifyEmailAction()
{
$is_valid = true;
$is_duplicate = false;
$email_reset = false;
$register = $this->getRegisterHelper();
$register->addEmailCheck();
$register->setData($this->getAllParams());
$validationErr = $register->getValidationResult();
if (!empty($validationErr['badWords']['email']) || $validationErr['banned']['email'] == true
|| empty($validationErr['isEmailValid'])
) {
$is_valid = false;
} elseif (!empty($validationErr['duplicates']['email'])) {
$is_duplicate = true;
$email_reset = $this->sendResetEmail();
}
$result = [
'duplicate' => $is_duplicate,
'valid' => $is_valid,
'reset' => $email_reset
];
$this->getResponse()->setBody(json_encode($result));
}
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
}
});
});
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json',
success:function(response){
console.log(response);
var duplicate=response.duplicate;
var valid=response.valid;
var reset=response.reset;
},
error:function(err){
console.log('Error '+err);
}
});
You need to use the success and error functions like below,
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
success : function(data, status, xhr) {
console.log(JSON.stringify(data));
},
error: function(jqXhr, textStatus, errorMessage){
console.log("ERROR " + errorMessage);
}
});
});
$.ajax({
type: 'GET',
url: url,
data: {
'email': value
},
dataType:'json',
}).success(function(response){
//YOUR Json KEY
if(response.success){
}
});
I hope this article will help you.
http://api.jquery.com/jquery.ajax/
Specially you can use this
jQuery.ajax({
url: "YOURURL",
type: "YOURTYPE",
dataType:"json",
}).done(function(data) {
console.log(data) // to see the reqested data
// manipulate data here
});
Add dataType:'json':
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json'
});
});
You can use this to convert JSON string to a JavaScript object:
var txtReturned = JSON.parse(data);
Reference:
jQuery AJAX Call to PHP Script with JSON Return
$('#lev_nr').on('input', {
source: function(request, response) {
$.ajax({
url : 'pallavvikelse/jsonData',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'lev_table',
row_num : 1
},
success: function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function(event, ui) {
var names = ui.item.data.split("|");
$('#lev_namn').val(names[1]);
var txt = $('#avta').val(names[2]);
if (txt.val() == "ja"){
$('#t').hide();
}
} }).trigger('input');
Can someone see why this does not work?
I am trying to change autocomplete function to on.input but I can't get it to work.
The code works perfectly when i change the first line to $('#leverantors_nr').autocomplete({
and when I remove .trigger('input')
$('#lev_nr').on('input', function() {
$.ajax({
url: 'pallavvikelse/jsonData',
data: {
name_startsWith: this.value,
type: 'country_table',
row_num: 1
},
dataType: 'json',
success: function(data) {
alert(data);
var names = data.split('|');
alert(names[0]);
}
});
});
I have managed to make it work this far, but when i try to alert(names[0]) i get nothing when alert(data) i get resault.. The data i get loocks like this: 5000950|TEST|BLABLA
Wen i try to split and alert again it dosent work
$('#leverantors_nr').on('input', function() {
$.ajax({
url: 'pallavvikelse/jsonData',
data: {
name_startsWith: this.value,
type: 'country_table',
row_num: 1
},
dataType: 'json',
success: function(data) {
alert(data.lev_namn);
}
});
});
Problem solved:
i changed the database so it outputs array like this:
$arr['lev_nr'] = $row->lev_nr;
$arr['lev_namn'] = $row->lev_namn;
I think you are not properly parsing JSON data.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Just downloaded a select2 files from github, the latest release 4.0.3, and i want to populate the options based on what i'm typing (ajax request)
heres the code
$('#usernetwork').select2({
ajax: {
url: 'someurl.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return data.items;
},
cache: false
},
minimumInputLength: 1
});
the url (someurl.php) shows this json result
[{"id":"1","text":"ClickWeb"},{"id":"2","text":"ClickWeb 1"},{"id":"3","text":"ClickWeb 2"},{"id":"4","text":"ClickWeb 3"}]
and finally the select field is this
<select name="usernetwork" id="usernetwork" class="form-control">
</select>
this is the very first time i try this for now im getting nothing as query (for test purposes)
The results are not showing up, and i have no idea on how to fix this, any tips?
Try my answer the only thing you need to change is your return statement inside processResults callback like this
return {
results: data
};
Here is full code :
$('#usernetwork').select2({
ajax: {
url: 'someurl.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: data
};
},
cache: false
},
minimumInputLength: 1
});
I want to request ajax many time in for loop . But it only return 1 value . result.ID. Can anyone help me?
$('#show').html('');
var min = parseInt($('#number_coupon_from').val());
var max = parseInt($('#number_coupon_to').val());
var total_time = parseInt($('#time_coupon').val())*1000;
var randcoupon = Math.floor(Math.random()*(max-min+1)+min);
var timetb = total_time/randcoupon;
var random = 0;
var i,j;
for(i=0;i<randcoupon;i++)
{
for(j=random;j>=0;j--)
{
if(j==0)
{
$.ajax({
url: 'backend/publish_auto/update',
type: 'post',
data: {},
dataType: 'json',
success: function (result)
{
if(result.st)
{
$('#show').append('Update Coupon ID: '+result.ID+'<br />');
}
}
});
}
}
}
});
Thank you !!
use async:False to get ajax response one by one
$.ajax({
url: 'backend/publish_auto/update',
async: false,
type: 'post',
data: {},
dataType: 'json',
success: function (result)
{
if(result.st)
{
$('#show').append('Update Coupon ID: '+result.ID+'<br />');
}
}
});