JSON Data Not showing from to view after retrieving using ajax - javascript

I retrieve Json data from controller using ajax. But I am trying to show the result in a specific div and tried so many things but couldn't figure it out what I am doing wrong. I can see in console that it is getting the json Data but it is just not showing in the specific div.
Here is the Json Data -
Object
postage_result:
costs:
cost:{item: "Parcel Post", cost: "15.80"}
delivery_time:"Delivered in 4 business days"
service:"Parcel Post"
total_cost:"15.80"
Ajax Code-
<script>
$.ajax({
url: '/ShoppingCart/GetFreight',
type: 'GET',
success: function (response) {
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
$.each(response.postage_result, function (i, val) {
$("#cost").append(document.createTextNode(val.total_cost));
})
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
</script>
View Code -
<td>Freight =<div id="cost"> </div></td>
Please suggest How should I do it to work .

Related

How to get Google maps URL with a 'placeid' with AJAX?

I have a URL which I can open on browser and view the JSON data. The URL looks something like this:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE
Now when I try to access this with jQuery AJAX, I fail to get any results, instead I get an error.
My AJAX call looks some like this:
$.ajax({
url: https://maps.googleapis.com/maps/api/place/details/json,
data: {
'placeid': 'ChIJZeH1eyl344kRA3v52Jl3kHo',
'key': 'API_KEY_HERE'
},
dataType: 'json',
success: function(response) {
alert(JSON.stringify(response));
},
error: function(error) {
alert(JSON.stringify(error));
}
});
var API_KEY = api_key;
var placeid = placeid;
var API_URL = `https://maps.googleapis.com/maps/api/place/details/json?placeid=${placeid}&key=${API_KEY}`
$.getJSON(API_URL, {
tags: placeid,
tagmode: "any",
format: "json"
},
function(data) {
alert(data);
});
If I build it up correctly, this should be the way to send the data correctly to the api, using the placeid inside the url string together with the api_key.
Then you use a getJSON instead of json because I assume you want to get the place data? Assuming to what you're doing in the ajax you made.
Maybe explain further what you mean with how to get google maps url with place id? Hope it helps you out :)

Parse JSON data from API

I am new to working with Jquery JSON and API's(this being my first Stack question, so please bear with me). So I am trying to figure out a way in which Im hitting a API and it will return data(city name) in JSON which I have to display on my page in list form. But the cities should be updated and the page should display the city names dynamically.
Here is the fiddle link:
Fiddle File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST2</title>
</head>
<body>
<button>Submit</button>
<select id="list"></select>
</body>
</html>
<script type="text/javscript" src="jquery-3.1.0.js"></script>
<script type="text/javscript">
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('list', {
text: element.detail
}));
});
}
});
</script>
JSON FILE
[
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]
Requesting for your help, thanks in advance for those who contributed
Provided you receive data from API you can do what you want.
//...
success: function (data) {
$.each(data, function(index, element) {
//$('body').append($('list', {//no comment
// text: element.detail
//}));
//add cities to select id="list"
$('<option/>') //create option
.val(element.id) //set its value
.text(element.detail) //set text
.appendTo('#list'); //and append to the list
});//each
}
this is not a JSON object, its an array, are you sure it comes back like this? try to log it then do one of the following:
if it comes as a string write this
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
accepts: "application/json; charset=utf-8"
/* ... */
the accepts tells the server to send back json, hence you can get it as json. if it is still a string, write JSON.parse(data)
if it comes as an array like youve written, then there should be no problem, except that its an array not a json object. json should be an object not an array.
{results: [
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]}
something like this will make it a json file.
if it comes like this, then you should write: data.results to access the array you need.
You don't need to parse. JSON is JavaScript Object Notation. you can just asign data to variable and use it in your code like
success: function(result) {
var data = result;
data.forEach(function(data){
$('body').append($('list', {
text: element.detail
}));
}
console.log(data);
//in console you can see tyour data
Object {type: "form-focus", element: "#run"}

Why Viewbag not show in asp.net mvc view page?

I'm beginner in asp.net mvc,write this java script code for fetch any data from controller:
$.ajax({
url: '#Url.Action("CallService", "MyScore")',
type: 'GET',
dataType: 'json',
cache: false,
data: {
'id': 29
},
success: function(color) {
//alert(color);
},
error: function() {
alert('Error occured');
}
});
and write this action in controller:
[HttpGet]
public ActionResult CallService(string id)
{
var idNum = Convert.ToInt32(id);
string color = idNum.ToString();
ViewBag.Myfamily = "razzaqi";
return Json(color, JsonRequestBehavior.AllowGet);
}
in view page write this code:
<h1> Hello Dear #ViewBag.Myfamily</h1>
when i run the project <h1> Hello Dear #ViewBag.Myfamily</h1> not show me ,but i think show me this output:
Hello Dear razzaqi
You are returning JSON not ViewBag. You need to send the "razzaqi" to as part of JSON object. Set up HTML as
<h1> Hello Dear <span id='familyname'></span></h1>
Modify You controller to return myfamily as part of JSON object.
[HttpGet]
public ActionResult CallService(int id)
{
string color = id.ToString();
return Json(new {
color = color
myfamily = "razzaqi"
}, JsonRequestBehavior.AllowGet);
}
Consume the result like
$.ajax({
url: '#Url.Action("CallService", "MyScore")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': 29 },
success: function (data) {
$('#familyname').text(data.myfamily)
},
error: function () {
alert('Error occured');
}
});
The Viewbag object is filled into the view, server side when making the view. Your ajax call contacts the server asking about Json data after the view is already made.
So you are too late passing objects to your viewbag if you do it this way...
There are however some workarounds/solutions for this problem:
Let the Controller return the variable in the Json it's returning.
Simple, efficient way to get the data you need
Html helpers etc. Won't work however and sometimes you just need that horrible viewbag...
Reload a partialview when doing the ajax call.
Takes more time to implement, You'll have to create a new action and partialview.
Good when you want more content to change on the call and want to use html helpers etc.

How to read JSON file in angular js

I am working on a project where i have to read the product and display it on my HTML page
here is my Controller
app.controller('SecondCtrl', function($scope,srvShareCart ,srvShareData,srvAddtoCart,$http) {
$scope.product=[];
$scope.One=function(){
//alert($scope.ids);
$scope.ids= srvAddtoCart.getData();
for (var i=0; i<$scope.ids.length; i++){
$http.get("http://www.ilexsquare.com/JwelTech/wordpress/api.php?function=GetProduct&id="+$scope.ids[i])
.then(function (response) {
srvShareCart.addData(response.data);
});
$scope.cart = srvShareCart.getData();
console.log($scope.cart);
}
}
and here is My HTML page
<div ng-controller="SecondCtrl">
<ul> <li class=oxy-list__item ng-repeat="d in cart">{{d.title}}</li></ul></div>
here is a working API
this the Example API link
it's giving me an error in response.data which is coming as undefined.what is the issue in it ?
I am getting the output but it's not in a form of array.. how do i Add those products in array. i have tried $scope.carts.push($scope.products); but its not storing as an array
The response content type sent from the API is plain text instead of application/json
Try like this.
$http.get({
url: "http://www.ilexsquare.com/JwelTech/wordpress/api.php?function=GetProduct&id="+$scope.ids[i],
dataType: "json",
success: function (response) {
srvShareCart.addData(response.data);
},
error: function (msg) {
alert(msg.d);
}
});

Posting to facebook wall using graph api

I'm trying to post a text with image to facebook wall using graph api.
I'm using following code snippet for this.
var body = {
message : 'this is a test message',
image : 'http://someurltoimage.png'
};
FB.api(
"/me/feed",
"POST",
{
"object": {
"message": body.message,
"picture": body.image
}
},
function (response) {
if (response && !response.error) {
//process when success
}
}
);
But I'm getting following error code.
error: Object
code: 100
error_subcode: 1349125
message: "Invalid parameter"
type: "FacebookApiException"
There's no document for this error.
Any advise will be appreciated.
"I'm trying to post a text with image to facebook wall using graph api."
You are using /feed, to upload a photo you have to use /photos call
You are sending an invalid parameter object which contains your parameters, to Facebook, the API doesn't know that your parameter Object is an object (I know, too many objects here, in another way, you're sending an object within an object
To solve all this, replace me/feed with me/photos and the 3rd argument (your object) with the body
var body = {
message : 'this is a test message',
url: 'http://someurltoimage.png'
};
FB.api("/me/photos",
"POST",
body,
function (response) {
if (response && !response.error) {
//process when success
}
}
);

Categories

Resources