Using json objects retrieved by post angular - javascript

I have a post that posts on page load. it returns json. how do i then use this json on the page to display images and text based on the object.
is there a way to hold the value of the objects in scope in angular
My post on page load
$scope.GetData = function () {
$http({
url: "http://www.somepage.co.uk/page/page2/objects",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log(response);
}, function (response) { // optional
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
I would like if I could store the objects in different scopes so that I may use them on the page.
Thanks
UPDATE
here is the object I need to turn into scopes
data
:
Array(1)
0
:
c_name
:
"ben"
d_text
:
[]
max_slots
:
2
resolution
:
(2) [1920, 1080]
slots
:
Array(3)
0
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 1}
1
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 2}
2
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 3}
length
:
3
__proto__
:
Array(0)
__v
:
0
_id
:
"59c92d6f45b79c8c110ee6ab"

Inside the then callback, you have to save the returned data into your $scope :
$scope.GetData = function () {
$http({
url: "http://www.somepage.co.uk/page/page2/objects",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
$scope.data = response; // Save the returned data into your $scope
console.log('you have received the data ');
console.log(response);
}, function (response) { // optional
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};

Related

Shopify Cart AJAX Request Returning Inconsistently

I am attempting to post 2 items to a shopping cart, in one click. I've built a form with hidden checkboxes that carry the relevant product attributes I need to do that. I have a loop going over the form's child checkboxes to pull that info and invoke the function for the post request.
The problem is that sometimes it does add both items (yay!) but sometimes it'll load only the first item and sometimes only the second item. There's no error code in the console for me to go off of so I'm wondering what I'm missing.
EDIT: 19 hours in. I'm thinking the issue is coming from the function that opens the cart that is firing when the first item is returned. Both of the calls are being return successfully but that code is interrupting it being added to the cart.
EDIT 2: This post describes the issue I'm having. I need to make one request and then move on to the next one. I think I'm going to have to build an array with the items from the form.
My JS
const freeAddOnForm = document.getElementById('free-addon-form'),
freeAddOnButton = freeAddOnForm[2];
function getDataForm(e) {
e.preventDefault();
loadingBarTrigger('start');
for(let i = 0; i < 2; i++) {
itemAdd(
freeAddOnForm[i].getAttribute('data-quickadd-id'),
freeAddOnForm[i].getAttribute('data-quickadd-properties'),
(freeAddOnForm[i].getAttribute('data-quickadd-quantity'))
? freeAddOnForm[i].getAttribute('data-quickadd-quantity')
: 1,
(!html.is('#cart')) ? true : false,
(html.is('#cart')) ? true : false
)
}
}
document.addEventListener('DOMContentLoaded', function (){
freeAddOnButton.addEventListener('click', getDataForm, false);
})
The itemAdd function that makes the post request to the cart:
const itemAdd = (variantId, properties, qty, openCart, reloadPage) => {
$.ajax({
type: 'POST',
dataType: 'html',
url: `/cart/add.js`,
data:
{
id: variantId,
quantity: qty,
properties: (properties)
? JSON.parse(properties) : null
},
error: function(data) {
console.error(data);
loadingBarTrigger('done');
},
success: function() {
loadingBarTrigger('move');
$.ajax({
url: '/cart',
dataType: 'html',
error: function(data) {
console.error(data);
loadingBarTrigger('done');
},
success: function(data) {
let minicartContent = $('#minicart-content');
let cartItemsHtml = $(data).find('#cart-content #cart-items').html();
// insert or prepend cart HTML
(minicartContent.find('#cart-items').length)
? minicartContent.find('#cart-items').html(cartItemsHtml)
: minicartContent.prepend(cartItemsHtml);
// remove giftbox content if exists
(minicartContent.find('#cart-giftbox .item-info').length)
? minicartContent.find('#cart-giftbox .item-info').remove()
: '';
loadingBarTrigger('done');
cartTotalUpdate();
// open cart
(openCart && !html.is('#cart'))
? minicartTrigger.trigger('click') : '';
(reloadPage)
? location.reload() : '';
}
});
}
});
}
Ended up putting both items as objects into an array and sending them to the Shopify AJAX api together. Seems to work, a couple little bugs to hammer out with the slide out cart at the end of the function.
const itemsAddAjax = (itemsQueue, openCart, reloadPage) => {
console.log(itemsQueue)
$.post(`/cart/add.js`, {
items: [
{
quantity: itemsQueue[0].qty,
id: itemsQueue[0].id,
properties: (itemsQueue[0].properties)
? JSON.parse(itemsQueue[0].properties) : null
},
{
quantity: itemsQueue[1].qty,
id: itemsQueue[1].id,
properties: (itemsQueue[1].properties)
? JSON.parse(itemsQueue[1].properties) : null
}
],
error: function(items) {
// console.error(items);
loadingBarTrigger('done');
},
success: function() {
loadingBarTrigger('move');
$.ajax({
url: '/cart',
dataType: 'html',
error: function(items) {
console.error(items[0]);
loadingBarTrigger('done');
},
success: function(items) {
I think the easy and Simple way is to use the following code and add number of items in "items" array with their respective data.
let formData = {
'items': [{
'id': 36110175633573,
'quantity': 2
},
{
'id': 36110175623388,
'quantity': 1
}
]
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});

Display json data in angular

I have a post that runs on page load. I am trying to get data objects in json to use on my page and in my controller so I am trying to store the value in Angular scope.
I do not know where I have gone wrong but I cant get the value and when I console.log I get
angular.js:11655 ReferenceError: data is not defined
I want to store
c_name
max_slots
base_image
Summery of what I need
I need my array objects listed above stored in scope variables so that I may use them in my html and else where in my JavaScript controller.
My json
{data: Array(1), status: 200, config: {…}, statusText: "OK", headers: ƒ}
config
:
{method: "POST", transformRequest: Array(1), transformResponse: Array(1), url: "http://www.site.co.uk/one/two/getdata", date: {…}, …}
data
:
Array(1)
0
:
c_name
:
"ben"
d_text
:
[]
max_slots
:
2
resolution
:
(2) [1920, 1080]
slots
:
Array(3)
0
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 1}
1
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 2}
2
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 3}
length
:
3
__proto__
:
Array(0)
__v
:
0
_id
:
"59c92d6f45b79c8c110ee6ab"
__proto__
:
Object
My script I am trying to get the data
My JavaScript
$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log(response);
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = data.c_name;
$scope.max_slots = data.max_slots;
$scope.slot_image = data.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
Full response from console.log(data);
you have received the data
{data: Array(1), status: 200, config: {…}, statusText: "OK", headers: ƒ}
config
:
{method: "POST", transformRequest: Array(1), transformResponse: Array(1), url: "http://www.site.co.uk/one/two/getdata", date: {…}, …}
data
:
Array(1)
0
:
c_name
:
"ben"
d_text
:
[]
max_slots
:
2
resolution
:
(2) [1920, 1080]
slots
:
[{…}]
__v
:
0
_id
:
"59c92d6f45b79c8c110ee6ab"
__proto__
:
Object
length
:
1
__proto__
:
Array(0)
headers
:
ƒ (c)
status
:
200
statusText
:
"OK"
__proto__
:
Object
And a screen shot
I understood as you have to print JSON data for that I'm posting this answer, if you not expect this answer please post your question more clearly.
$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log(response); // if the response data is in json
console.log(angular.toJson(response)); // if the response data is in json
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = response.c_name;
$scope.max_slots = response.max_slots;
$scope.slot_image = response.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
var data = JSON.parse(response);
console.log('you have received the data ');
console.log(data);
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = data.c_name;
$scope.max_slots = data.max_slots;
$scope.slot_image = data.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
Replacing response with data should fix the issue.

Creating JSON string in AngularJS

I want to create a JSON string in the following format as below using AngularJS:
{
"userid": 100,
"fleetid": 506,
"comments": "This is a test comment",
"fleetcheckdate": "29/10/1976",
"options": [{
"fleetcheckid": "1",
"fleetcheckvalueid": "1"
}, {
"fleetcheckid": "2",
"fleetcheckvalueid": "1"
}, {
"fleetcheckid": "3",
"fleetcheckvalueid": "1"
}]
}
Where
"userid"
"fleetid"
"comments"
"fleetcheckdate"
are all separate values know to me.
For "options" I have a multi-dimensional array that stores the values for "fleetcheckid" and "fleetcheckvalueid" that I create as follows:
$scope.selectedRadioArray = [];
$scope.doSomething = function(fleetCheckItemID, fleetCheckID)
{
$scope.selectedIDS = [fleetCheckItemID, fleetCheckID];
$scope.selectedRadioArray.push($scope.selectedIDS);
console.log("Array: " + $scope.selectedRadioArray); // Prints e.g. 4,3,8,6,34,8
}
The doSomething() method is fired each time the user interacts with a button and this generates the 2 values "fleetcheckid" and "fleetcheckvalueid". In the example above the user has clicked the button 3 times. The button can be clicked any number of times.
How do I convert the information above into a JSON string as per the example that I can send to my Database via a $http.post()?
When sending information to the server via $http, it's generally a good idea to use JSON. Don't convert it to a string.
Simply format your payload like this:
var payload = {
userId: $scope.userId,
/* etc.... */
options: $scope.optionsArray
};
Then, when sending to the server, do this:
$http.post('path/to/api', payload, { headers: { /* etc... */ }}).then(successCallback).catch(errorCallback);
you can use in the $http someething like this
$http({
url: uri,
method: 'post',
data: angular.toJson(categoria),
headers: {
'Authorization': 'Bearer ' + token.data.access_token,
'Content-type': 'application/json'
}
}).then(function successCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
}, function errorCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
});
in this case `angularToJson` convert it on a JSON and send it in the body

Angular LocalStorage Service

i have passed a lot of time to get data from controller to another using Angularjs
i found this module https://github.com/grevory/angular-local-storage and i like it , i get object object issue [object Object]
my first controller code
$scope.getUserFunction = function () {
$scope.username;
$scope.password;
$scope.data;
//var data = {username: 'akram',password: "yes"};
$http({
method : 'POST',
url : 'http://localhost:8080/JersyBackEnd/resources/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.username+'&password='+$scope.password
//headers: {username: "toto",password:"toto"},
})
.then(function(data) {
// $window.location.href = "/about.html";
// $cookieStore.put('user',data);
localStorageService.set('users',JSON.stringify(data));
// console.log("Employee",x);
$scope.data = data;
console.log(data);
}, function (error) {
console.log(error)
});
};
and second controller code
$scope.getEmployee = function () {
//var cookie = $cookieStore.get('user');
//console.log("Employee"+cookie);
var users = JSON.parse(localStorageService.get('users'));
console.log("happiens"+users);
}
i get happiens[object Object] in console
1 . how to resolve this problem ?
2 . is this a good idea to get data from controller to another
and thanks :)
console.log("happiness", users);
Or
console.log("happiness", JSON.stringify(users));
OR
console.log("happiness" + JSON.stringify(users));
One of them will work.

How to post data with angular js to sql server

Thanks for all your input, but now I have more or less a similar problem, I have the data that needs to be stored in sql-server database, when I try to post it the data does not get written. Is my code structure correct?
self.CurrentDowntimeEvent = {
method: 'POST'
, url: 'someurl/test'
, data: {
DepartmentId: cookie
, CategoryId: -1
, Comment: ""
, DowntimeStart: "2014-07-07T10:00:00"
, DowntimeEnd: null
}
, headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
console.log(data);
}).error(function (data) {
});
$http is a service which should be injected into the controller, so you shouldn't need self. to reference it:
self.RecordsSave = function () {
for (var i = 0; i < self.Employees.length; i++) {
var employee = self.Employees[i];
var params = {
CompanyNumber: employee.ClockNumber,
Department: employee.DepartmentID,
Present: employee.Present,
Reason: employee.AbsentCode
};
$http.post(SAVE_EMPLOYEERECORDS, {
params: params
}).success(function (data) {
alert("testing");
});
}
};

Categories