Jquery Autocomplete with json fails - javascript

I am using the auto complete plugin by Devbridge and I have it all installed here is my code:
$(document).ready(function(){
$('#request_task').autocomplete({
serviceUrl: '<%= ajax_path %>',
minChars:1,
width: 300,
delimiter: /(,|;)\s*/,
deferRequestBy: 0, //miliseconds
params: { artists: 'Yes' },
});
});
This request hits my rails action and returns this json. there is only one object returned but most of the time there will be more then 1...this was just a test case:
[
{
"user": {
"salt": "somthing",
"name": "john",
"encrypted_password": "92dadsfa6b001ffe71c3c1d8e9fb76c42d1c8afeffa739de9063d94206c",
"created_at": "2010-09-10T14:10:54Z",
"updated_at": "2010-09-10T14:10:54Z",
"admin": null,
"id": 1,
"remember_token": "c945522b3eb0a25e36bb39155fc05b3eec301ac5e2196956f2e6f86b4b22c987",
"email": "test#gmail.com"
}
}
]
I can clearly see the request in firebug but I am not getting anything for the autocomplete and it errors out...Am i missing anything...My error is
a.suggestions is undefined

I think you need to read a little further down the developers page as your response is in the wrong format:
Web page that provides data for Ajax
Autocomplete, in our case
autocomplete.ashx will receive GET
request with querystring ?query=Li,
and it must return JSON data in the
following format:
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}
Notes:
query - original query value
suggestions - comma separated array of suggested values data
(optional) - data array, that contains values for callback function when data is selected.

Sincere advice , dont construct JSON Strings. Please go for an API.
If you are using java, check this out http://www.json.org/java/
and make sure to set content-type in response as application/json

YOUR JSON is in a wrong format
Check their correct format
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}

Related

Can't Parse Client Side JSON Object Created with Python/Django

I'm passing an object of data from a Python/Django App to the front end using AJAX in JSON form. Everything is working correctly, except that I cannot parse the JSON object once in Javascript. I keep getting undefined. I've tried every approach I could think of and I am super stuck so I wanted to see if someone might be able to point out what I hope is a super simple oversight!
Snippet of Python/Django:
data = serializers.serialize('json', products)
response = {'product_data': data,
'product_count': product_count}
return HttpResponse(json.dumps(response), content_type='application/json')
Snippet of AJAX Callback:
.done(function(data){
console.log(data.product_count)
console.log(data.product_data)
console.log(data.product_data["model"])
console.log(data.product_data[0])
console.log(data.product_data[0]["model"])
})
Console Logs Response Snippet:
>1
>[{"model": "seller.product", "pk": 11048, "fields": {"seller": 132, "width": 211, "height": 3, "length": 350, "weight": 18600, "price": 11077, "color_id": null, "po_number": null, "po_sub_number": null, "custom_order_id": null, "active_at": "2019-08-02T01:27:23.410Z", "deactive_at": null, "in_holding": false, "approved_at": "2019-08-04T15:34:08.318Z", "sold_at": "2020-02-07T20:07:54.675Z", "slug": "colored-beni-ourain-rug", "created_at": "2019-08-02T01:23:51.650Z", "updated_at": "2020-02-07T20:07:54.675Z", "assets": [3567, 3581, 3585, 3572, 3573, 3574, 3577, 3582, 3583, 3584, 3586, 3587, 3589, 3594, 3596], "colors": [1, 2, 3, 4, 12], "shipping_options": [1]}}]
> undefined
> [
> undefined
The first console log of 1 is correct and in the second line the data I want is all there. But any time I try and get info out of it I just get undefined or a ] and I cannot figure it out. Can anyone help? Thank you!
Use JSONResponse instead of HttpResponse.
That way you don't need to handle anything in between.
return JSONResponse(products)
:)
"json.dumps" would've been sufficient tho, no need for another call to the serializer.
You're serializing you data multiple times, just put products into response without serializing it.
response = {'product_data': products,
'product_count': product_count}
return HttpResponse(json.dumps(response), content_type='application/json')
I believe you need to JSON.parse(data.product_data) first.

getting signature error for _POST_ORDER_FULFILLMENT_DATA_

I'm trying to post fulfillment data on SubmitFeed using javascript in sapui5 and i have done the steps as,
1) I have created json object for fulfillment data and converted it into XML again XML converted into MD5.
JSON code:-
{
"AmazonEnvelope": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"-xsi:noNamespaceSchemaLocation": "amznenvelope.xsd",
"Header": {
"DocumentVersion": "1.01",
"MerchantIdentifier": "Example"
},
"MessageType": "OrderFulfillment",
"Message": {
"MessageID": "1",
"OperationType": "Update",
"OrderFulfillment": {
"AmazonOrderID": "102-8289425-201934",
"FulfillmentDate": "2017-06-20T00:36:33-08:00",
"FulfillmentData": {
"CarrierName": "UPS",
"ShippingMethod": "Second Day",
"ShipperTrackingNumber": "1234567890"
},
"Item": {
"AmazonOrderItemCode": "1234567",
"MerchantFulfillmentItemID": "1234567",
"Quantity": "2"
}
}
}
}
};
2) Created signature as per the api documents.
3) Post the data on Feed/2009-01-01.
but i'm getting the error as:-
"<?xml version="1.0"?>
<ErrorResponse xmlns="https://mws.amazonservices.com/">
<Error>
<Type>Sender</Type>
<Code>InvalidAddress</Code>
<Message>Resource /$metadata is not found on this server. API Version is missing</Message>
</Error>
<RequestID>c00cb653-f53c-445f-9f24-82587144805d</RequestID>
</ErrorResponse>
"
Please help me to resolve this.
Thank you
The error you are getting is InvalidAddress, not a signature check error. It seems whatever you are doing in step 3 (Post the data on Feed/2009-01-01) does not work as expected. The MWS servers see a request for /$metadata instead of API name and version. Your question does not include the piece of code that does that.

