receiving json via ajax asp.net issue - javascript

I am trying to receive a json data using ajax asp.net.
i have got a web service with a web method -
[WebMethod]
public List<Song> GetSongListByMood(string Mood)
{
SongBL songbl = new SongBL();
return songbl.GetSongListByMoodBL(Mood);
}
and i have got the javascript code -
$(document).ready(function () {
var cssSelector = {
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
};
var playlist = [];
var options = {
swfPath: "./js",
supplied: "mp3"
};
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);
$("#slider a").click(function () {
var mood = $(this).text();
var xhr = new XMLHttpRequest();
var url = "AvironaService.asmx/GetSongListByMood";
xhr.open("POST", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var obj = JSON.parse(xhr.responseXML.text);
myPlaylist.playlist = obj;
}
};
var contentType = "application/x-www-form-urlencoded"
xhr.setRequestHeader("Content-Type", contentType);
var qs = 'Mood=' + mood;
xhr.send(qs);
});});
now basically what im trying to do is get the data from the server using ajax in json format and put the data in the playlist variable

You need to make a few changes.
Change your method to return a string instead of List<Song>.
add a using statement using System.Web.Script.Serialization.
Create an instance of JavaScriptSerializer and use that to serialize your object and return the results.
So...
using System.Web.Script.Serialization;
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string GetSongListByMood(string Mood)
{
SongBL songbl = new SongBL();
var jss = new JavaScriptSerializer();
return jss.Serialize(songbl.GetSongListByMoodBL(Mood));
}
Change your AJAX code to leverage the JQuery methods available:
$("#slider a").click(function () {
$.ajax({
"url" : "AvironaService.asmx/GetSongListByMood",
"type" : "post",
"data" : {"Mood" : $(this).text()},
"dataType" : "json"
"success" : function(data){
myPlaylist.playlist = data;
}
});
});

Related

JSON Object Access Value

This is my JSON response:
{
"2f2EdLjYHcTx4APbgnlvE2SCXQb2": {
"name": "test",
"latitute": 7.4866174,
"longitute": 80.3637889
},
"pJua8KSpMwSXiSlWJcDE4sEkOuZ2": {
"name": "akalanka",
"latitute": 7.4866198,
"longitute": 80.3638016
}
}
How can i access name, latitude and longitute in JavaScript?
I tried using this method, it shows data but i can't access the properties I need:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
xmlHttp.send();
var data=xmlHttp.responseText;
var x=[];
x=JSON.parse(xmlHttp.responseText);
// x=data.length;
console.log(x);
// latitute=x.latitute;
// longitute=x.longitute;
z=15;
myMap();
}
Two problems in the code:
1) You are using xmlHttp incorrectly.
You are sending the request but parsing the result directly (without waiting for the request to succeed).
xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
xmlHttp.send();
xmlHttp.onload = function () {
// Request finished. Do processing here.
};
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
2) You need to use the key to access the 'latitute'.
Object.keys(x).forEach(field => {
console.log(x[field].latitute);
console.log(x[field].longitute);
});
So it should look like this:
xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
xmlHttp.send();
xmlHttp.onload = function () {
var x = JSON.parse(xmlHttp.responseText);
Object.keys(x).forEach(field => {
console.log(x[field].latitute);
console.log(x[field].longitute);
});
};
First, please confirm that you already get responseText by using onreadystate method.
After that, please try with this.
var responseText = `{"2f2EdLjYHcTx4APbgnlvE2SCXQb2":{"name":"test","latitute":7.4866174,"longitute":80.3637889},"pJua8KSpMwSXiSlWJcDE4sEkOuZ2":{"name":"akalanka","latitute":7.4866198,"longitute":80.3638016}}`;
var x = JSON.parse(responseText);
console.log(x);
Object.keys(x).forEach(field => {
console.log(x[field].name);
});
Beware your properties are misspelled longitute, latitute... te? Should be de
I'd convert the nonstandard UID-as-keys to a simple Array.
Quick example using fetch API:
const myMap = (data) => {
console.log(`lat:${data.latitute}, lng:${data.longitute}`)
};
const fetchMapData = async () => {
const response = await fetch('https://jsbin.com/mijopocunu/js');
const json = await response.json();
const dataArr = Object.keys(json).map(k => (json[k].id = k, json[k]));
dataArr.forEach(myMap);
};
fetchMapData();

