Ember beginner: Router and Outlets with ajax - javascript

I'm just new to Ember and sure this is an easy question but cannot figure out the best way to achieve what I want.
The scenario is the following:
App.Router = Ember.Router.extend({
root: Ember.Route.extend({
home: Ember.Route.extend({
route: '/',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('home');
router.get('homeController').connectOutlet('menu', 'menu', App.Channels.find());
router.get('homeController').connectOutlet('video_overview', 'videoOverview', App.Featured.find());
}
})
})
App.Featured = Ember.Object.extend();
App.Featured.reopenClass({
find: function() {
setRequestUrl('featured');
establishSecureConnection();
$.ajaxQueue({
type: "GET",
url: connect.url,
data: "",
dataType: 'jsonp',
jsonp: false,
jsonpCallback: "fjsonp",
cache: true,
context: this,
success: function(response){
this.findOne(response[0].mediaId); // get the first featured object and retrieve details
//
console.log('Featured Video:');
console.log(response);
}
});
},
findOne: function(item) {
var featuredVideo = App.Featured.create({});
setRequestUrl('media/'+item);
establishSecureConnection();
$.ajaxQueue({
type: "GET",
url: connect.url,
data: "",
dataType: 'jsonp',
jsonp: false,
jsonpCallback: "fjsonp",
cache: true,
context: featuredVideo,
success: function(response){
this.setProperties(response);
//
console.log('Featured Video details:');
console.log(response);
}
});
return featuredVideo;
}
So when executing the app and Router connects the outlet video_overview with content retrieved from App.Featured.find() I can see the response on the browser logs but values never arrives to the template.
I guess is related with the 'double' request I'm doing on App.Featured (first find() and then findOne()) so when I'm returning values with return featuredVideo is not being notified.
Thanks a lot for your time.

The App.Featured.find does seem to return anything. I think you have to return the result of the findOne, don't you ?

Hy everyone again,
Finally I was messing around and take sly7_7 advices and got working!
This is the way I achieved but if anyone could explain in detail the behaviour of Ember will be appreciated.
App.Featured = Ember.Object.extend();
App.Featured.reopenClass({
find: function(singleItem) {
if (singleItem){
console.log('Returning the single item...');
console.log(singleItem);
//
featuredContent.setProperties(singleItem);
} else {
setRequestUrl('featured');
establishSecureConnection();
$.ajaxQueue({
type: "GET",
url: connect.url,
data: "",
dataType: 'jsonp',
jsonp: false,
jsonpCallback: "fjsonp",
cache: true,
context: featuredContent,
success: function(response){
this.setProperties(App.Featured.findOne(response[0].mediaId)); // this.setProperties({'category':'hey arrives here success'});
//
console.log('Featured Video:');
console.log(response);
}
});
}
return featuredContent;
},
findOne: function(item) {
setRequestUrl('media/'+item);
establishSecureConnection();
$.ajaxQueue({
type: "GET",
url: connect.url,
data: "",
dataType: 'jsonp',
jsonp: false,
jsonpCallback: "fjsonp",
cache: true,
context: this,
success: function(response){
console.log('Featured Video content:');
console.log(response);
//
this.find(response);
}
});
}
});
var featuredContent = App.Featured.create({});
Then the template recieves the changes made on featuredContent object.

Related

undefined variable under jquery payload

I'm trying to post some data to an API but I'm struggling with javascript.
function pushData() {
let rawdata;
$.ajaxSetup({
async: false
});
$.getJSON('https://api.db-ip.com/v2/free/self', function(result) {
result = rawdata;
})
console.log(rawdata);
let message = {
"ip": rawdata.ipAddress,
"country": rawdata.countryName,
"city": rawdata.city
};
console.log(message);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/get",
headers: {},
/* crossDomain: true,
*/
type: "GET",
success: function(result) {
console.log(result);
},
error: function() {
console.log("error");
}
})
}
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/post",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(message),
success: function(result) {
console.log(result);
},
error: function() {
console.log("error pushing data");
}
})
I'm getting Uncaught ReferenceError: message is not defined although I think that message is a global variable, so it should be called successfully on the payload? What I'm I doing wrong here?
Thanks to anyone for his reply in advance, I'm just trying to write a quick script for my API here.
message is a local variable in the pushData() function, not a global variable. But even if it were global, you'd have to call the function before the second $.ajax() call.
Move the second AJAX call inside the function so you can access the variable. And embrace asynchrony, don't fight it with async: false. Nest the successive AJAX calls inside the callback function of the previous one.
function pushData() {
$.getJSON('https://api.db-ip.com/v2/free/self', function(rawData) {
console.log(rawdata);
let message = {
"ip": rawdata.ipAddress,
"country": rawdata.countryName,
"city": rawdata.city
};
console.log(message);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/get",
headers: {},
/* crossDomain: true,
*/
type: "GET",
success: function(result) {
console.log(result);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/post",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(message),
success: function(result) {
console.log(result);
},
error: function() {
console.log("error pushing data");
}
})
});
},
error: function() {
console.log("error");
}
})
}