_changes API not working with filter and view parameter on Couchbase Lite

The _changes document is not clear on the filter and view parameters, in Couchbase Lite. I am trying to query the below url to fetch changes if a document with type order gets added.
_changes?include_docs=true&feed=longpoll&since=0&filter=_view&view=orders%2Forder
This filter=_view&view=orders%2Forder query parameter is the issue, removing the same from the above fetches all the documents
Using the above gives a 404 on Couchbase Lite but the same works on CouchDB.
Response:
{
status: 404,
error: "not_found"
}
Here is my _design/orders
{
"_id": "_design/orders",
"language": "javascript",
"views": {
"order": {
"map": "function(doc) {if(doc.type && doc.type == 'order') {emit(doc.oID, doc);}}"
}
}
}
Please can any one share a syntax or example on how to pass the design document and/or view in _changes API to get a filtered output.
Everyone who finds this, I think the answer could be changing the filter itself and the query string like this:
Filter:
{
"_id": "_design/orders",
"language": "javascript",
"filters": {
"order": "function(doc) {if(doc.type && doc.type == 'order') {emit(doc.oID, doc);}}"
}
}
and the query string:
_changes?include_docs=true&feed=longpoll&since=0&filter=orders/order

How to make an AJAX call to a locally defined variable

I'm trying generate a list after an obtained JSON, I found docs from dynatable library so they can populate a table in the ajax way receiving a JSON.
However, what if I already have the json stored in a variable. I've tried this so far:
var json = {
"records": [
{
"someAttribute": "I am record one",
"someOtherAttribute": "Fetched by AJAX"
},
{
"someAttribute": "I am record two",
"someOtherAttribute": "Cuz it's awesome"
},
{
"someAttribute": "I am record three",
"someOtherAttribute": "Yup, still AJAX"
}
],
"queryRecordCount": 3,
"totalRecordCount": 3
}
var table = $('#resultados').dynatable({
dataset: {
ajax: true,
ajaxUrl: json,
ajaxOnLoad: true,
records: []
}
})
So I'm getting a 404 code, I understand that's because that's not an actual route. But what can I do to tell library to request for that file. Isn't even ajax required?
Since you already have it in a javascript array called json, you can (I make the assumption that you want to use json.records):
$('#resultados').dynatable({
dataset: {
records: json.records
}
});

twitter typeahead 0.9.3 remote return URL and json object

in bootstrap 2, I used the following code to post a json object,
$('#typeahead').typeahead({
source: function (query, process) {
var URL = 'http://localhost:8080/autocomplete/search/';
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return $.getJSON(URL,
{ query: JSON.stringify(query)},
function (data) {
return process(data);
});
}
});
Now in twitter tyeahead 0.9.3 they have done away with the source concept and moved to a remote concept, but unfortunately I do no know how to work with it.
$(".typeahead").typeahead({
remote : {
url: 'http://localhost:8080/autocomplete/search/',
replace: function(uri, query) {
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return uri + JSON.stringify(query);
},
filter: function(response) {
return response.matches;
}
return process(resultList);
}
}
Unfortunately it doesn't work, how do I just post the JSON object rather than appending it to the string? Thanks.
In your original code you use $.getJSON. This will send a request (and expects json as result) to: http://localhost:8080/autocomplete/search/?query=%7B%22t%3AjsonStringField%22%3A%7B%22name%22%3A%22model%22%2C%22value%22%3A%22fusion%22%7D%2C%22t%3AjsonStringFilter%22%3A%5B%7B%22name%22%3A%22year%22%2C%22value%22%3A%222009%22%7D%2C%7B%22name%22%3A%22make%22%2C%22value%22%3A%22ford%22%7D%5D%7D
To do the same for Twitter's Typeahead call your replace function of your remote data should return a valid url. In your function the ?query= part of the url is missing.
You will have to set: url: 'http://localhost:8080/autocomplete/search/?query=',
You also will have to urlencode you json input maybe.
Note: you will not need the line return process(resultList); You will have to use the filter function to convert your json results to valid data:
The individual units that compose datasets are called datums. The
canonical form of a datum is an object with a value property and a
tokens property.
you could use templates to style your dropdown results, see: http://twitter.github.io/typeahead.js/examples/
By default, the dropdown menu created by typeahead.js is going to look
ugly and you'll want to style it to ensure it fits into the theme of
your web page.
You will need the additional CSS from https://github.com/jharding/typeahead.js-bootstrap.css to style the default dropdown for Bootstrap.

Categories

Resources