Hello I'm trying to pull my characters title from the Warcraft Armory but I don't get any returned results. My code is as follows with my character name being replaced with my actual character name .
HTML
<li>Title Prefix: <span id="title">Test</span>
Javascript
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
});
}
);
function GoGet(data) {
$("#title").html(data.titles.name)
;}
The api documentation shows the json items for "titles" as follows:
{
"achievementPoints": 675,
"battlegroup": "Test Battlegroup",
"calcClass": "f",
"class": 10,
"gender": 1,
"lastModified": 1348187981118,
"level": 90,
"name": "Peratryn",
"race": 25,
"realm": "Test Realm",
"thumbnail": "test-realm/1/1-avatar.jpg",
"titles": [
{
"id": 285,
"name": "%s, Savior of Azeroth",
"selected": true
}
]
}
Where am I going wrong?
Not being a WOW player myself, I'll hazard one guess:
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
success: UpdateTitle
});
}
);
function UpdateTitle(response) {
if (response.titles) {
for (var i = 0; i < response.titles.length; i++) {
if (response.titles[i].selected === true) {
$("#title").html(response.titles[i].name);
break;
}
}
}
}
What this is doing is calling UpdateTitle after a successful XHR response from your provided URL. This function will loop through each title and update your #title element with the FIRST selected: true title found in the json response.
Related
I have a data variable holding an object like this:
{
"details": {
"id": 10,
"name": John Doe,
"hobbies": [{
"id": 1,
"name": "Football"
},
{
"id": 2,
"name": "Badminton"
},
{
"id": 3,
"name": "Running"
}
],
"dob": 1989-12-31
}
}
I retrieve it using this AJAX request:
$.ajax({
type: 'POST',
url: "{{ route('askdata') }}",
dataType: 'json',
data: { 'id': $('#member_id').val(), },
success: function(data) {
$('#id').val(data.details.id);
$('#name').val(data.details.name);
$('#dob').val(data.details.dob);
$('#hobbies').val(JSON.stringify(data.details.hobbies, ['name']));
}
});
I get a value in the hobbies input like this:
[{"name":"Football"},{"name":"Badminton"},{"name":"Running"}]
How can I change this to get the values like Football, Badminton, Running?
Your current logic is building a JSON string from the hobbies array. To get the output you want you can use map() to build an array of the hobby names which you can then join() together to form a single string:
let data = {"details":{"id": 10,"name": 'John Doe',"hobbies": [{"id": 1,"name": "Football"},{"id": 2,"name": "Badminton"},{"id": 3,"name": "Running"}],"dob": '1989-12-31'}}
$('#hobbies').val(data.details.hobbies.map(o => o.name).join(', '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="hobbies" size="25" />
Also note that your data object is missing some quotes around the name and dob properties, but I assume that was just a typo in the question otherwise you'd get no output at all.
The best solution is :
$.ajax({
type: 'POST',
url: "{{ route('askdata') }}",
dataType: 'json',
data: { 'id': $('#member_id').val(), },
success: function(data) {
const { details: {id, name, dob, hobbies} } = data
$('#id').val(id);
$('#name').val(name);
$('#dob').val(dob);
$('#hobbies').val(JSON.stringify(hobbies.map(hobby => {
return {name: hobby.name}
})));
}
});
I am using a simple ajax call on load and onclick,I am using function for it.Here my ajax call url is different onload and onclick,I have used function and different parameter but its still showing previous json using onclick. Below is my code,
Updated in plunker https://plnkr.co/edit/YOeklbX5shZCnHVRktyK?p=preview
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
<div id="critical">
<span id="name1"></span> : <span id="value1"></span>
</div>
<div id="major">
<span id="name2"></span> : <span id="value2"></span>
</div>
<div id="minor">
<span id="name3"></span> : <span id="value3"></span>
</div>
<button>click</button>
javascript
$(document).ready(function(){
$.fn.reload_cart = function(){
$.ajax({
type: "GET",
url: "1.json",
success: function(result) {
$("#name1").text(result.critical[0].name);
$("#value1").text(result.critical[0].value);
$("#name2").text(result.major[0].name);
$("#value2").text(result.major[0].value);
$("#name3").text(result.minor[0].name);
$("#value3").text(result.minor[0].value);
}
});
}
$.fn.reload_cart();
$("button").click(function(){
var url2;
$.fn.reload_cart(url2);
url2: "2.json";
});
});
1.json
{
"critical": [{
"name": "critical",
"value": "50"
}],
"major": [{
"name": "major",
"value": "40"
}],
"minor": [{
"name": "minor",
"value": "20"
}]
}
2.json
{
"critical": [{
"name": "criticalnew",
"value": "53"
}],
"major": [{
"name": "majornew",
"value": "43"
}],
"minor": [{
"name": "minornew",
"value": "23"
}]
}
You need to pass the json file name in reload_cart() function and check if file name is passed then read from this file(1.json) else read from another file(2.json). Please your javascript code to following:
$(document).ready(function(){
$.fn.reload_cart = function(url){
if(!url){
url = "1.json"
}
$.ajax({
type: "GET",
url: url,
success: function(result) {
$("#name1").text(result.critical[0].name);
$("#value1").text(result.critical[0].value);
$("#name2").text(result.major[0].name);
$("#value2").text(result.major[0].value);
$("#name3").text(result.minor[0].name);
$("#value3").text(result.minor[0].value);
}
});
}
$.fn.reload_cart();
$("button").click(function(){
var url2 = "2.json";
$.fn.reload_cart(url2);
});
});
I have updated your Plunker
You need to make your reload_cart function accept a parameter url.
$(document).ready(function() {
$.fn.reload_cart = function(url) {
$.ajax({
type: "GET",
url: url,
success: function(result) {
$("#name1").text(result.critical[0].name);
$("#value1").text(result.critical[0].value);
$("#name2").text(result.major[0].name);
$("#value2").text(result.major[0].value);
$("#name3").text(result.minor[0].name);
$("#value3").text(result.minor[0].value);
}
});
}
$.fn.reload_cart("1.json");
$("button").click(function() {
$.fn.reload_cart("2.json");
});
});
I am trying to pass three products through the shopify ajax api. It sends over the variant id and quantity but not the properties. the code is below. if I add request.properties to the Shopify.addItem function it stops after one item and gives me a pop saying that one item has been added to the cart. It does not add the other two items nor does it redirect. If I remove request.properties from the Shopify.addItem function it adds all three items to the cart but with no properties.
FINAL CODE Revised from #miglio code
var FreeTrial={
data:[],
ini:0,
total:0,
addItem:function(qty,id,properties,callback) {
var params = {quantity:qty,id:id};
if(properties != false){
params.properties = properties;
}
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
async:false,
data: params,
success: function(){
if(typeof callback === 'function'){
callback();
}
},
error: function(){}
});
},
recursive:function(){
FreeTrial.addItem(FreeTrial.data[FreeTrial.ini].qty,FreeTrial.data[FreeTrial.ini].id,FreeTrial.data[FreeTrial.ini].properties,function(){
//console.log(FreeTrial.data[FreeTrial.ini]);
FreeTrial.ini += 1;
if(FreeTrial.ini < FreeTrial.total){
FreeTrial.recursive();
}else{
//return false;
document.location.href = '/cart';
}
});
},
begin:function(){
/* SET YOUR ARRAY QTY's' ID's*/
FreeTrial.data = [
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": false
},
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": false
},
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": false
},
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": false
},
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": {
"recurring_price": "200.00",
"shipping_interval_frequency": "30",
"shipping_interval_unit_type": "days",
"subscription_id": "12599"
}
}
];
FreeTrial.total = FreeTrial.data.length;
FreeTrial.recursive();
}
}
FreeTrial.begin();
To add properties I use this function and work fine for me.
addItem=function(qty,id,properties,callback) {
var params = {quantity:qty,id:id};
if(properties != false){
params.properties = properties;
}
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: params,
success: function(){
if(typeof callback === 'function'){
callback();
}
},
error: function(){}
});
}
//Example :
var qty = 1;
var id = 123456;//variant_id
var properties: {
"recurring_price": "12",
"shipping_interval_frequency": "34",
"shipping_interval_unit_type": "56",
"subscription_id": "78"
}
//
addItem(qty,id,properties,function(){
console.log('done');
});
Well, I did this code for multiple items and a save in a gist:
multiple add to cart
Any POST to the endpoint url: '/cart/add.js', can include properties. If the properties are setup correctly, it works like a charm. You can assign as many properties to a variant as you want. Has been working for what, 5 years now? This function has been working for that long at least... no trouble.
addItemWithProperties: function(variant_id, quantity, properties, callback) {
var quantity = quantity || 1;
if(properties) {
var data = properties.join("&")+"&quantity="+quantity+"&id="+variant_id;
} else {
var data = "quantity="+quantity+"&id="+variant_id;
}
var params = {
type: "POST",
url: "/cart/add.js",
data: data,
dataType: "json",
success: function(line_item) {
if((typeof callback) === "function") {
callback(line_item)
} else {
Shopify.onItemAdded(line_item)
}
},
error: function(XMLHttpRequest, textStatus) {
Shopify.api.onError(XMLHttpRequest, textStatus)
}
};
$.ajax(params)
},
edit. I guess you could do the call manually
add to cart
Considering the Shopify.addItem() function is, straight off their API I'm not sure you can simply add a parameter like that.
My guess is that the extra parameter has the effect that the function doesn't run.
I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!
One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]
I have been trying to populate my input with select2 using the JSON provided.
Here's the JSON:
{
"airports":
[
{
"id": "1",
"code": "AMQ",
"city": "Ambon",
"country": "Indonesia"
},
{
"id": "2",
"code": "BJW",
"city": "Bajawa",
"country": "Indonesia"
}
]
}
And the html code:
<input class="" type='hidden' value="192" data-init-text='Departing City' name='input' id='depart-airport' style="width: 300px"/>
And the js code:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
return { results: data};
}
}
});
});
There's no error in console, but whether I try to input them it's always saying that "searching failed" or there's not even anything. The data from json never showed.
Do you have anything to fix this around? Thanks's before :)
You have a minor error in your jQuery:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
// You had { results: data }, but your actual information is in data.airports
return { results: data.airports };
}
}
});
});