ajax json parsing to return related values - json

I am trying to only parse the information related to a certain "market_name" however I cannot seem to figure out how. The api is located at https://stocks.exchange/api2/ticker which displays information related to the entire exchange. I simply need all of the information returned relating to the "market_name" I am searching for such as ETH_BTC
Ajax:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
last = data.last;
console.log(last);
$("#btcprice").text(last);
},
error: function() {
//alert("Was unable to get info!");
}
});

That's because data is an array of objects, not a single object.
Try:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function (data) {
// find object
var market = data.find(function (obj) {
return obj.market_name == 'ETH_BTC';
});
$("#btcprice").text(market.last);
},
error: function() {
//alert("Was unable to get info!");
}
});

Use array filter() method to filter out the record having market_name as ETH_BTC.
array.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
DEMO
var jsonObj = [{"min_order_amount":"0.00000010","ask":"0.00000017","bid":"0.0000001","last":"0.00000010","lastDayAgo":"0.00000009","vol":"154955.9586604","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ATR_BTC","market_id":338,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.000032","bid":"0.000012","last":"0.00003200","lastDayAgo":"0.000065","vol":"372.5011152","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ETH_BTC","market_id":35,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.00003595","bid":"0.00003","last":"0.00003000","lastDayAgo":"0.00003001","vol":"26.44435669","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ARDOR_BTC","market_id":262,"updated_time":1527789301,"server_time":1527789301}];
var res = jsonObj.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
console.log(res);

