handling ajax data with jQuery - jquery-ui

$.ajax({
url: "/rooms.json",
dataType: "json",
data: {
q: req.term
},
success: function (data) {
alert('test');
responseFn($.map(data.room, function (item) {
alert('test1')
return {
label: item.title
value: item.title
}
}));
}
});
data from /rooms.json?q=a looks like below:
[{
"room": {
"created_at": "2011-05-19T18:08:04Z",
"title": "Great Office Space for Rent!",
"cost": 450,
"updated_at": "2011-05-19T18:08:04Z",
"property_id": 4,
"maximum_capacity": 234,
"id": 15,
"fulladdress": "550 12th St NW, Washington D.C., DC 20005, USA",
"user_id": null,
"phone": "301-395-7578",
"description": "Great office space to rent in DC\r\n\r\nPlease contact. ",
"email": "something#gmail.com"
}
}]
In the above code, I see the first alert but not the second alert so something is going wrong in the handling of the data from the json request.
What should I do to fix this?
Update
After playing around w/ some code I figured it out.
I had to tweak the rails controller to render json as below
format.json {render :json => #events.map(&:attributes)}
Furthermore, for jQuery code I had to remove .room from the code below
responseFn($.map(data.room, function (item) {

silly me
in rails code:
format.json {render :json => #days.map(&:attributes)}
in jQuery code
responseFn( $.map( data, function( item ) {

Related

Passing Json response to view in Rails Ajax Datatable

I have an index method that respond with Json call to Datatable such as:
respond_to do |format|
format.html
format.json { render json: PeopleDatatable.new(params, user: current_user, view_context: view_context) }
end
I would like to be able to pass an array of all the IDs in the response to a dom in my view such as <div id: "people">1,2,3,4</div>
As per the gem description, the People records are generated in the
app/datatables/people_datatable.rb
using:
def get_raw_records
User.all
end
I tried adding the following in the view's script:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "<%= peoples_path(format: :json) %>",
dataType: "json",
success: function(data) {
alert(data.name)
$('#bouba').html(data);
}
});
});
but the result is an undefined object class.
What would be the easiest way to do so please?
I am using the following gem for my datatable Rails ajax Datatable
Open /people.json and see what you get as a response, it looks something like this:
{
"recordsTotal": 2,
"recordsFiltered": 2,
"data": [
{
"id": "1",
"name": ""
},
{
"id": "2",
"name": ""
},
]
}
Now that you know what the structure looks like, send ajax request to that url:
<div id="people-ids"></div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
// send request to the correct url: "/people.json"
url: "<%= people_path(format: :json) %>",
dataType: "json",
success: function({data}) {
// ^
// extract "data" attribute from the response
console.log(data) // you can see what you get in the console
// extract ids
const user_ids = data.map(user => user.id)
// do what you like with the ids
$("#people-ids").html(user_ids.join());
}
});
});
</script>

Extjs 6.7 TreeList load data infinite from remote store

I try to fill a treelist with remote data via a ajax proxy but the treelist shows only the first level and try to reload the sub levels even though the json response contain a complete tree structure. Fiddle link: https://fiddle.sencha.com/#view/editor&fiddle/33u9
When i try to expand the node 'SUB a' (or set the expanded property to true) the store trys to reload the node.
Why is the tree structure from the json response not honored?
Thanks in Advance.
The backend response looks like:
{
"data": {
"root": [
{
"leaf": true,
"text": "Server"
},
{
"leaf": true,
"text": "Storage"
},
{
"text": "SUB a"
"children": [
{
"leaf": true,
"text": "Modul A - 1"
},
{
"leaf": true,
"text": "Modul A - 2"
}
],
},
{
"leaf": true,
"text": "Modul B"
}
]
},
"success": true
}
The used reader config is
reader: {
type: 'json',
rootProperty: 'data.root',
successProperty: 'data.success',
},
After playing around i use the following workaround:
getNavigation: function() {
var me = this,
tree = me.getView().down('navigationtree'),
store = tree.getStore(),
node = store.getRoot();
Ext.Ajax.request({
url: '/getnav',
method: 'POST',
success: function(response) {
var obj = Ext.decode(response.responseText),
childs = obj.data.root;
tree.suspendEvents();
node.removeAll();
childs.forEach(function(item) {
node.appendChild(item);
});
tree.resumeEvents();
},
failure: function(response) {
//debugger;
console.log('server-side failure with status code ' + response.status);
}
}).then(function() {
//debugger;
}
);
}
The funny things is that only the first level of the tree has to be added all following sub-levels are added automaticaly.

