Save Json in Javascript variable - javascript

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
}
}

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");

send multiple parameter using ajax and save data into database

send multiple parameter using ajax and save data into database....and in the case of packet i want value will remain unchange on form mean i don't want that my form reload so, how it is possible i'm a newbie please give your valuable suggestions
onsubmitbtn call on submit button
function onsubmitbtn(){
var packet = document.getElementById("packet").value;
var name = document.getElementById("name").value;
var number = document.getElementById("number").value;
var sub = document.getElementById("sub").value;
var zipcode = document.getElementById("zcode").value;
var city = document.getElementById("city").value;
var weight = document.getElementById("weight").value;
var data = "packet=" +packet+ "&name="+name+ "&number="+number+ "&sub="+sub+ "&zipcode="+zipcode+ "&city="+city+ "&weight="+weight;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
var response = request.responseText;
}
request.open("get", "PickUpInvertFormSubmit.jsp?"+data, true);
request.send();
}
i want to send multiple parameters in my ajax and save the value in my database. if the packet is more than one in that case i want that on submit but the value in input field will remain same
jsp code for insert data into database
String name = request.getParameter("name");
String[] splt = client.replaceAll("\\s+", "").split("\\|");
String number = request.getParameter("number");
String sub = request.getParameter("sub");
String zip = request.getParameter("zipcode");
int z = Integer.valueOf(zip);
String city = request.getParameter("city");
String pkt = request.getParameter("packet");
int p = Integer.valueOf(pcs);
String weight = request.getParameter("weight");
double w = Double.valueOf(weight);
Dbcon dbc = new Dbcon();
Connection con = dbc.ConnDb();
String query = "insert query"
+ "VALUES (?,?,?,?,?,?,?,CURRENT_DATE,CURRENT_DATE,CURRENT_TIMESTAMP)";
PreparedStatement psmt = null;
try {
psmt = con.prepareStatement(query);
psmt.setString(1, ....);
psmt.setString(2, .......);
psmt.setString(3, ........);
psmt.setInt(4, .......);
psmt.setString(5, .......);
psmt.setInt(6, ..........);
psmt.setDouble(7, .......);
psmt.executeUpdate();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
dbc.disconnect(null, null, null, psmt);
}
}
this code works perfectly when i use this code on action
onsubmit button event my form field get refreshed and no data save in database...
use this
function onsubmitbtn() {
var packet = document.getElementById("packet").value;
var name = document.getElementById("name").value;
var number = document.getElementById("number").value;
var sub = document.getElementById("sub").value;
var zipcode = document.getElementById("zcode").value;
var city = document.getElementById("city").value;
var weight = document.getElementById("weight").value;
$.ajax({
type: 'POST',
cache: false,
url: "PickUpInvertFormSubmit.jsp",
data: {
"packet": packet,
"name": name,
"number": number,
"sub": sub,
"zipcode": zipcode,
"city": city,
"weight": weight
},
success: function (data, textStatus, jqXHR) {
successMethod(data);
},
error: function (jqXHR, textStatus, errorThrown) {
errorMethod(errorThrown);
}
});
}
Your data can't be altered after submission and also can't be bookmarked.
you can also use alert("success: " + data); in success value of ajax function and same in error of the ajax method.
Using this, data is not appended to browser's URL and you don't have to modify your controller/jsp.
This method will make a call to URL in background and you can perform cleanup in the success method.
also import jQuery in head tag of your document as
<head>
<script type="text/javascript" src="jquery-3.2.1.js"></script>
</head>
You can download jQuery from here Download jQuery | jQuery
Hope this helps :)

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.');
});

receiving json via ajax asp.net issue

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;
}
});
});

Categories

Resources