How to send an integer from ajax without jquery?

I am trying to send an integer called 'petadid' from this js to the django view called 'petadlikeview'. But it looks like the data is not going there in the view.If i print 'petadid' in the view, it shows 'None'. Can anyone please tell me what is wrong? I am new to ajax and django.
Here is my js:
<script>
$(document).ready(function(argument) {
$.ajaxSetup({cache:false});
var element = document.getElementById("likes");
var petadid = $(this).attr("data-petadid");
element.addEventListener("click",function(){
var req = new XMLHttpRequest();
req.open("POST",'/petadlike/')
req.onload = function(){
console.log(req.responseText);
console.log(petadid);
var data = JSON.parse(req.responseText);
}
req.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
var data = {
'petadid':petadid,
}
req.send(data);
});
});
</script>
And here is my django-view:
def petadlikeview(request):
print("vau")
if request.method=="POST":
print("vai")
petadid = request.POST.get('petadid')
print(petadid)
petad = PetAd.objects.get(pk=petadid)
like_count = petad.petadlikes_set.all().count()
like, created = petadlikes.objects.get_or_create(user=request.user,petad=petad)
print(created)
if created is False:
petadlikes.objects.get(user=request.user,petad=petad).delete()
like_count -= 1
liked = False
else:
like.save()
like_count += 1
liked = True
dict = {'like_count':like_count}
return JsonResponse(dict)
return HttpResponse(str(like_count)+' people have liked this')
else:
return HttpResponse('Bad Request')
XMLHttpRequest will not automatically convert an object to POST data as jQuery does, you need to create the URL-encoded string yourself.
var data = "petadid=" + encodeURIComponent(petadid);
Also
var petadid = $(this).attr("data-petadid");
should probably be
var petadid = $(element).attr("data-petadid");

How to access a JSON array directly from url

I am new to javascript and I have a Json Array in a url like below;
[{"year":2015,"month":4,"day":1,"num":0,"time":"2015-04-01","hour":0,"zone":3,"state1":2137,"state2":249,"state3":1810,"state4":30,"state5":0},....]
I want to access the state1 value and assign that value to the variable which I have.How can I do that?(Is parsing necessary or are there any methods there that we can directly access the JSON object in the URL).I am sorry if I asked anything wrong.
You can use jQuery getJSON() function :
$.getJSON(' localhost:8080/dataurl', function(data) {
//data is the JSON string
var jsonObj = JSON.parse(data);
});
Now, Below are the methods to parse the jsonObj to get the state1.
Using array map() method :
var jsonObj = [
{
"year":2015,
"month":4,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2137,
"state2":249,
"state3":1810,
"state4":30,
"state5":0
},
{
"year":2016,
"month":12,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2474,
"state2":250,
"state3":1811,
"state4":31,
"state5":0
}
];
var state1arr = jsonObj.map(function(item) {
return item.state1;
});
console.log(state1arr);
using for...in loop :
var jsonObj = [
{
"year":2015,
"month":4,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2137,
"state2":249,
"state3":1810,
"state4":30,
"state5":0
},
{
"year":2016,
"month":12,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2474,
"state2":250,
"state3":1811,
"state4":31,
"state5":0
}
];
var state1arr = [];
for (var i in jsonObj) {
state1arr.push(jsonObj[i].state1);
}
console.log(state1arr);
The data you have is array of objects and you need to loop to access each object and access the key using dot notation
Like this,
var app=[{"year":2015,"month":4,"day":1,"num":0,"time":"2015-04-01","hour":0,"zone":3,"state1":2137,"state2":249,"state3":1810,"state4":30,"state5":0}];
for(var i of app)
{
console.log(i.state1);
}
Just use the following JS Code:
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
You can now use the function to get the JSON contents from the url:
getJSON("<URL>").then(function(data) { // Replace <URL> With your URL
var jsondata = data.result; //store result in variable
// Your code here....///
/// Now you can access the json's data using jsondata variable: //
// jsondata[0].year will have the value of year key, jsondata[0].month will have month key and so on.... //
}, function(status) { //error detection....
alert('Something went wrong.');
});