$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
var results = [];
var searchField = "market_name";
var searchVal = "ETH_BTC";
for (var i=0 ; i < data.length ; i++)
{
if (data[i][searchField] == searchVal) {
results.push(data[i]);
}
}
$("#btcprice").text(results[0].last);
},
error: function() {
//alert("Was unable to get info!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a simple code in which you find what you want simply just change searchVal statically or dynamically according to your need......

Related

Populate textboxes based on id searched

Okay, so i am new to ajax and mvc. i have a form which requires me to enter an id in the field and after clicking the search button it retrieves and populates data from the database and displays it in the textfields.
Controller Code
public ActionResult LoadVendorInfo(string vendornumber)
{
var query = from c in db.Vendors
where c.VendorNumber == vendornumber
select c;
return Json(query.FirstOrDefault());
}
Ajax
<script type="text/javascript">
$(document).ready(function () {
$("#searchvendor").click(function () {
var vendornumber = $('#vendornumber').val();
$.ajax({
cache: 'false',
type: "POST",
data: { "vendornumber": vendornumber },
url: '#Url.Action("LoadVendorInfo", "Vendors")',
datatype: 'json',
"success": function (data) {
if (data != null) {
var vdata = data;
$("#companyname").val(vdata[0].companyname);
$("#regnum").val(vdata[0].regnum);
$("#email").val(vdata[0].email);
$("#contactnum").val(vdata[0].contactnum);
$("#refnum").val(vdata[0].refnum);
}
}
})
})
})

Handling a model returned as json data from a controller in ASP.NET

I have a controller which return a model as json object:
[HttpGet("{id}")]
[Route("GetById")]
public async Task <JsonResult> GetById([FromQuery]string id)
{
var myfoo = new {foo="bar", baz="Blech"};
return Json(myfoo);
}
How can handle the returned json object in jQuery?
<script type="text/javascript">
$('#id').change(function () {
var id = $('#id').val();
if (id.length = 17) {
$.ajax(
{
url: '/Home/GetById?id=' + id,
type: 'GET',
jsondata: "",
contentType: 'application/json; charset=utf-8',
success: function (jsondata) {
alert("foo is: " + jsondata ); <---?
},
error: function () {
//alert("error");
}
});
}
});
</script>
I need to get foo value and assigned to an html control
Thanks in advance
all the time I was using capital letter
jsondata.foo // not .Foo

Bootstrap typeahead ajax result format - Example

I am using Bootstrap typeahead with an ajax function, and want to know what is the correct Json result format, to return an Id and a descripcion.
I need the Id to bind the typeahead selected element with a mvc3 model.
This is the code:
[Html]
<input id="myTypeahead" class='ajax-typeahead' type="text" data-link="myUrl" data-provide="typeahead" />
[Javascript]
$('#myTypeahead').typeahead({
source: function (query, process) {
return $.ajax({
url: $('#myTypeahead').data('link'),
type: 'post',
data: { query: query },
dataType: 'json',
success: function (jsonResult) {
return typeof jsonResult == 'undefined' ? false : process(jsonResult);
}
});
}
});
This works properly when I return a simple list of strings, for example:
{item1, item2, item3}
But I want to return a list with Id, for example:
{
{Id: 1, value: item1},
{Id: 2, value: item2},
{Id: 3, value: item3}
}
How to process this result in the ajax "success: function()"?
That is very easy with jquery Autocomplete, because I can return a Json Object list.
[jquery Autocomplete process data example]
...
success: function (data) {
response($.map(data, function (item) {
return { label: item.Id, value: item.Value, id: item.Id, data: item };
})
...
But that doesn't work with boostrap Typeahead.
Can anyone help me?
Thanks.
I try for two days and finally I could it working.
Bootstrap Typeahead doesn't support an array of objects as a result by default, only an array of string. Because "matcher", "sorter", "updater" and "highlighter" functions expect strings as parameter.
Instead, "Bootstrap" supports customizable "matcher", "sorter", "updater" and "highlighter" functions. So we can rewrite those functions in Typeahead options.
II used Json format, and bound the Id to a hidden html input.
The code:
$('#myTypeahead').typeahead({
source: function (query, process) {
return $.ajax({
url: $('#myTypeahead').data('link'),
type: 'post',
data: { query: query },
dataType: 'json',
success: function (result) {
var resultList = result.map(function (item) {
var aItem = { id: item.Id, name: item.Name };
return JSON.stringify(aItem);
});
return process(resultList);
}
});
},
matcher: function (obj) {
var item = JSON.parse(obj);
return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
},
sorter: function (items) {
var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
while (aItem = items.shift()) {
var item = JSON.parse(aItem);
if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
else caseInsensitive.push(JSON.stringify(item));
}
return beginswith.concat(caseSensitive, caseInsensitive)
},
highlighter: function (obj) {
var item = JSON.parse(obj);
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>'
})
},
updater: function (obj) {
var item = JSON.parse(obj);
$('#IdControl').attr('value', item.id);
return item.name;
}
});
Note: I saw #EralpB`s comment "Is this still the best way to accomplish this task?"
Yes, #Gonzalo solution works, but it seems strange (like crutch,especially after using jQuery-Autocomplete) - it should work "from box".Better is to use this - Bootstrap-3-Typeahead. It supports an array of objects as result: format - [{id: .. ,name:...},...,{id: .. ,name:...}]. Example for OP`s issue:
....
source: function (query, process) {
return $.ajax({
......
success: function (result) {
var resultList = [];
$.map(result,function (Id,value) {
var aItem = { id: Id, name: value};
resultList.push(aItem);
});
return process(resultList);
}
});
},

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

How to get json with backbone.js

I am trying to use backbones.js fetch to get json from a twitter search
and my code below can someone tell me where I am going wrong?
(function($){
var Item = Backbone.Model.extend();
var List = Backbone.Collection.extend({
model: Item,
url:"http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed"
});
var ListView = Backbone.View.extend({
el: $('#test'),
events: {
'click button#add': 'getPost'
},
initialize: function(){
_.bindAll(this, 'render', 'getPost');
this.collection = new List();
this.render();
},
render: function(){
var self = this;
$(this.el).append("<button id='add'>get</button>");
},
getPost: function(){
console.log(this.collection.fetch());
}
});
// **listView instance**: Instantiate main app view.
var listView = new ListView();
})(jQuery);​
I am just getting started with backbone and I just want to console.log the json
you can see my example here. jsfiddle.net/YnJ9q/2/
There are two issues above:
Firstly, you need to add a success/fail callback to the fetch method in order for you to have the fetched JSON logged to the console.
getPost: function(){
var that = this;
this.collection.fetch(
{
success: function () {
console.log(that.collection.toJSON());
},
error: function() {
console.log('Failed to fetch!');
}
});
}
Another problem is the issue of "same-origin-policy'. You can find out how to resolve that by taking a look at this link.
Update:
I modified your code and included the updated sync method. It now works! Take a look here!
Basically, update your collection to include the parse and sync methods as below:
var List = Backbone.Collection.extend({
model: Item,
url: "http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed",
parse: function(response) {
return response.results;
},
sync: function(method, model, options) {
var that = this;
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: that.url,
processData: false
}, options);
return $.ajax(params);
}
});