I'm trying to verify my transaction with the URL JSON format of bitcoin for my app with a sample request. and I don't know if in this URL I have the answer for my case. I need to show data in a list. the information request I need is the payment it's ok. can you help me?
request: https://blockchain.info/tx/a47b5f0e31faaec5ff7d8d7c4662e174dae99ecbddd9bf32a846017b69c98794?format=json
$.ajax({
url:'https://blockchain.info/tx/a47b5f0e31faaec5ff7d8d7c4662e174dae99ecbddd9bf32a846017b69c98794?format=json',
type: 'POST',
dataType: 'HTML',
data: {param1: 'value1'},
})
.done(function(data) {
alert(data);
console.log("success");
//check the json and print result
$('#answer').html("<li>"+data+"</li>");
})
.fail(function(data) {
alert("Error: " + data);
console.log("error");
})
.always(function() {
console.log("complete");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="answer">waiting..</div>
i think i understood your question so you want to fetch data then print to the DOM a list of transaction values so i used fetch API to retrieve the transaction value then i grabbed the out transactions iterated over them and created an "li" for each value and append it to the DOM , hope this helps you
let proxyUrl = 'https://cors-anywhere.herokuapp.com/'
const list = document.getElementById('values')
const renderValues = (values) => {
values.forEach(value => {
const element = document.createElement('li')
console.log(element)
element.innerHTML = value.value
list.appendChild(element)
})
}
fetch(proxyUrl + 'https://blockchain.info/tx/a47b5f0e31faaec5ff7d8d7c4662e174dae99ecbddd9bf32a846017b69c98794?format=json').then(data => data.json()).then(res => renderValues(res.out)).catch(err => console.error(err))
<div id="answer">
<ul id="values">
</ul>
</div>
Related
Currently I have a main view called getRolesByYear.cshtml. In this view I have three buttons, each for an year. When I click a button(or on page load) I invoke a method, which takes an int 'year' for a parameter and calls an ajax with the year parameter. This ajax calls an action method (getRolesByYear, the one for the main view). The Action method makes a query to a database, a result of which is a list of ViewModel objects. In the return statement I return a PartialView like this : return PartialView("_yearlyRoles",list);. Sadly, after all this, instead of getting a list of the desired objects in my frontend, all i get is an error from the error part of the ajax call. I am generally a novice and I am very stuck with this.
Here is the main view getRolesByYear.cshtml:
#{
ViewBag.Title = "getRolesByYear";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
getRolesForYear(parseInt(#DateTime.Now.Year));
$(function () {
$('#years a').click(function () {
var year = $(this).text();
console.log(year);
getRolesForYear(parseInt(year));
});
})
//console.log(year);
function getRolesForYear(year) {
console.log(year);
$.ajax({
type: "POST",
url: '#Url.Action("getRolesByYear", "WorkRoles")',
dataType: "json",
data: {
year: year
},
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$("#partial").html(data);
}
function errorFunc() {
alert('error');
}
}
</script>
<div id = "years" class="btn-group btn-group-justified timeline">
#DateTime.Now.Year
#DateTime.Now.AddYears(-1).Year
#DateTime.Now.AddYears(-2).Year
</div>
<div id = "partial"></div>
The partial view :
#model IEnumerable<eksp.Models.RoleViewModel>
#foreach (var item in Model)
{
<div class="jumbotron">
<h2>item.Role.RoleName</h2>
<h1> item.Role.RoleDescription</h1>
<p class="lead">Focus start : item.Role.FocusStart</p>
<p>Focus end : item.Role.FocusStart </p>
</div>
}
The Action Method :
[HttpPost]
public ActionResult getRolesByYear(int year)
{
string currentUserId = User.Identity.GetUserId();
var list = db.WorkRoles.
Join(db.WorkRolesUsersDetails,
o => o.WorkRoleId, od => od.WorkRoleId,
(o, od) => new
{
WorkRoleId = o.WorkRoleId,
RoleName = o.RoleName,
RoleDescription = o.RoleDescription,
CompanyId = o.CompanyId,
WRUDId = od.WRUDId,
UserDetailsId = od.UserDetailsId,
FocusStart = od.FocusStart,
FocusEnd = od.FocusEnd
}).ToList()
.Select(item => new RoleViewModel(
item.WorkRoleId,
item.RoleName,
item.RoleDescription,
item.CompanyId,
item.WRUDId,
item.UserDetailsId,
item.FocusStart,
item.FocusEnd)).ToList();
//RoleViewModel rv = list;
if (Request.IsAjaxRequest())
{
return PartialView("_yearlyRoles", list);
}
else
{
return View(list);
}
}
Given the reported error message, you need to alter your ajax call. By setting "data" parameter to "json" you're telling ajax to expect JSON-formatted data back in the response, but a partial view is HTML, so change your ajax call to reflect this:
$.ajax({
type: "POST",
url: '#Url.Action("getRolesByYear", "WorkRoles")/' + year,
dataType: "html", //set the correct data type for the response
success: successFunc,
error: errorFunc
});
As an aside, you can improve your error handling on the client side quite straightforwardly by changing errorFunc to something like this, using the parameters that are provided to the callback by $.ajax:
function errorFunc(jQXHR, textStatus, errorThrown) {
alert("An error occurred while trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}
For less instrusive reporting and/or easier debugging, you could change the alert to console.log. To get more detail you could also log the entire jQXHR object:
console.log(JSON.stringify(jQXHR));
my problem is, i can't retrieve data using AJAX (post) on my NodeJS and MongoDB. Im using body-parser. i use post request because the data will be dependent on what the value of my 1st dropdown is.
Here is my code
NodeJS
app.get('/test', function(req, res){
City.findOne({'thecity': 'Auckland'}).populate('coolplaces').exec(function(err, thecoolplace){
if(err){
console.log(err);
} else {
res.send(thecoolplace);
}
});
});
app.post('/testpost', function(req, res){
City.findOne({'thecity': req.body.thecityname}).populate('coolplaces').exec(function(err, thecoolplace){
if(err){
console.log(err);
} else {
res.send(thecoolplace);
}
});
});
EJS
<select id="cities" name="thecityname">
<% City.forEach(function(city){ %>
<option val="<%= city.thecity %>"><%= city.thecity %></option>
<% }); %>
</select>
<select id="coolplace" name="thecities">
</select>
So basically, i have 2 dropdown list, my goal is, on my 1st dropdown, it contains the city name, then when i selected a city name on it, it should fillup the second dropdown with the places based on that city (i've handled that data on database).
As you can see on my NodeJS code, at first, i tried using GET request then query the database based on its name and i used hardcoded one which is 'Auckland', the ajax call works find, it fills up the second drop down of the places in Auckland.
Now since my goal is to populate the second form based on the selected value on 1st dropdown, i create a post request, same code, except the query value will depend on the 'req.body.thecityname' which is the 'name' of my tag.
Now this is my Ajax Code
$('#cities').change(function(){
theAjax();
});
function theAjax(){
console.log($('#cities').val())
$.ajax({
type: 'POST',
url: '/testpost',
data: $('#cities').val(),
success: function(data){
console.log(data);
},
error: function(){
alert('No data');
}
});
}
function fillupPlaces(){
var $coolplaces = $('#coolplace');
$.ajax({
url: '/test',
type: 'GET',
dataType: 'json',
success: function(data){
data.coolplaces.forEach(function(thecoolplaces){
$coolplaces.append('<option>' + thecoolplaces.theplacename + '</option>');
});
}
});
}
Whenever the value on the 1st dropdown change, the Ajax will trigger, on the 1st line, i console.log the value of it and it returns the value of the data that i selected, but on the Ajax success, the console.log(data) returns nothing.
The second function works, but what i want is, to fillup the second dropdown with the places based on the city
Here's the screenshot
What am i doing wrong? thank you guys!
Try changing the post data to an object with the key 'thecityname' and the value as the city name.
function theAjax(){
console.log($('#cities').val())
$.ajax({
type: 'POST',
url: '/testpost',
data: {
thecityname: $('#cities').val(),
},
success: function(data){
console.log(data);
},
error: function(){
alert('No data');
}
});
}
Adding a console.log like below may be helpful. If only the city is sent as post data, instead of an object with key 'thecityname', then req.body.thecityname will be undefined.
app.post('/testpost', function(req, res){
console.log('req.body.thecityname is ' + req.body.thecityname);
City.findOne({'thecity': req.body.thecityname}).populate('coolplaces').exec(function(err, thecoolplace){
if(err){
console.log(err);
} else {
res.send(thecoolplace);
}
});
});
Im trying to use ajax to sent request. I have CartsController and a method add. Please help!
<?php
echo $this->Html->link('Add', array('controller'=>'carts',
'action'=>'add', 'product_id'=>$product['Product']['id']),
array('class'=>'btn btn-primary col-md-offset-4',
'data-product-id'=>$product['Product']['id']));
?>
$('a.btn').on('click', function(e){
var this = $(this);
var product_id = this.data('product-id');
this.html('Item Added');
$.ajax({
url: '/cartphp_cart/carts/add/',
type: 'POST',
data: {product_id: product_id},
success: function(count) {
$('#number-of-items').text(' ' + count);
console.log(count);
}
});
e.preventDefault();
});
If the ajax request is OK, than in your add method of CartsController
you can get it by
if ($this->request->is('post') || $this->request->is('put')) {
debug($this->request->data['product_id'])
}
You should be able to access the data you've put in your ajax request by
if( $this->request->is('ajax') ) {
pr($this->request->data['product_id']);
// Or try printing the whole $this->request->data if you need other items.
}
I am trying to use ko.mapping to transform data to a viewmodel. The result come from an async call to a web service.
Simple view:
<div data-bind="with: myData">
<div data-bind="text: mapWidth"></div>
<div data-bind="text: mapHeight"></div>
<div data-bind="foreach: priceRanges">
<div data-bind="text: title"></div>
</div>
AND the view model is as follows:
var ViewModel = function() {
var self = this;
self.myData = null;
var data = {
action: 'GetPricePoints',
type: 'who cares'
};
$.ajax({
url: 'http://cdt.lotamore.com/api/imap',
data: { "": JSON.stringify(data) },
//async: false, // works!
async: true, // doesn't work!!!!!
type: 'post'
})
.done(function (data) {
self.myData = ko.mapping.fromJS(data);
})
.error(function (data) {
alertError(data);
})
.always(function () {
});
};
When I run this synchronously is works fine. However, when I run it asynchronously it doesn't update the myData within my view model.
I have created a fiddle here:
http://jsfiddle.net/jgergen/jF9pm/20/
I really don't want to make ajax calls that block the UI thread!
What am I doing wrong here?
Thanks,
Jim
Here is the solution:
I have changed the line:
self.myData = null;
to:
self.myData = ko.observable();
This is not all, I tried this before without favorable results. In addition to making myData observable, I had to change the way it is updated. Here is the new .done method:
.done(function (d) {
self.myData(ko.mapping.fromJS(d));
})
So, what I needed to do is treat this field as I would any other observable.
You can see it here at this new fiddle: http://jsfiddle.net/jgergen/jF9pm/47/
I hope that this helps more than me. I searched for a solution to this problem all over the web without any results. So here it is.
Thanks,
Jim
I am looking to call an ajax function inside the Datatables mRender function that will use an id from the present ajax source to get data from a different ajax source.
To put this into perspective, I have:
A listing of requisitions from different clients in one Datatable.
In this listing I have a client id. I want to get the client Name to be shown on the table instead of the client Id. However the Client Name and other client details are in the clients table hence these details are not in the requisitions json data. But I have the Client Id.
How do I use this to get client name inside the mrender function? E.g
{"sTitle":"Client","mData":null,
"mRender":function(data){
//ajax function
}
},
Thank you in advance,
Regards.
I don't believe this is how you are supposed to deal with your data. However I also use an AJAX data source in my mRender function as stated below.
$(document).ready(function(e){
$('.products').dataTable({
"bProcessing": true,
"sAjaxSource": window.location.protocol + "//" + window.location.hostname + '/product/getAll',
"aoColumns": [
{ "sTitle": "Pid", "bVisible" : false},
{ "sTitle": "Pname" },
{ "sTitle": "Pprice" },
{ "sTitle": "Pgroups",
"mRender" : function( data, type, full ){
console.log( data, type, full );
console.log(category.getAll());
return 'test';
}
}
]
});
});
De category object is initialized in a selfinvoking function. I used this to prevent the function from loading the data remotely each time the function is called.
It looks like this:
(function(){
if(typeof category === 'undefined'){
category = {};
}
category.getAll = function(){
if(typeof category.all === 'undefined'){
$.ajax({
'type' : 'POST',
'async': false,
'url' : window.location.protocol + "//" + window.location.hostname + "/category/getAll",
'success' : function(data){
console.log(data);
category.all = data;
},
'error': function(a,b,c){
console.log("You shall not pass!",a,b,c);
alert('stop');
}
});
}
return category.all;
}
})();