Update function for typeahead - javascript

I want to get data from server and suggest with typeahead.
I get my data from list to an usl like /foo/q=QUERY and this query return json like ["salam","bye", "khodafez,].
How i can use from bootstrap typeahead to suggestion.
I try this code:
<script type="text/javascript">
$(document).ready(function() {
$("#vahid").typeahead({
// ???
});
});
</script>

According to the documentation, you just provide a function for source in the options:
$("#vahid").typeahead({
source: function(query, process) {
// `query` is the text in the field
// `process` is a function to call back with the array
$.ajax({
// Your URL
url: "/foo",
// Your argument with the query as its value
data: {q: query},
// Success callback -- since it expects the first
// parameter to be the data, and that's what the
// success callback is called with, you can just
// use `process` directly
success: process
});
}
});
The above assumes that the response correctly identifies the response as Content-Type: application/json. If it doesn't, add
dataType: "json"
...to your ajax options.
I'm using the asynchronous mechanism because you're querying a server. If you already had the data client-side, you could simply return it from the source function directly. But they (intelligently) don't require you to retrieve it synchronously from the server, as that would lead to a bad XU.

Accourding to docs https://github.com/tcrosen/twitter-bootstrap-typeahead
you can add ajax attr like :
$('#myElement').typeahead({
ajax: '/path/to/mySource'
});
or
var mySource = [
{ id: 1, name: 'Terry'}, { id: 2, name: 'Mark'}, { id: 3, name: 'Jacob'}
];
$('#myElement').typeahead({
source: mySource
});
for local data

Related

First param of the Query String not being sent on AJAX call as GET parameter, why?

I am using this code to sent an AJAX call within a Select2 element:
var condition_type = 'something'; // this is dynamic but I turned on a string for demonstration
var field_value = 'something_1'; // this is dynamic but I turned on a string for demonstration
$('#condition_value_1').select2({
placeholder: 'Start typing ...',
allowClear: true,
tags: true,
ajax: {
url: '/search',
dataType: 'json',
minimumInputLength: 2,
delay: 250,
data: function(params) {
return {
keyword: params.term,
condition: condition_type,
field: field_value
};
},
processResults: function(data) {
return {
results: data.items
};
}
}
});
The code above works and is sending an AJAX request with the following structure:
/search?keyword=some&condition=something&field=something_1
I should be getting three GET parameters but instead I am getting only the last two and I am not sure why this behavior. Take a look to the debug window from phpStorm:
Notice how condition and field are part of the REQUEST and are being passed as GET parameters but where is the first one keyword? Shouldn't be part of the REQUEST as well? I am missing something here on the configuration either PHP or Select2?

Can Mockjax handle single IDs Api from Json file

I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?
current code :
$.mockjax({
url: "/Api/Cases/{caseId}",
proxy: "/mocks/cases nuevo.json",
dataType: 'json',
responseTime: [500, 800]
});
$.ajax({
type: 'GET',
url: '/Api/Cases/',
data: {caseId: taskId},
success: function(data){
//use the returned
console.log(data);
}
});
current error:
GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)
Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.
Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:
$.mockjax({
url: /\/Api\/Cases\/(\d+)/, // notice the regex here to allow for any ID
urlParams: ['caseID'], // This defines the first matching group as "caseID"
responseTime: [500, 800],
response: function(settings, mockDone) {
// hold onto the mock response object
var respObj = this;
// get the mock data file
$.ajax({
url: 'mocks/test-data.json',
success: function(data) {
respObj.status = 200;
// We can now use "caseID" off of the mock settings.urlParams object
respObj.responseText = data[settings.urlParams.caseID];
mockDone();
},
error: function() {
respObj.status = 500;
respObj.responseText = 'Error retrieving mock data';
mockDone();
}
});
}
});
There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId, // this will add the ID to the URL
// data: {caseId: taskId}, // this adds the data to the query string
success: function(data){
//use the returned
console.log(data);
}
});
Note that this presumes the mock data is something like:
{
"13": { "name": "Jordan", "level": 21, "id": 13 },
"27": { "name": "Random Guy", "level": 20, "id": 27 }
}
What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId,
success: function(data){
//note you have to parse the data as it is received as string
data = JSON.parse(data);
var result = $.grep(data, function(e){ return e.caseId == taskId; });
//since i'm expecting only one result, i pull out the result on the 0 index position
requestedData = result[0];
}
});
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API, And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];
**Note: **
A more suited solution would be a mixture between what i've done and #jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:
[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]

JSON to HTML table using 'datatable' plugin

