How to send data to controller by using YAHOO connect and json - javascript

I can not send data to MVC controller using YAHOO connect library.
Parameters query and filter are NULL. Where is the problem?
// --- JavaScript --- //
var callbacks = {
// Successful XHR response handler
success: function (o) {
var messages = [];
// Use the JSON Utility to parse the data returned from the server
try {
messages = YAHOO.lang.JSON.parse(o.responseText);
}
catch (x) {
alert("JSON Parse failed!");
return;
}
handleSearchResult(messages, query, filter);
},
argument: { query: "flowers", filter: "home" }
};
// Make the call to the server for JSON data
YAHOO.util.Connect.asyncRequest("GET", "Search/GetTopics", callbacks);
// --- C# --- //
//Controller
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTopics(string query, string filter)
{
// query and filter are NULL <- problem here //
// ...do my stuff... //
return Json(Search(query, filter), JsonRequestBehavior.AllowGet);
}
Thank you! :)

You have to possibilities to send parameters:
Use GET verb: In this case you need to pass the parameters in the querystring:
YAHOO.util.Connect.asyncRequest('GET',
'Search/GetTopics?query=foo&filter=bar', callbacks);
Use POST verb: In this case you could use the postData parameter
YAHOO.util.Connect.asyncRequest('POST', 'Search/GetTopics',
callbacks, 'query=foo&filter=bar');
In the first case it is actually recommended to use Url helpers to generate the address to make sure values are properly url encoded:
var url = '<%= Url.Action("GetTopics", "Search", new { query = "foo", filter = "bar" }) %>';
YAHOO.util.Connect.asyncRequest('GET', url, callbacks);
The same is true for the second case. Make sure to properly encode values.

Related

jquery is this a valid http request

I have this http request
GET /deals/couchbaseDocument/_search
{
"query" : {
"match" : {
"amenities" : "Maids "
}
}
}
when i put it in curl, it gives me results, i want to build a web app to call that request.
what i did is removing the newlines and put the whole text in .getjson()
as this:
var query = $("#query").val();
query = query.replace(/(\r\n|\n|\r)/gm,"");
$.getJSON(query, function (results) {
alert("success");
alert(results);
})
.success(function () { alert(" second success"); })
.error(function () {
alert("error");
alert(query);
});
i kept getting the error alert, i wonder if what i did is actually what should it be done to send that request
I read this
I found that .getJson could be like this:
$.getJSON('httpURL',
{ parameter1: "parameter value", parameter2: "parameter value" })
i wonder if i should pass my json request as a parameter
in case of the whole picture** i am working on sense elasticsearch plugin
According to the documentation of jQuery's getJson, you can pass a javascript object (jQuery.getJSON() | jQuery API Documentation) so you can do something like this
var queryData = {
"query" : {
"match" : {
"amenities" : "Maids "
}
}
};
$.getJSON('httpURL', queryData)

AngularJS code is giving back error?

$scope.logout = function () {
//var auth_token = $cookieStore.get('auth_token');
Auth.delete({
'auth_token': $cookieStore.get('auth_token')
}, function(data){
$scope.isLoggedIn = false;
$cookieStore.remove('auth_token');
});
When this called it given me an error:
Error: [$resource:badcfg] http://errors.angularjs.org/1.2.27/$resource/badcfg?p0=object&p1=array
z/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:6:450
t/</f[d]/q<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular-resource.min.js:8:1
De/e/l.promise.then/J#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:101:87
De/e/l.promise.then/J#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:101:87
De/f/<.then/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:102:259
Yd/this.$get</h.prototype.$eval#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:113:28
Yd/this.$get</h.prototype.$digest#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:110:109
Yd/this.$get</h.prototype.$apply#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:113:360
m#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:72:452
w#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:77:463
ye/</B.onreadystatechange#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:79:24
http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js
Line 92
Its a common problem. The delete method of resource model is expecting a json response which must be an object but your server is returning the json data in array format. So you have two options either change your server code to respond the json object data or change your resource model something like:
var Auth = $resource('/your-server-url', {}, {
delete: {
isArray: false
}
});
Hope this helps!
Thanks,
SA

How to get Model attributes from nested json object in Backbone

** JSON Data **
{
"data" : [{
"book" : "first book", -- > i want this via model.get('book');
"aurthor" : "xyz"
}
]
}
** Get json data using jquery Ajax. **
var jsonData = {};
$.ajax({
url : 'booklist.json',
async : false,
dataType : 'json',
success : function (json) {
jsonData = json.data;
}
});
** Model declaration here **
var MyModels = Backbone.Model.extend({
initialize : function () {},
defaults : {}
});
var modelinstance = new MyModels(jsonData);
modelinstance.get('book'); // it is giving undefined how can i get this value.
** Please help where i doing wrong.i am new in Backbone. **
If the data is always a single object wrapped up like that then you'd just add a parse method to your mode:
parse model.parse(response, options)
parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model.
Something like this:
parse: function(response) {
return response.data[0];
}
You can also trigger a parse call through the model constructor using the parse: true option:
constructor / initialize new Model([attributes], [options])
[...]
If {parse: true} is passed as an option, the attributes will first be converted by parse before being set on the model.
So if you're manually loading the data through a $.ajax call then you'd have something like this:
success: function (json) {
var m = new MyModel(json, { parse: true });
// Do something with m...
}

Is there a way to send an object as well as a separate variable in an ajax POST request

I have a post request I am doing like so:
var addProject = function (project, id) {
return $.ajax(projectUrl, {
type: "POST",
data: { project: project, id: id }
});
};
This is all fine, and it send up my project object (in JSON) with no problem. What i want to do is this request but also add in a key (that does not belong in the project object) that I can pass to the server controller. Any idea if I can do this, or what is a good way to do this. I really don't want to have to go back and change my object models to account for a key that I will only need every once in awhile.
This is an ASP.NET MVC4 project, and it is going back to a web api controller if that matters.
EDIT: here is my server side stuff
public HttpResponseMessage PostNew(Project project, int id)
{
//TODO grab the client to add the project to
Uow.Projects.Add(project);
Uow.Commit();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, project);
//response.Headers.Location = new Uri(Url.Link("ApiControllerAction", new { id = client.ID }));
return response;
}
Maybe I am not being clear enough. I want to pass in the project object, and then just an int variable. Passing project alone works, but if I try to pass the int it gives me a 400 error
var addProject = function (project) {
return
$.ajax(projectUrl, {
type: "POST",
data: {data1 : 'Object',data2: 'variable'}
});
};
You have just to send 2 data params., object and var..
Easiest way to pass a complex object is to JSON-encode it:
var addProject = function (project) {
return $.ajax(projectUrl, {
type: "POST",
contentType: 'application/json',
data: JSON.stringify(project)
});
};
To decode this on the server side, you will need a JSON decoder of some kind. I'm sure C# has some available.

