I'm having a problem with a JSON conversion by jQuery AJAX.
Ajax Setup
$.ajax({
url: 'ajax/get_available_schedule.php',
type: 'GET',
dataType: 'json',
data: {field: field, day: day, hour: inicio},
})
I have this response from server
{"success":true,"ranges":[["22:00","22:30"],["22:30","23:00"],["01:30","02:00"],["02:00","02:30"]],"close":"03:30"}
But at the moment I do a 'console.log' of the response in the Ajax success, it will convert to this:
close: "03:30"
ranges: Array(2)
0: (2) [5400, 9000]
1: (2) [79200, 82800]
success: true
I don't know why the 'ranges' array are converted to numbers, I want that be likely the response, an array of 2 strings
I try to Google the problem but I don't find anything, or I don't know how to search it.
I know I've seen a duplicate for this, but I can't find it at the moment, so here goes.
var data = { ranges: [ "A", "B", "C" ] };
//log the data element to the console
console.log( data );
//set the anotherVariable to point to the ranges array
//this does NOT create a separate element
//both variables point to the same array in memory
var anotherVariable = data.ranges;
//this changes both variables, because as said before, they point to the
//same array
anotherVariable[1] = "weee";
/*
If you look at your actual browser, you will see that the consoled
data has ranges of "A", "weee", "C". This is because your browser
is showing you the value of the element, up to date. Not only of
when you logged it.
*/
The problem was the disabled_hours var in timepicker library option declared later in the code.
It changes the value of disabled_hours, and I can't looking in the console until after it is changed.
$.ajax({
url: 'ajax/get_available_schedule.php',
type: 'GET',
dataType: 'json',
data: {field: field, day: day, hour: inicio},
})
.done(function(dataSCHEDULE) {
console.log(dataSCHEDULE);
// debugger;
if (dataSCHEDULE.success) {
disabled_hours = dataSCHEDULE.ranges;
console.log(disabled_hours);
close_hour = dataSCHEDULE.close;
}
else {
console.warn('API ERROR -> Getting available hours');
}
})
.fail(function(error) {
console.error('API ERROR -> Getting available hours');
console.log(error);
});
Related
I'd like to know a way of how to update the list values of a ExtJs ComboBox. For instance, I have two comboboxs.
One Combobox determine what values the another ComboBox should have. So, after selecting some of those,
I click the drowndown list (combobox) to see the values. But i dont get reflected.
change: function (combofirst, record) {
Ext.Ajax.request({
-- -- --
-- -- --
success: function (response) {
var combosecond = Ext.getCmp('defaultPackageType');
//I am unable to update the combosecond from below snippet.
combosecond.store = Ext.create('Ext.data.Store', {
fields: ['value', 'display'],
data: [
["N", "No"],
["A", "All accounts"]
] //json response
});
},
failure: function (record, action) {}
});
});
In short, how can I change the values of a ComboBox already has with ajax only.
Hope someone can help me
Thanks
I would also agree to the comment, that creating every time a new store and bind it to the combobox is not the optimal solution. I don't know really the reason why this should be done, but nevertheless here is a working example by using bindStore:
https://fiddle.sencha.com/#view/editor&fiddle/3ci0
Ext.create('Ext.form.field.ComboBox', {
// ...
listeners: {
change: {
fn: function (cb) {
Ext.Ajax.request({
url: 'https://jsonplaceholder.typicode.com/albums',
method: 'GET',
timeout: 60000,
success: function (response) {
var jsonResp = response.responseText;
let jsonObj = Ext.JSON.decode(jsonResp, true)
var combo2 = Ext.getCmp('myCombo2');
combo2.bindStore(Ext.create('Ext.data.Store', {
fields: ['id', 'title'],
data: jsonObj
}));
}
});
}
}
}
});
For selection of value 1 the data is loaded from a different url.
But I would think about whether a new proxy call is necessary and whether you can achieve your requirements by using filters or something else.
I am making an AJAX call to this controller method:
def search_posts
keyword = params[:keyword]
results = #client.query("SELECT *
FROM posts
WHERE keyword = '#{keyword}'")
posts = []
results.each do |row|
posts << {
media_id: row["media_id"],
media_type: row["media_type"],
caption: row["caption"]
}
end
#client.close
render json: posts
end
and my JavaScript looks like this:
$.ajax({
url: '/search_posts',
type: "get",
data: {
keyword: keyword
},
success: function(res) {
console.log(res);
}
});
However, when I console.log the returned JSON, some of the media_ids are one less than the real value. For example, a media_id that should be 17924518156307537 is logged in the browser as 17924518156307536.
I have puts'd the posts hash just before the render json: line and the media_ids are correct at that point. What's very strange is that it only happens to some media_ids, not all.
Finally figured it out: JavaScript only supports up to 53-bit integers and some of the media_ids were larger than that. Solved this by converting the media_ids to strings in Ruby before sending them to the client.
There is a static array which should be dynamically updated based upon click event.
I am able to get the dynamic value in an array format using Ajax but finding difficulties in setting it to the existing variable.
Ajax returns the below array
echo json_encode($arry);
// ["2","1","1","0","1","0"]
$.post( "ajaxcall.php", { ids: id })
.done(function( returnedArray){
//returnedArray looks like ["2","1","1","0","1","0"]
datasets: [{
//data: [10,12,33,50,12,34]
data: returnedArray
}]
},
But after the click event, returnedArray does not get interpreted to place the value.
Bacialy the result should look like below:
data: ["2","1","1","0","1","0"]
Use the assignment operator instead of :
datasets = [{
//data: [10,12,33,50,12,34]
data: returnedArray
}]
I am using the easyautocomplete, http://easyautocomplete.com/, to populate a list as the user types in a search field. The code is as follows:
var options = {
url: function(phrase) {
if (phrase !== "") {
return "http://<url>/todo?query=" + phrase + "&format=json";
} else {
return "http://<url>/todo?query=empty&format=json";
}
},
getValue: "results",
ajaxSettings: {
dataType: "jsonp"
},
requestDelay: 300,
theme: "round"
};
$("#product-list").easyAutocomplete(options);
I am getting a response from my API that looks like:
{
"results": [
"list_item_1",
"list_item_2",
"list_item_3",
...
"list_item_50"
]
}
I have a feeling I'm not formatting the response properly, but I'm not sure how to fix it.
A look through the guide it looks like getValue would be if you had an array of objects and wanted to pull a particular key from each one. From the list location section it looks like you are looking for listLocation to specify the object key that has the array of things to autocomplete. So changing getValue to listLocation should give you the results you are looking for
Ok, I feel like I'm going crazy here. I'm using the select2 jquery plugin (version 4), and retrieving data via ajax. So you can type in a name, and it will return that contact information. But I also want to return what organization that contact is a part of.
Here is my select2 initialization:
$('#contact_id').select2({
ajax: {
url: 'example.com/contacts/select',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 3,
maximumSelectionLength: 1
});
And here is the data I'm returning (laravel framework):
foreach($contacts as $con) {
$results[] = [
'id' => $con->contact_id,
'text' => $con->full_name,
'org' => [
'org_id' => $con->organization_id,
'org_name' => $con->org_name
]
];
}
return response()->json($results);
So isn't 'org' supposed to be attached to either the created option or select element by select2? So I could do something like $('#contact_id').select2().find(':selected').data('data').org or $('#contact_id').select2().data('data').org or something like that?
Idealistically, this would look like:
<select>
<option value="43" data-org="{org_id:377, org_name:'Galactic Empire'}">Darth Vader</option>
</select>
I swear I confirmed this worked last week, but now it's completely ignoring that org property. I have confirmed that the json data being returned does include org with the proper org_id and org_name. I haven't been able to dig anything up online, only this snippet of documentation:
The id and text properties are required on each object, and these are the properties that Select2 uses for the internal data objects. Any additional paramters passed in with data objects will be included on the data objects that Select2 exposes.
So can anyone help me with this? I've already wasted a couple hours on this.
EDIT: Since I haven't gotten any responses, my current plan is to use the processResults callback to spawn hidden input fields or JSON blocks that I will reference later in my code. I feel like this is a hacky solution given the situation, but if there's no other way, that's what I'll do. I'd rather that than do another ajax call to get the organization. When I get around to implementing it, I'll post my solution.
Can't comment for now (low reputation).. so... answering to slick:
Including additional data (v4.0):
processResults: function (data) {
data = data.map(function (item) {
return {
id: item.id_field,
text: item.text_field,
otherfield: item.otherfield
};
});
return { results: data };
}
Reading the data:
var data=$('#contact_id').select2('data')[0];
console.log(data.otherfield);
Can't remember what I was doing wrong, but with processResults(data), data contains the full response. In my implementation below, I access this info when an item is selected:
$('#select2-box').select2({
placeholder: 'Search Existing Contacts',
ajax: {
url: '/contacts/typeahead',
dataType: 'json',
delay: 250,
data: function(params){
return {
q: params.term,
type: '',
suggestions: 1
};
},
processResults: function(data, params){
//Send the data back
return {
results: data
};
}
},
minimumInputLength: 2
}).on('select2:select', function(event) {
// This is how I got ahold of the data
var contact = event.params.data;
// contact.suggestions ...
// contact.organization_id ...
});
// Data I was returning
[
{
"id":36167, // ID USED IN SELECT2
"avatar":null,
"organization_id":28037,
"text":"John Cena - WWE", // TEXT SHOWN IN SELECT2
"suggestions":[
{
"id":28037,
"text":"WWE",
"avatar":null
},
{
"id":21509,
"text":"Kurt Angle",
"avatar":null
},
{
"id":126,
"text":"Mark Calaway",
"avatar":null
},
{
"id":129,
"text":"Ricky Steamboat",
"avatar":null
},
{
"id":131,
"text":"Brock Lesnar",
"avatar":null
}
]
}
]