I have such autocomplete code:
$("input#PickupSpot").autocomplete({
source: function(request, response){
$.ajax({
url: "AjaxSearch.aspx",
dataType: "jsonp",
data: {
a: "getspots",
c: "updateSpotList",
q: request.term
},
success: function(){
alert("Success");
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
}
});
When i try to get data Firebug shows an error: "updateSpotList is not defined".
I need to creat a function called updateSpotList to get response from the server. And the success alert is never invoked.
Why do i need this function? Maybe there are something defined in aspx? It is:
string response = "";
string callback = Request.QueryString["c"];
string action = Request.QueryString["a"];
string query = Request.QueryString["q"];
//Ensure action parameter is set
if(action != null && action.Equals("getspots")){
//Ensure query parameter is set
if (query != null && query.Length > 0){
SpotListRequest request = new SpotListRequest
{
FreeText = query,
Language = "sv-SE"
};
IEnumerable<Spot> spots = DataBridge.GetSpotList(null, null, query).OrderBy(i => i.FullName);
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(spots.ToArray());
//Ensure callback parameter is set
if (callback != null && callback.Length > 0)
{
response = String.Format("{0}('{1}')", callback, json);
}
}
}
You can specify a URL as the source parameter, instead of the data parameter.
http://jqueryui.com/demos/autocomplete/#option-source
The plugin will make a request to your server, and you should return a JSON array looking like this:
[{label: "Name"}, {label: "Name 2"}]
Change your JavaScript code to this:
$("input#PickupSpot").autocomplete({
source: "AjaxSearch.aspx?a=getspots&c=updateSpotList"
});
The autocomplete plugin will append a parameter named term to the source URL, with the current value of the input element, so a request would be made to: "AjaxSearch.aspx?a=getspots&c=updateSpotList&term=test" if you wrote test in the input element.
On the server, you want to change q to term.
Related
We use a rest api to get customer information. A lot of the GET request were already written by others. I was able to follow their code to create other GET request, but one of the API methods for updating a customer requires using json patch. Below I have pasted in sample code of a current GET method, a Patch method (that I don't know how to implement) and a sample function written in javascript on how to use the json-patch that came from the api creators demo documentation:
public GetCustomerResponse GetCustomerInfo(CustomerRequest request)
{
//All of this works fine the base url and token info is handled elsewhere
var restRequest = CreateRestRequest($"customer/account?id={request.id}", RestSharp.Method.GET);
var response = CreateRestClient().Execute<GetCustomerResponse>(restRequest);
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Data;
}
else
{
return new GetCustomerResponse(response.Content);
}
}
public EditCustomerResponse EditCustomer(EditCustomerRequest request)
{
var restRequest = CreateRestRequest($"customer/account?id={request.id}", RestSharp.Method.PATCH);
var response = CreateRestClient().Execute<EditCustomerResponse>(restRequest);
//how do I pass along json patch data in here???
//sample json might be like:
//[{'op':'replace','path':'/FirstName','value':'John'},{'op':'replace','path':'/LastName','value':'Doe'}]
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Data;
}
else
{
return new EditCustomerResponse(response.Content);
}
}
//javascript demo version that is working
function patchCustomer(acctId, patch, callback) {
var token = GetToken();
$.ajax({
method: 'PATCH',
url: BaseURI + 'customer/account?id=' + acctId,
data: JSON.stringify(patch),
timeout: 50000,
contentType: 'application/json; charset=UTF-8',
beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer ' + token.access_token) },
}).done(function (data) {
if (typeof callback === 'function')
callback.call(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Request failed: " + textStatus);
console.error(errorThrown);
failureDisplay(jqXHR);
});
}
This was pretty simple. After viewing similar questions on stackoverflow, I initially was trying something like this:
var body = new
{
op = "replace",
path = "/FirstName",
value = "John"
};
restRequest.AddParameter("application/json-patch+json", body, ParameterType.RequestBody);
It would not work. To get it to work, I added a patchparameters class with op, path and value properties, and then added a list property of type patchparameters to my EditCustomerRequest class and used it like this:
restRequest.AddJsonBody(request.patchParams);
I am trying to return the results of monogdb query into a webapplication. The simplest initial one was just to return the full collection as you will see it in the mongodb console from a webservice call within the project that accesses the database:
> db.usercollection.find()
{ "_id" : ObjectId("52d2f2b3c60804b25bc5d2ca"), "username" : "testuser1", "email
" : "testuser1#testdomain.com" }
{ "_id" : ObjectId("52d2f2f9c60804b25bc5d2cb"), "username" : "testuser2", "email
" : "testuser2#testdomain.com" }
{ "_id" : ObjectId("52d2f2f9c60804b25bc5d2cc"), "username" : "testuser3", "email
" : "testuser3#testdomain.com" }
>
I would like to get the resulting json into an extjs grid. I am trying to ways to see if it works but the first question is actually how to return the result above:
<WebMethod()> _
<ScriptMethod(UseHttpGet:=True, ResponseFormat:=ResponseFormat.Json)> _
Public Function getDBData() As String
Dim response As String = String.Empty
mongo.Connect()
Dim db = mongo.GetDatabase("nodetest1")
Using mongo.RequestStart(db)
Dim collection = db.GetCollection(Of BsonDocument)("usercollection").FindAll()
response = collection.Collection.ToString
Return response
End Using
I am not seeing the result I want here:
var newStore = Ext.create('Ext.data.JsonStore', {
model: 'User',
proxy: {
type: 'ajax',
url: 'http://localhost:52856/WCFService/WebService1.asmx/getDBData',
reader: {
type: 'json',
root: 'd',
idProperty: '_id',
successProperty: 'success'
},
success: function (response, options) {
var s = response.responseText;
Ext.MessageBox.alert(s, 'LA LA LA');
newStore.loadData(s);
},
failure: function (response, options) {
Ext.MessageBox.alert('FAILED AGAIN', 'SUCKS');
}
}
});
I tried adding the root as follows:
response = "{""d"":" + response + "}"
Return response
The second alternative is to call the service from node.js directly but not show how to set up the result also:
Ext.Ajax.request({
url: 'http://localhost:3000/userlist',
method: 'GET',
success: function (response, options) {
var s = response.responseText;
Ext.MessageBox.alert(s, 'WOO WOO');
myStore.loadData(s);
},
failure: function (response, options) {
Ext.MessageBox.alert('FAILED MOFO', 'Unable to GET');
}
});
This is what I get back:
nodetest1.usercollection
View: userlist
extends layout
block content
h1.
User List
u1
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
default route:
exports.index = function(db) {
return function(req, res) {
var collection = db.get('usercollection');
collection.find({},{}, function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
};
};
am I way off here or can someone see what I am doing wrong.
A call to FindAll returns a MongoCursor.
A quick way to convert that to a JSON format would be:
Return collection.ToArray().ToJSON()
You could loop through each result using a technique like this:
For Each document in collection
' do something with each document
Next document
Depending on the size of the results, you may find that returning the response uses a lot of server memory and takes a substantial amount of time to transmit and process in JavaScript.
Also, for production code, I'd recommend that the connection to MongoDB be only created once. The connection is thread safe and reusable (and uses a connection pool to support multiple clients). Opening and closing connections is "expensive."
I am building an application using AngularJS and I have a login form from which I want to send JSON data as request body.
In my controller;
$scope.credentials = {userid: $scope.userid, password: $scope.password};
$scope.login = function () {
$http({
method : 'POST',
url : 'http://localhost/login.json',
data : $scope.credentials,
headers: {'Content-Type': 'application/json'}
}).success(function (data) {
// code
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
console.log($scope.status);
});
};
But when I am submitting the form POST request is not performing and I am getting a message in the console like;
0 function (name) {
"use strict";
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}
What am I doing wrong here?
If I changed the line
headers: {'Content-Type': 'application/json'}
to
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
the POST request is making. But I don't want to send it as form values instead I want to send the request as JSON.
You should encode javascript object to corresponding mime-type data in order to post data. If you are using jQuery, try to use $.param($scope.credentials) instead of just $scope.credentials.
I think the problem is that you're POSTing to http://localhost/login.json which is not any script that is able to receive POSTrequests with form data.
I'm using xml service to get response but i get null response from service.please help me solve this problem.............
By this service i am sending username and password but both wrong and right is going to succeess part because my service will return nulll value but it will be work fine in POSTMAN.........
<script>
function callXMLConnection() {
alert("call Xml method call");
var un=$("#user").val();
var pw=$("#pwd").val();
var myurl="http://192.162.1.153/EServices/retrieve.aspx";
$.support.cors = true;
$.ajax({
data :"",
type: "POST",
url:myurl,
dataType: "xml",
contentType: "application/xml; charset=utf-8",
crossDomain:true,
success: function(data, textStatus, jqXHR){
alert("text : "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("No data found."+jqXHR);
}
});
}
$(document).unbind('pageinit').bind('pageinit', function () {
$("#userInfo").click(function () {
callXMLConnection();
});
});
</script>
this is my get authentication method
Private Sub GenerateXMLPostMethod(ByVal Format As String, ByRef iostream As Stream)
Try
Dim WSCOMMAND As String, TMPSTR As String As String
WS_USERID = Page.Request.Item("username")
WSCOMMAND = Page.Request.Item("command")
Select Case WSCOMMAND
Case "get_authentication"
Application_Error("Responded at:" & System.DateTime.Now)
WSCOMMAND = Page.Request.Item("username")
TMPSTR = Page.Request.Item("password")
DeviceID = Page.Request.Item("deviceid")
TMPSTR = Page.Request.Item("command")&"&username"&Page.Request.Item("username") & "&password"&Page.Request.Item("username")
TMPSTR = Page.Request.Item("password") 'Passowrd
LBFN_GET_USER(WSCOMMAND, TMPSTR, iostream)
End Select
Catch ex As Exception
Application_Error("GenerateXMLPostMethod :" + ex.Message)
End Try
In code there is no data(username, password ) pass to the server, modify the your code, with
data:"" // sending null value
use like this
data:{usename:un,password:pw}
In server page you can get the values from username,password using post method
I am trying to pass some text from a textbox to a controller to get JSON results like so
function invokeAction() {
var searchText = $("#SearchTextBox").val();
// Invoke MVC controller action
$.getJSON("/Home/Results/" + searchText, bindResults);
}
If I put an alert here I can see that searchText definately has a value, but when I put a break point on this controller action:
public ActionResult Results(string search)
{
var r = from t in db.Restaurants
where SqlMethods.Like(t.Name, "%" + search + "%") || SqlMethods.Like(t.Postcode, search + "%") || SqlMethods.Like(t.CuisineType.Type, search + "%")
orderby t.Name ascending
orderby t.Rating descending
orderby t.NumOfViews
descending
select t;
return Json(r.ToList());
}
The string passed in is null, yet when I check the http context in the debugger my searchtext is a part of the url.
As this is null the query returns no results.
Am I missing something here?
I've had some problems returning json from services and I wasn't getting any calls back. it turned out that the json was malformed and I was able to test that and get those errors by handling the error option of the plain ajax call.
$.ajax({
type: "GET",
url: "Home/Results/",
data: { search: searchText },
dataType: "json",
error: function(xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function(json){
alert( "Data Returned: " + json);
}
});
You will have to fix your route and replace {id} with {search} in order to get it to bind to the correct parameter - try something like this:
routes.MapRoute("search", "Home/Results/{search}",
new { controller = "Home", action = "Results" });
If you don't want to do that, you can do it like this by specifying the parametername as a standard querystring paramter
$.getJSON("/Home/Results?search=" + searchText,bindresults);
that will fix the binding.