This question already has answers here:
Pass array to mvc Action via AJAX
(12 answers)
Closed 6 years ago.
let's assume I have controller method like this
public ActionResult GetSelected(int[] ids)
{
//do something
return Json (ids, JsonRequestBehavior.AllowGet)
}
and in view file I have function which creates array named list.
How can I pass my array to controller using $.get function?
I would do this :
var data = { 1, 2 };
$.ajax({
url: '#Url.Action('GetSelected','ControllerName')',
data: {
getSelected : data
},
success:function(data){
//Do Something With the return data or HttpStatusCode
}
});
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Asynchronous Process inside a javascript for loop [duplicate]
(6 answers)
Closed 5 years ago.
I'm trying to create a JavaScript object (friends_ringsigs), in which the keys are the values of names[i], and the values are the "result" variable created at the execution of the promise. The problem is, when I try to access the "names[i]" variable for use, it doesn't exist.
// get list of new contact requests
$.ajax({
url: '/api/messaging/getnewfriends.php?auth=<?=$_SESSION['auth_random']?>',
type: 'POST',
data: '',
success: function(result) {
if(result != 'none'){
var names = result.split("[Delimiator0]");
for(var i = 0; i < names.length-1; i++){
ringsig_decrypt(priv_ck, names[i]).then(function(result){
friends_ringsigs[result] = names[i];
alert(friends_ringsigs[result]);
alert(names[i]);
alert(result);
document.getElementById('newcontactslist').innerHTML += contactify(result);
$('#contactslabel').show();
});
}
}else{
document.getElementById('newcontactslist').innerHTML = "";
$('#contactslabel').hide();
}
}
});
I'm able to access the "result", but not the names[i], and later when I go to get the value out of friends_ringsigs, it doesn't exist. In fact, alert(JSON.stringify(friends_ringsigs)); outputs "{}".
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I have object with data array and mark_read method, which sends PUT request to my Rails app. It looks like this in data option is not the object instance, how can I fix it?
Notifications.prototype = {
constructor: Notifications,
...
mark_read: function() {
$.ajax({
method: "PUT",
url: '/notifications/mark_read',
data: this.data.slice(0,5)
});
}
...
}
You should store "this" in a closure before trying to access it from inside of $.ajax function.
It should be something like this
Notifications.prototype = {
constructor: Notifications,
...
mark_read: function() {
var me = this;
$.ajax({
method: "PUT",
url: '/notifications/mark_read',
data: me.data.slice(0,5)
});
}
...
}
The scope for this is the mark_read function, so the context for this is whatever Notification object mark_read() is called upon.
This question already has answers here:
Angular - extending $resource subobject with custom methods
(4 answers)
add a custom function on angular $resource [duplicate]
(3 answers)
Closed 7 years ago.
I'd like to get objects from a server, something like:
var User = $resource('/user/:userId', {userId:'#id'});
I'd like User instances to all have certain methods to calculate derived data, without the server having to return it. For example, say for:
var aUser = User.get({userId: 43});
The server returns something like:
{id: 43, name: "Bob", alertTimestamp: 1447365544}
I'd like to be able to do something like:
if (aUser.alertTimePassed()) {
// do stuff
}
Is there a clean way to do this short of something like this, which seems hacky?
var alertTimePassed = function () {
var now = (new Date()).getTime() / 1000;
return now >= this.alertTimestamp;
};
var User = $resource('/user/:userId', {userId: '#id'}, {
get: {
method: "GET", url: '/user/:userId',
transformResponse: [angular.fromJson, function (obj) {
obj.alertTimePassed = alertTimePassed;
}]
}
});
If you create your $resource using a factory you can modify the $resource object before returning it from the factory.
app.factory('User', function ($resource) {
var User = $resource('/user/:userId', {userId: '#id'});
// add any methods here using prototype
User.prototype.alertTimePassed = function() {
// do stuff
};
return User;
});
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 8 years ago.
How can I call the loadlist function correctly when I have this JSON data?
I am calling like this but it’s not working:
loadlist($('select#selName').get(0), 'pull.php','data.name')
Here is my JSON data:
{
data: [
{
id: "e0b0d8sc5ffd82e",
name: "John",
}
]
}
the function
function loadlist(selobj,url,nameattr) {
$(selobj).empty();
$.getJSON(url,{},function(data)
{
$(selobj).append(
$('<option>Select</option>')
.val('null')
);
$.each(data, function(i,obj)
{
$(selobj).append(
$('<option></option>')
.val(obj[nameattr])
.html(obj[nameattr]));
});
});
}
Your assumption that obj["data.name"] is equal to obj.data.name is wrong. (The equivalent requires two property accesses: obj["data"]["name"])
If you think you might need to do nested property retrievals, you might have better luck passing in a function for retrieving the property. (This also will work if you need to use a dynamically computed value.)
function loadlist(selobj,url,getter) {
$(selobj).empty();
$.getJSON(url,{},function(data)
{
$(selobj).append(
$('<option>Select</option>')
.val('null')
);
$.each(data, function(i,obj)
{
var value = getter(obj);
$(selobj).append(
$('<option></option>')
.val(value)
.html(value));
});
});
}
// Call as follows:
loadlist($('select#selName').get(0), 'pull.php', function (obj) {
return obj.data.name;
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 8 years ago.
initialize: function() {
var store = {};
var item = {};
var me = this;
Ext.Ajax.request({
url: "some_valid_url",
success: function(response) {
try {
var parser = new DOMParser();
var xml = parser.parseFromString(response.responseText, "text/xml");
store = Ext.create('Ext.data.Store', {
autoLoad: true,
fields: ['temp', 'low', 'high', 'desc', 'icon'],
data: xml,
proxy: {
type: 'memory',
reader: {
type: 'xml',
rootProperty: 'current',
record: 'day'
}
}
});
item = Ext.create("Ext.Container", {
var bla = "hello world",
})
} catch (err) {
//err
}
}
});
}
console.log("STORE AND ITEM");
console.log(item);
console.log(store);
Why item and store give back null objects?
However I can see that it's parsing some data, as if I put console.log in between store and item elements I will get a valid element.
STORE AND ITEM
Object {} ArticleWeatherList.js:105
Object {} ArticleWeatherList.js:106
Ajax is asynchronous which basically means that the code continues executing without waiting for the request to complete. Therefore, when you are trying to use item and store, the request has not yet completed and the success method which sets them has not yet run. The only ways round this are to force the request to happen synchronously (although this is generally a bad idea) or to put all the code that depends on the request into the success callback or functions that are called from within the success callback.
Because,
you have declared store and item as local variables inside intialize function. If you want access these variable outisde you must declare them in the global not in the function. The same can be achived omitting the var keywords in the declaration of the variables.
initialize: function () {
store = {};
item = {};
var me = this;
....
this should works but is a considered a bad practice.