QPX Express API obj not parsing properly when passed to Rails

I've been trying for quite some time now to figure out why the JSON object I'm passing through AJAX to Rails with Typhoeus isn't working properly. Apologies if this is a newb question but I'm relatively new to web dev.
I've spent all day looking at docs, googling, and on SO but I haven't been able to figure out much for some reason.
I'm trying to pass a request to Google's QPX Express API for flight search and the docs say to send a JSON obj in the following format:
{
"request": {
"passengers": {
"kind": "qpxexpress#passengerCounts",
"adultCount": 1,
"childCount": 0,
"infantInLapCount": 0,
"infantInSeatCount": 0,
"seniorCount": 0
},
"slice": [
{
"kind": "qpxexpress#sliceInput",
"origin": "SFO",
"destination": "HNL",
"date": "2015-04-03",
"maxStops": 0,
"maxConnectionDuration": 0,
"preferredCabin": "COACH",
"permittedDepartureTime": {
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "00:00",
"latestTime": "11:59"
},
"permittedCarrier": [
"VX",
"UA"
],
"alliance": "",
"prohibitedCarrier": [
""
]
}
],
"maxPrice": "USD1000.00",
"saleCountry": "US",
"refundable": false,
"solutions": 1
}
}
I have this stored a variable which is referenced in the AJAX request below as 'reqBody':
$.ajax({
url: '/search',
dataType: 'json',
contentType: 'application/json',
method: 'POST',
// contentType: "application/json; charset=utf-8",
data: JSON.stringify(reqBody),
success: function(data) {
console.log(data);
}
});
And this is call goes to the rails controller shown here, using Typhoeus to process the request/response:
reqBody = params[:request]
flightRequest = Typhoeus::Request.new(
"https://www.googleapis.com/qpxExpress/v1/trips/search?key=APIKEY",
method: :post,
headers: {'Content-Type'=> "application/json; charset=utf-8"},
body: reqBody,
)
flightRequest.run
#results = JSON.parse(flightRequest.response.body)
respond_to do |format|
format.html
format.json { render json: {
:results => #results
}
}
end
This ends up being the response I get back:
{"results":{"error":{"errors":[{"domain":"global","reason":"parseError","message":"Parse Error"}],"code":400,"message":"Parse Error"}}}
And this is what I get when I look at the obj in pry:
=> {"passengers"=>
{"kind"=>"qpxexpress#passengerCounts",
"adultCount"=>1,
"childCount"=>0,
"infantInLapCount"=>0,
"infantInSeatCount"=>0,
"seniorCount"=>0},
"slice"=>
[{"kind"=>"qpxexpress#sliceInput",
"origin"=>"SFO",
"destination"=>"HNL",
"date"=>"2015-04-03",
"maxStops"=>0,
"maxConnectionDuration"=>0,
"preferredCabin"=>"COACH",
"permittedDepartureTime"=>
{"kind"=>"qpxexpress#timeOfDayRange", "earliestTime"=>"00:00", "latestTime"=>"11:59"},
"permittedCarrier"=>["VX", "UA"],
"alliance"=>"",
"prohibitedCarrier"=>[""]}],
"maxPrice"=>"USD1000.00",
"saleCountry"=>"US",
"refundable"=>false,
"solutions"=>1}
What's going on here? Shouldn't the object be a string since I stringified it in the AJAX request? Is this why there's a parsing error when I send the object to the QPX Express API?
Any help is highly appreciated!
Thanks!
Just a thought,
did you require 'json' in your controller?
The other thing you could try is the variant of parse
parse! which can be used for safe safe sources.
here is a link!
How do I parse JSON with Ruby on Rails?
good luck

how to get value from json file using jquery autocomplete

This is my jquery code
$('.typeahead', this).autocomplete({
source: function(request, response) {
$.ajax({
url: 'includes/stations.json',
dataType: 'json',
data: request,
success: function(data) {
response($.map(data, function(item, i) {
return {
label: item.name,
value: item.code
}
}));
},
});
},
minLength: 3
});
My Json File is
[
{
"code": "9BP3",
"name": "9Bp No3"
},
{
"code": "AA",
"name": "Ataria"
},{
"code": "BILA",
"name": "Bheslana"
},
{
"code": "BILD",
"name": "Bildi"
},{
"code": "HRI",
"name": "Hardoi"
},
{
"code": "HRM",
"name": "Hadmadiya"
}
]
When i typing any three letter its returns whole json file values
q: request.term this is the string for filter returned values from stations.json. You must pass variable like this to filter results. stations.json must be dynamically generated file like php with json header. q is $_GET parameter and must be parsed. Try to change the code like this:
$.ajax({
url: "includes/stations.json",
dataType: "json",
data: {
q: request.term // here is the string for filter returned values from stations.json. You must pass variable like this to filter results. stations.json must be dynamically generated file like php with json header. q is $_GET parameter and must be parsed.
},
success: function(data) {
response(
$.map(data, function(item, i) {
return {
label: item.name,
value: item.code
}
})
);
}
});
},
minLength: 3,