I'm trying to generate a HTML data table from the result of a SQL query execution. The resulting data is in JSON format. I'm using the plugin "Datatables" to achieve this. I'm following this example
I don't get an error but the data table is empty. I'm obviously doing something wrong or missing something.
Here's the code excerpt. Could I please get some guidance on to the right path please.
function jsDataPlot(chartProps) {
// Get the array from the element:
var graphPropsStore = chartProps;
// Loop through the array with the jQuery each function:
$.each(graphPropsStore, function (k, graphPropsStoreProperty) {
// The makeCall function returns a ajaxObject so the object gets put in var promise
var dbResAjx = getResultFromSql(k);
// Now fill the success function in this ajaxObject (could also use .error() or .done() )
dbResAjx.success(function (response) {
console.log(response);
// When success, call the function and use the values out of the array above
$('#divId').DataTable(response);
});
dbResAjx.error(function (response) {
console.log(response);
});
});
}
function getResultFromSql(paramId) {
// bla bla code
return $.ajax({
url: 'runMySqlQuery.php',
type: 'post',
data: {// some POST params}
});
}
JSON Result
[{"DATE":"2015-12-15","TYPE":"AAA","NAME":"asdasd"},{"DATE":"2015-12-15","TYPE":"BBB","NAME":"dsfsdfsdfsdf"},{"DATE":"2015-12-15","TYPE":"AAA","NAME":"reterter"},{"DATE":"2015-12-15","TYPE":"CCC","NAME":"ertertertert"}]
OK, in your JSON yu have this. DATE - TYPE - NAME
[
{"DATE":"2015-12-15","TYPE":"AAA","NAME":"asdasd"},
{"DATE":"2015-12-15","TYPE":"BBB","NAME":"dsfsdfsdfsdf"},
{"DATE":"2015-12-15","TYPE":"AAA","NAME":"reterter"},
{"DATE":"2015-12-15","TYPE":"CCC","NAME":"ertertertert"}
]
then in your JS should define your columns ....
$('#divId').DataTable({
columns : [
{data: "DATE"},
{data: "TYPE"},
{data: "NAME"}
],
data: response
});
example: https://jsfiddle.net/cmedina/7kfmyw6x/4/

How to construct the POST data values in an AJAX call?

i've this piece of code that performs an AJAX call
$.ajax({
url : 'inviaCommento.php',
type : 'POST',
data : {page: page, category: category}
dataType : 'json',
success : function (msg)
//...and so on
The problem is that i want to check if a search parameter is set, if yes i've to add the word to the data parameters.
The question is: can i costruct the data parameters before the call appendig values to it?
Something like this:
if $('#searchBtn').val()!=''
{
data.append(search: $('#searchBtn').val())
}
Yeah, just create an array.
var data = {something: [], page: page, category: category, somekey: "default"};
data.something.push("a");
data.something.push("b");
if (...) {
data.somekey = "new value";
}
$.ajax({
...
data: data
});
Yup, but data isn't a list, it's an object, so you just assign to the appropriate key.
var data = {page:page}; // ... current value of data: param in the $.ajax call
if($('#searchBtn').val()!=='')
{
data.search= $('#searchBtn').val();
}
You'd put this above the $.ajax() call.

Get values from object using Backbonejs

i want to get value from this API http://demo82.com/lois/api/get_page/?id=6 using Backbone js. i tried but i don't know how can we get values from object in backbone.
here is my Backbone code
Page = Backbone.Model.extend({
initialize: function() {
this.on('all', function() { console.log(this.get('page')); });
},
url: "http://demo82.com/lois/api/get_page/?id=6",
defaults: {
"id":null,
"title":"",
"content":""
}
});
var page = new Page();
console.log(page.fetch({}));
i am new and try to learn backbonejs please explain what is the better way ? please give me ans using jsfiddle.net.
thanks
Is id always going to be 6? In your code, your model is always getting the 6th thing. If you want a custom url with a get parameter, override url as a function:
url: function() {
id = this.get("id");
return "loispage/api/get_page/?id=" + id
}
Better yet, if you have control over the server side and can do something a little more RESTful with a page entity -- simply set urlRoot
urlRoot: "loispage/api/page/"
and fetch will automatically do an HTTP get from
"http://.../loispage/api/page/<id>
It looks like a context problem (this doesn't refer to the model in on's callback). You can fix this by specifying the context:
this.on('all',
function() { console.log(this.get('pagel')); },
this
);
Edit
There's also a cross-domain issue. You'll need to use a JSONP request for this by overriding sync and parse. (I adapted the following code from this example.)
var Page= Backbone.Model.extend({
// override backbone synch to force a jsonp call
sync: function(method, model, options) {
// Default JSON-request options.
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: model.url(),
processData: false
}, options);
// Make the request.
return $.ajax(params);
},
parse: function(response) {
// parse can be invoked for fetch and save, in case of save it can be undefined so check before using
if (response) {
console.log(JSON.stringify(response));
// here you write code to parse the model data returned and return it as a js object
// of attributeName: attributeValue
return { status: response.status }; // just an example
}
},
Here's a JSFiddle demo.

Categories

Resources