I'm getting an xml answer from a server using jquery and I need to have one of its child nodes as a string to further work with it.
Here is my code:
function pollServer(dataObject) {
$.ajax({
type: "POST",
url: '/server.php',
data: dataObject,
success: function (data) {
$xmlDoc = $(data);
$listen = $xmlDoc.find('listen');
console.log($listen);
},
dataType: 'xml'
});
}
I already tried using (new XMLSerializer()).serializeToString(listen) but that gives me an empty string.
The following should work fine for XML:
var listen = $("listen", data)[0].outerHTML;
Related
I'm trying to use AJAX to gather search results from DuckDuckGo's Search API.
Here's the JavaScript I've written so far:
$.ajax({
type: 'GET',
url: 'https://api.duckduckgo.com/',
data: { q: myhomestate, format: 'json', pretty: 1 },
jsonpCallback: 'jsonp',
listLocation: "RelatedTopics",
dataType: 'text'
}).then(function (data) {
console.log(data);
});
}
The code works fine, but it just returns a big JSON object, and I don't know how to select any of its elements. Please help!
data = JSON.parse(data);
turns it into a normal JavaScript object. Then you can select elements like you would any other object.
e.g.
var heading = data.Heading;
var developer = data.meta.developer[0].name
First you need to convert JSON response into JSON Object, as shown below :
var jsonObj = JSON.parse(data);
Then you can access, it's fields as shown below :
console.log(jsonObj["RelatedTopics"]);
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.
var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "html",
success: function (data) {
var dataObj = data.replace(/"/g, '"');
console.log(dataObj);
}
});
I'm grabbing the contents of an HTML page, and the contents on that page is super simple. It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. This is all that's on that HTML page:
[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
Without replace the "'s, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array?
You can use JSON.parse
JSON.parse(dataObj);
You can parse the returned HTML fragment as JSON:
JSON.parse(dataObj);
Change "dataType" to "json" and it will convert it for you:
var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "json",
success: function (data) {
console.log(data);
}
});
If it is returning the " instead of ", then I would change the AJAX return page to make sure it is doing a proper JSON response.
I have code that makes an AJAX call to an MVC controller method and it'll work without a hitch if I do this:
var obj = '{"titlename":"whatever"}';
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
But if I do this:
var stringed="whatever"
var obj = '{"titlename":stringed}';
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
It craps out on me with an "invalid JSON primitive" error. I keep trying various single and double quote permutations, but they all keep giving me the same error. How can I insert a string variable into a JSON object?
Try this:
var stringed = "whatever";
var obj = '{"titlename": "' + stringed + '"}';
Also you may want to take a look at a JSON2 library, which can stringify your data automatically.
Why are you declaring your object as a String?
Have you tried doing:
var stringed="whatever";
var obj = {
"titlename":stringed
};
var obj = {"titlename":stringed};
This is probably what you need.
Try this:
var stringed="whatever";
var obj = {"titlename": stringed};
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
What you had was just a string that contained the the string "stringed", you need a object literal.
jQuery can take an object and it'll take care of sending the json string to the server instead.
You should do:
var stringed="whatever";
var obj_as_object = {titlename: stringed};
var obj_as_string = JSON.stringify(obj_as_object);
...
data: obj_as_string //This goes in your ajax call
With this, we're auto encoding the obj with JSON.
JSON.stringify will work in modern browsers. If you want support to an older browser (for example, IE6) you should use a library such as json2 from http://json.org.
Hope this helps. Cheers
This isn't a great way to do it but..
var stringed="whatever"
var obj = '{"titlename":'+stringed+'}';
Or
var obj = {
"titlename":stringed
}
When I tried to fetch the values from a JSON response, I stucked up. Here is my code
Code:
$.ajax({
url: 'checkvotes.php',
dataType: "json",
success: function(data) {
// want to fetch UP and DOWN variables from JSON here
}
});
AJAX Response from PHP
{"sample":[{"id":"1","message":"my message","up":"200","down":"34"}]}
$.ajax({
url: 'checkvotes.php',
dataType: "json",
success: function(data) {
var up = data.sample[0].up;
var down = data.sample[0].down;
}
});
Try data.sample[0].up and data.sample[0].down. If in doubt, use this JavaScript to emulate the call:
var data = {"sample":[{"id":"1","message":"my message","up":"200","down":"34"}]};
Run that in a debugger and examine data.
var up = data['sample'][0]['up'],
down = data['sample'][0]['down']
just print a console.log(data) to inspect your json