How do get an Ember.Select to be populated via Rails backend data?

I'm trying to write a select box in Ember, based on a Rails back end. When editing the model Recipes, I want to be able to select from a list of Sources in a dropdown. Right now in Ember I'm getting the message "The value that #each loops over must be an Array. You passed App.Sources" as a result of the following code.
I have tested the REST api and it is providing the response for Recipes and Sources both properly.
I'm new to Embers (and Javascript too, actually!) and I feel like I'm missing something basic. Thank you for any tips.
Here's my JS:
App.RecipeEditController = Ember.ObjectController.extend({
needs: ['sources'],
selectedSource: null,
actions: {
save: function() {
var recipe = this.get('model');
// this will tell Ember-Data to save/persist the new record
recipe.save();
// then transition to the current recipe
this.transitionToRoute('recipe', recipe);
}
}
});
App.RecipesRoute = Ember.Route.extend({
model: function() {
return this.store.find('recipe');
},
setupController: function(controller, model) {
this._super(controller, model);
this.controllerFor('sources').set('content', this.store.find('source'));
}
});
App.SourcesRoute = Ember.Route.extend({
model: function() {
return this.store.find('source');
}
});
DS.RESTAdapter.reopen({
namespace: "api/v1"
});
App.Recipe = DS.Model.extend({
title: DS.attr('string'),
url: DS.attr('string'),
rating: DS.attr('number'),
source: DS.belongsTo('source', {
async: true
}),
page_number: DS.attr('number'),
want_to_make: DS.attr('boolean'),
favorite: DS.attr('boolean')
});
App.Source = DS.Model.extend({
title: DS.attr('string'),
authorLast: DS.attr('string'),
recipes: DS.hasMany('recipe', {
async: true
})
});
App.Router.map(function() {
return this.resource("recipes");
});
App.Router.map(function() {
return this.resource("recipe", {
path: "recipes/:recipe_id"
});
});
App.Router.map(function() {
return this.resource("recipeEdit", {
path: "recipes/:recipe_id/edit"
});
});
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.RESTAdapter
});
And here's the view:
{{view Ember.Select
contentBinding="controllers.sources.content"
optionLabelPath="content.title"
optionValuePath="content.id"}}
UPDATE And here's the JSON:
{
"recipes": [
{
"id": 3,
"title": "Did this make it through?",
"url": "www.hellyeahitdid.com/high-five/",
"rating": null,
"source_id": null,
"page_number": null,
"want_to_make": false,
"favorite": false
},
{
"id": 1,
"title": "Here's another totally crazy one for ya",
"url": "http://www.example.com/recipe/1",
"rating": null,
"source_id": null,
"page_number": null,
"want_to_make": false,
"favorite": false
},
{
"id": 2,
"title": "A Sample Recipe",
"url": "http://www.example.com/recipe/1",
"rating": null,
"source_id": null,
"page_number": null,
"want_to_make": false,
"favorite": false
}
]
}
{
"sources": [
{
"id": 1,
"title": "Joy of Cooking",
"author_last": null
},
{
"id": 2,
"title": "Everyday Food",
"author_last": null
}
]
}
Welcome to javacript/ember, here's an example using a select.
http://emberjs.jsbin.com/OxIDiVU/69/edit
you'll notice the i don't quote real properties, and do quote strings
{{ view Ember.Select
content=someSource
optionValuePath='content.id'
optionLabelPath='content.title'
}}
Additionally that appears to be a very old version of Ember Data. You may consider updating. https://github.com/emberjs/data/blob/master/TRANSITION.md
Your routing can go in a single call
App.Router.map(function() {
this.resource("recipes");
this.resource("recipe", { path: "recipes/:recipe_id"}, function(){
this.route('edit');
});
});
This should get you started
http://emberjs.jsbin.com/OxIDiVU/74/edit

Resources