AJAX - setting parent object's member variables from callback function

I'm developing a Javascript libraray which I want to use as follows.
var obj = new Lib().actionOne();
This call should populate "transcript" and "session" member variables in obj.
Then I want to call:
obj.actionTwo();
which will use populated "transcript" and "session" objects in the previous call.
Find below my library.
var xmlhttp = null;
function Lib() {
this.transcript = null;
this.session = null;
return this;
}
Lib.prototype = {
_initRequest : function() {
// create xmlhttp request here
},
_consumeService : function(callback) {
this._initRequest();
xmlhttp.open("GET", "THE URL", true);
var self = this;
xmlhttp.onreadystatechange = function(self) {
if(xmlhttp.readyState==4 && xmlhttp.status==200 ){
callback.call(self);
}
};
xmlhttp.send();
},
actionOne: function() {
var connUrl = "SOME URL";
this._consumeService(this._actionOneCallback);
return this;
},
_actionOneCallback : function() {
var jsonObj = JSON.parse(xmlhttp.responseText);
this.session = jsonObj.session
this.transcript = jsonObj.transcript;
this.isActionOneDone = true;
xmlhttp = null;
},
actionTwo : function() {
// use this.session and this.transcript
}
};
The issue is that actionOneCallback() function doest not populate 'obj' members though I pass 'self' reference to it. Therefore when I call 'obj.actionTwo();', obj's member variables are undefined. What is the workaround for this?

Save Json in Javascript variable

I'm studying javascript these days and I have question. I have variable that contain an url. I would like to save the content of the url pointed by my variable in another variable...
The first variable is something like:
var Link = "http://mysite.com/json/public/search?q=variabile&k=&e=1";
If I open the link I see something like:
{
"count": 1,
"e": 1,
"k": null,
"privateresult": 0,
"q": "gabriel",
"start": 0,
"cards": [
{
"__guid__": "cdf8ee96538c3811a6a118c72365a9ec",
"company": false,
"__title__": "Gabriel Butoeru",
"__class__": "entity",
"services": false,
"__own__": false,
"vanity_urls": [
"gabriel-butoeru"
]
}
]
}
How can I save the json content in another javascript variable?
You would need a simple AJAX request to get the contents into a variable.
var xhReq = new XMLHttpRequest();
xhReq.open("GET", yourUrl, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);
Please note that AJAX is bound by same-origin-policy, in case that URL is different this will fail.
You can use like this
var savings_data = JSON.stringify(your_json_object);
You can save json as object in this way
Reference : Json
var obj = {};
obj.name = "test";
obj.no = "1234";
I think this might help you, using jQuery... :)
$.ajax({
beforeSend: function() { DO HERE WHATEVER }, //Show spinner
complete: function() { DO HERE WHATEVER }, //Hide spinner
type: 'POST',
url: Link,
dataType: 'JSON',
success: function(data){
var data = data;
OR IF YOU WANT SEPARATE THE VALUES...
var count = data.count;
var e = data.e;
var k = data.k;
...
}
});
This example considers the state of the request and will allow you to access the data from the JSON format using the dot operator.
var request = new XMLHttpRequest();
request.open("GET", "mysite.com/json/public/search?q=variabile&k=&e=1", true);
request.setRequestHeader("Content-type", "application/json");
request.send();
request.onreadystatechange = function(){
if(request.ready == 4 && request.readyState == 200){
var response = request.responseText;
var obj = JSON.parse(response);
alert(obj.count); // should return the value of count (i.e Count = 1)
alert(obj.e); // should return the value of e (i.e. e = 1)
var count = obj.count; //store the result of count into your variable
var e = obj.e; //store the result of e into your variable
//...and so on
}
}

Categories

Resources