i am trying to pass parameter to data through ajax

I am trying to pass value through an ajax json array but value of catergory variable is not getting in controller action
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: "POST",
data: {
'category': category
},
dataType: "json",
cache: false,
contentType: false,
processData: false,
success: function(response) {}
});
You need to use the parameter namespace matching your extension/plugin:
$.ajax({
// ...
data: {
'tx_myext_foo[category]': category,
},
// ...
});
But you'll also need to configure the cHash evaluation since this will lead to a HTTP request like /?tx_myext_foo[category]=X which will fail without a matching cHash.
This can be done with the excludedParameters configuration option.
Please check the Controller action if category (parameter name) passed from the ajax is exactly same in the controller action too
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
cache: false,
async: false,
url: url,
data: JSON.stringify {
category: category
},
dataType: 'json',
success: function(response) {}
});
You need to make ajaxurl with action and controller. and then pass the data in full format.
var ajaxUrl = '<f:uri.action action="youraction" controller="Yourcontroller" />';
var category = $('#category').val();
$.ajax({
type: 'POST',
url: ajaxUrl,
data: '&tx_yourext_yourplugin[category]='+category,
success: function(response) {
},
});
Just make the following changes :
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: "POST",
url:url,
data: {'category': category},
dataType: "json",
success: function(response) {}
});

jquery not posting contents of json map

given this very simple ajax post using jquery
function addEntity(parent, entity, successCallback, errorCallback ) {
console.log("add entity:", JSON.stringify(entity));
$.ajax( '/service/v3/rest/' + parent.id, {
type: 'POST',
dataType: 'application/json;',
contentType:"application/json; charset=utf-8",
data: JSON.stringify(entity),
success: successCallback,
error:errorCallback
});
}
note the console log that is identical to that used in the data field:
console.log("add entity:", JSON.stringify(entity));
outputs exactly what i'd expect the post body to contain:
add entity: `{"name":"some name","execute":false,"listeners":{"foo":"bar"}}`
That's exactly correct for what i'm trying to do.
What is actually posted (seen through Charles Proxy) :
{
"name": "some name",
"listeners": {}
}
Why would jquery remove the contents of my map?
this magically made my post contain the map :/
function addEntity(parent, entity, successCallback, errorCallback ) {
console.log("add entity:", JSON.stringify(entity));
$.ajax( '/service/v3/rest/' + parent.id, {
type: 'POST',
dataType: 'json',
contentType:"application/json; charset=utf-8",
processData: false,
data: JSON.stringify(entity),
success: successCallback,
error:errorCallback
});
}

Cant get value from ajax request to be save in variable outside the success

Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.
When I return the value it always comes up undefined when I alert() inside it shows the proper values.
function getItemInfo(itemHashPass) {
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
return data.Response.data.inventoryItem.itemName;
}
});
}
I've also tried
function getItemInfo(itemHashPass) {
var tmp = null;
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
tmp = data.Response.data.inventoryItem.itemName;
}
});
return tmp;
}
Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like
function yourBusinnesLogicFunction() {
...
getItemInfo("password_hash_value").done(
function(data){
alert(data.Response.data.inventoryItem.itemName);
}
)
}
function getItemInfo(itemHashPass) {
var tmp = null;
return $.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
})
}

Send data from a javascript ajax function to a jsp

This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});

Categories

Resources