I'm using ajax to parse JSON data from a URL. I need to capture the parsed array into a variable. How would I go about this? Thanks
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also don't need to pass any data, as you're performing a GET request.
Hope this helps! :)
So I guess you are not sure about the ajax call, so lets break it..
Ajax call is a simply method to make a request to remote resource (Get/post/put...) the type of request (GET/POST) depends upon your need.
so if you have an endpoint that return simply data as in your case a simple get/post request is sufficient.
You can send addition data with request to get the data from endpoint (say id of resource (say person) whose other fields you want to get like name, age, address).
here is link for ajax request in jQuery
here is jQuery parse json parse json in jQuery
So for example:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can try something like: -
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});
Related
I'm working on a poll system. After the user submits their poll answer choice, it should return JSON with all answers so I can display them.
After submitting the AJAX form, it returns the JSON correctly like this:
[{"answer_1":0,"answer_2":1,"answer_3":0,"answer_4":0}]
But when I try to parse it, all answers return undefined.
This is how I parse it:
$("#poll-form").submit(function(event) {
var data = $("#poll-form").serialize();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: data,
success: function(response) {
var res = JSON.parse(response);
$(".poll-content").html("<h1>Answer:</h1>" + res.answer_1); // res.answer_1 returns undefined
}
});
event.preventDefault();
});
What am I doing wrong? Why is it returning undefined? All suggestions are welcome.
res is an array
res[0].answer_1
How can I do a AJAX request in ColdFusion?
I have my javascript:
function getdata(){
var formElements=document.getElementById("CFForm_1").elements;
var data=[];
for (var i=0; i<formElements.length; i++){
if(formElements[i].name == 'customersid')
data.push({'customersid':document.getElementById("customersid").value});
if(formElements[i].name == 'customerstoid')
data.push({'customerstoid':document.getElementById("customerstoid").value});
}
$.ajax(
{
type: "get",
url: "components/BillingCalc.cfc",
data: {
method:"ajaxGetTotalCost",
data: data.join()
},
dataType: "json",
success: function( objResponse ){
}
});
}
My component:
component displayName="Calc" {
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
I am getting the error: JSON parsing failure at character 2:'o' in [object Object],[object Object]
Does anyone knows how to do AJAX request in CF?
This function:
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
is not complete. It's at the stage where you have to call it from a ColdFusion page, not with javascript. That will enable you to see the results of the writedump(data) command to ensure it's what you expect. You have to add more code to the function to get it to produce a variable javascript can receive, and then return that variable to whatever is calling the function.
The issue is related to dataType attribute you are passing with $.ajax() method. dataType: "json" indicates your AJAX request is expecting JSON data as a response. But in your case you are simply returning DUMP of the deserialized JSON, which is HTML not JSON. So if you want it to work properly, then you need to return JSON data from your ColdFusion function. You can try this and see if it works.
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
return serializeJSON(data));
}
I have following ajax call
$.ajax({
type: "GET",
url: "../targeturl",
data : postdata,
contentType: 'application/json',
success: function(response, status, request) {
** in response im getting three sets which i wish to iterate
}
last few lines of controller methods are as follows:
JsonWrapper response = new JsonWrapper();
/*some lines to fetch data from db*/
response.addParam("vSet",vSet);
response.addParam("dSet",dSet);
return response;
Since I have never tried this before, please tell me know how to perform this. also let me know if question is not clear enough.
Using JQuery :
$.each(response.vSet, function(index, element) {
//process
});
Using Javascript :
for(var i=0;i<response.vSet.length;i++){
//process
}
If your response is valid Json, you can parse the response using javascripts built in function JSON.parse(). Then iterate over it as you like, depending on how you constructed your json in your response.
$.ajax({
type: "GET",
url: "../targeturl",
data : postdata,
contentType: 'application/json',
success: function(response, status, request) {
var json = JSON.parse(response).
//iterate over json by accessing the indices of json.
for(var i = 0; i < json.length; i++)
{
(..) //do stuff with json[i]
}
//or access json using the key values you specified in your response
json['vSet'] // or json.vSet.
console.log(json) //this will allow you to inspect your response after you parsed it to json.
}
So as the title suggests, I am having difficulty retrieving data from my database with these technologies. This is my current situation:
var username = $('#username').val();
var password = $('#password').val();
// For the sake of example this is a dummy IP
var url = 'http://55.55.55.55/dbfuncts.php?action=getuser&user=' + username;
// For debugging purposes I compare this object with the one I get with the ajax function
var obj1 = {
"name" : "Dave"
};
var obj = $.ajax({
url: url,
type: 'POST',
dataType: 'json'
});
The format of my JSON is supposed to be like this:
{"UserID":"User","Password":"User","Email":"User#questionmark.com","Fname":"Web","Lname":"User","isManager":"0"}
When I go to the URL I am able to see this JSON string in my browser.
Currently when debugging, I find that I keep getting the jqXHR object instead of the json object that I want.
How do I retrieve the information as a JSON from the database?
I don't think jQuery ajax call will return the result directly as you did (but I'm not sure).
I used to get result from ajax call by using callback function as below.
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(data) {
// data argument is the result you want
console.log(data);
}
});
Try this:
Place the url which gives the json data in the url column.
var jsonData = $.ajax({
url: '*',
dataType:"json",
async: false
}).responseText;
var parsed = JSON.parse(jsonData);
If this does not then try this:
var jsonData1 = $.ajax({
xhrFields: { withCredentials: true },
type:'GET',
url: '*',
dataType:"json",
crossDomain: true,
async: false
}).responseText;
var parsed1 = JSON.parse(jsonData1);
TRY 2:
Ok so try it with Spring MVC. Get the data from the database, and keep it in a url. As given in this link. Ckick Here And then use the above ajax call to access the data from the url.
I have a JSON URL that I need to grab the variables from and use them as jQuery stings. I've tried several different approaches and all of them are unsuccessful.
Approach 1
$.getJSON('http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get', function(data) {
alert(JSON.stringify(data))
});
Resilt
I receive an 200 OK message, but I do not get any data returned.
Approach 2
$.ajax({
url:"http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType:'jsonp',
success:function(data){
var obj = jQuery.parseJSON(data);
alert(obj.title);
}
});
Result
I receive on 200 OK but the obj value is NULL
Approach 3
$.getJSON("http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",function(ajaxresult){
window.artist = ajaxresult.track.artist;
});
Resilt
I receive an 200 OK message, but I do not get any data returned.
You didn't look with attention at the JSON object returned by the service.
What you're looking for is the data property of the returned object which is an array.
Something like this do work :
$.ajax({
url: "http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType: 'jsonp',
success: function (data) {
console.log(arguments);
alert(data.data[0].title);
}
});
JSFiddle to demo