Node.js - Can't post nested/escaped JSON to body using Fermata REST client

The problem may be with the actual client, but he's not responding on github, so I'll give this a shot!
I'm trying to post, in the body, nested JSON:
{
"rowkeys":[
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"{\"date\":\"2011-06-21T00:53:10.309Z\",\"disk0\":{\"kbt\":31.55,\"tps\":6,\"mbs\":0.17},\"cpu\":{\"us\":5,\"sy\":4,\"id\":90},\"load_average\":{\"m1\":0.85,\"m5\":0.86,\"m15\":0.78}}",
"ttl":10000
},
{
"columnname":"cn",
"columnvalue":"cv",
"ttl":10000
}
]
},
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"fd"
},
{
"columnname":"cn",
"columnvalue":"cv"
}
]
}
]
}
When I remove the columnvalue's json string, the POST works. Maybe there's something I'm missing regarding escaping? I've tried a few built in escape utilities to no avail.
var jsonString='the json string above here';
var sys = require('sys'),
rest = require('fermata'), // https://github.com/andyet/fermata
stack = require('long-stack-traces');
var token = ''; // Username
var accountId = ''; // Password
var api = rest.api({
url : 'http://url/v0.1/',
user : token,
password : accountId
});
var postParams = {
body: jsonString
};
(api(postParams)).post(function (error, result) {
if (error)
sys.puts(error);
sys.puts(result);
});
The API I'm posting to can't deserialize this.
{
"rowkeys":[
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":{
"date":"2011-06-21T00:53:10.309Z",
"disk0":{
"kbt":31.55,
"tps":6,
"mbs":0.17
},
"cpu":{
"us":5,
"sy":4,
"id":90
},
"load_average":{
"m1":0.85,
"m5":0.86,
"m15":0.78
}
},
"ttl":10000
},
{
"columnname":"cn",
"columnvalue":"cv",
"ttl":10000
}
]
},
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"fd"
},
{
"columnname":"cn",
"columnvalue":"cv"
}
]
}
]
}
Dual problems occuring at the same occurred led me to find an issue with the fermata library handling large JSON posts. The JSON above is just fine!
I think the real problem here is that you are trying to post data via a URL parameter instead of via the request body.
You are using Fermata like this:
path = fermata.api({url:"http://example.com/path");
data = {key1:"value1", key2:"value2"};
path(data).post(callback);
What path(data) represents is still a URL, with data showing up in the query part. So your code is posting to "http://example.com/path/endpoint?key1=value1&key2=value2" with an empty body.
Since your data is large, I'm not surprised if your web server would look at such a long URL and send back a 400 instead. Assuming your API can also handle JSON data in the POST body, a better way to send a large amount of data would be to use Fermata like this instead:
path = fermata.api({url:"http://example.com/path");
data = {key1:"value1", key2:"value2"};
path.post(data, callback);
This will post your data as a JSON string to "http://example.com/path" and you would be a lot less likely to run into data size problems.
Hope this helps! The "magic" of Fermata is that unless you pass a callback function, you are getting local URL representations, instead of calling HTTP functions on them.

Categories